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
Spaces: one design, one Machines list, a flat thread, valid sign-ins, remote-agent onboarding (#6108)
ddupont0bcfa0653b6e
diff --git a/apps/cua-spaces-desktop/src/bridge/agent-keys.ts b/apps/cua-spaces-desktop/src/bridge/agent-keys.tsindex 75c5230a8b..62c8cd04e4 100644--- a/apps/cua-spaces-desktop/src/bridge/agent-keys.ts+++ b/apps/cua-spaces-desktop/src/bridge/agent-keys.ts@@ -11,6 +11,7 @@ import type { Handlers } from "./host";export function agentKeysMethods({ model }: BridgeContext): Handlers {return {"agentKeys.list": () => model.agents.keys.call("agent_keys.list"),+ "agentKeys.check": () => model.agents.keys.call("agent_keys.check"),"agentKeys.set": (args) => {const call: Record<string, unknown> = { provider: string(args, "provider"), value: string(args, "value") };const env = optionalString(args, "env");diff --git a/apps/cua-spaces-desktop/src/bridge/host-parts.ts b/apps/cua-spaces-desktop/src/bridge/host-parts.tsindex 08bca35a8f..cd83e14fe0 100644--- a/apps/cua-spaces-desktop/src/bridge/host-parts.ts+++ b/apps/cua-spaces-desktop/src/bridge/host-parts.ts@@ -125,7 +125,7 @@ export function hostParts(ctx: BridgeContext): HostParts {if (system) {model.devices.presence = (reason) => system.confirmPresence(reason);model.devices.notify = (prompt) =>- system.notify({ id: `device-${prompt.deviceId}`, title: prompt.notifyTitle, body: prompt.notifyBody, route: "/settings/devices" });+ system.notify({ id: `device-${prompt.deviceId}`, title: prompt.notifyTitle, body: prompt.notifyBody, route: "/machines" });}const onboarding = new OnboardingStore(path.join(path.dirname(model.settingsPath), "onboarding.json"));diff --git a/apps/cua-spaces-desktop/src/bridge/join-with-code.ts b/apps/cua-spaces-desktop/src/bridge/join-with-code.tsindex 6c1f89a1cf..fdf25742ca 100644--- a/apps/cua-spaces-desktop/src/bridge/join-with-code.ts+++ b/apps/cua-spaces-desktop/src/bridge/join-with-code.ts@@ -106,7 +106,7 @@ export function joinMethods(ctx: BridgeContext, run: typeof runCua = runCua): Haif (!code) throw Failure.badArgs("code: 12 letters and digits, like K7QM-4XPB-2RHD");const named = typeof args.relay === "string" && args.relay.trim() ? args.relay.trim() : null;if (named && !/^https?:\/\//i.test(named)) throw Failure.badArgs("relay: an http(s) URL");- if (!supervisor) throw Failure.unsupported("This build has no bundled cua to join with a code. Use the install command on this computer.");+ if (!supervisor) throw Failure.unsupported("This build has no bundled cua to join with a code. Use the install command on this machine.");const result = await run(supervisor.cua, joinArgs(code, named ?? linkRelay(input)), { ...env });if (!result.ok) throw Failure.failed(failureText(result.stderr, result.status));await model.host.refresh();diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 7cf7be3c41..ab13ee0c8a 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -20,7 +20,7 @@ export const METHODS = ["agents.status", "agents.connect", "agents.disconnect", "agents.signInStart", "agents.signInWait", "agents.start", "agents.message","agents.detail", "agents.readFile", "agents.restoreFile", "agents.addRoutine", "agents.setRoutine","agents.removeRoutine", "agents.allowComputer", "agents.revokeComputer",- "agentKeys.list", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell",+ "agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell","spaces.add", "clouds.status", "clouds.test", "clouds.connect", "clouds.disconnect", "clouds.approve","teleport.catalog", "teleport.entryForPath", "teleport.windows", "teleport.remoteWindows","teleport.icon", "teleport.thumbnail", "teleport.plan", "teleport.run", "teleport.sites",diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.tsindex bbedc57745..15cfae3571 100644--- a/apps/cua-spaces-desktop/src/bridge/settings.ts+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts@@ -192,7 +192,7 @@ export function settingsMethods(ctx: BridgeContext): Handlers {case "global-shortcut": {// The keys that bring the app forward from any app (Mac). The option is the accelerator.const system = parts().system;- if (!system?.setGlobalShortcut) throw Failure.failed("This computer has no shortcut to change.");+ if (!system?.setGlobalShortcut) throw Failure.failed("This machine has no shortcut to change.");try {system.setGlobalShortcut(option);} catch (e) {diff --git a/apps/cua-spaces-desktop/src/bridge/space-ready.ts b/apps/cua-spaces-desktop/src/bridge/space-ready.tsindex e5acd1f063..b6f77f0e6b 100644--- a/apps/cua-spaces-desktop/src/bridge/space-ready.ts+++ b/apps/cua-spaces-desktop/src/bridge/space-ready.ts@@ -14,7 +14,7 @@ const OS_WORDS: Record<string, string> = { macos: "macOS ", linux: "Linux ", win/** What the notification says: no OS word for a Space whose OS is not known, "this Mac" only on a Mac. */export function spaceReadyNote(space: { id: string; name: string; os: string }, platform: NodeJS.Platform): SystemNote {- const where = platform === "darwin" ? "this Mac" : "this computer";+ const where = platform === "darwin" ? "this Mac" : "this machine";return {id: `space-ready-${space.id}`,title: `${space.name} is ready`,diff --git a/apps/cua-spaces-desktop/src/media-bridge.ts b/apps/cua-spaces-desktop/src/media-bridge.tsindex 898cbb111e..0da72e8ca1 100644--- a/apps/cua-spaces-desktop/src/media-bridge.ts+++ b/apps/cua-spaces-desktop/src/media-bridge.ts@@ -280,7 +280,7 @@ export function createStreamOpener(deps: StreamDeps) {const wsUrl = deps.testStreamUrl.replaceAll("{id}", encodeURIComponent(spaceId)).replaceAll("{tier}", tier);return { wsUrl, expiresAt: null };}- if (!(await deps.hasCua())) throw new StreamUnavailableError("Live video needs cua on this computer.");+ if (!(await deps.hasCua())) throw new StreamUnavailableError("Live video needs cua on this machine.");const json = JSON.stringify(openMediaRequest(tier, window));let e = await endpoint();try {diff --git a/apps/cua-spaces-desktop/src/model/agents.ts b/apps/cua-spaces-desktop/src/model/agents.tsindex 5042412985..4b5b493d37 100644--- a/apps/cua-spaces-desktop/src/model/agents.ts+++ b/apps/cua-spaces-desktop/src/model/agents.ts@@ -384,7 +384,7 @@ export function agentKeysInput(report: Json | null, error: string | null): AppAgexpired: k.expired === true,})).filter((k) => k.env !== "");- const unavailable = report?.available === false ? (typeof report.unavailable === "string" ? report.unavailable : "this computer can't keep keys") : undefined;+ const unavailable = report?.available === false ? (typeof report.unavailable === "string" ? report.unavailable : "this machine can't keep keys") : undefined;return { keys, unavailable, error: error ?? undefined };}diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.tsindex 86b5858283..580be263a1 100644--- a/apps/cua-spaces-desktop/src/model/app-model.ts+++ b/apps/cua-spaces-desktop/src/model/app-model.ts@@ -617,7 +617,7 @@ export class AppModel {// A create this app asked another computer for already has its own pending row.this.creatingElsewhere = (list.creating ?? []).filter((c) => !this.spaces.some((s) => s.name === c.name && (s.host === c.machineId || this.native.appCreatesIsPending(s.id))));// Your other computers could not be read: their rows are the last known ones.- this.rosterError = list.notice ? "Could not reach your other computers. Their Spaces may be out of date." : null;+ this.rosterError = list.notice ? "Could not reach your other machines. Their Spaces may be out of date." : null;if (this.selectedSpaceId === null) {const first = this.sidebar.selectedId;if (first) this.selectedSpaceId = first;diff --git a/apps/cua-spaces-desktop/src/model/host-failure.ts b/apps/cua-spaces-desktop/src/model/host-failure.tsindex 7fc30dcb94..07d87cbefe 100644--- a/apps/cua-spaces-desktop/src/model/host-failure.ts+++ b/apps/cua-spaces-desktop/src/model/host-failure.ts@@ -22,7 +22,7 @@ export const SIGN_IN_LABEL = "Sign In";/** What the app calls the computer it runs on, mid-sentence. */export function thisComputer(platform: NodeJS.Platform): string {if (platform === "darwin") return "this Mac";- return platform === "win32" ? "this PC" : "this computer";+ return platform === "win32" ? "this PC" : "this machine";}const SYSTEM: Partial<Record<NodeJS.Platform, string>> = { darwin: "macOS", win32: "Windows", linux: "Linux" };diff --git a/apps/cua-spaces-desktop/src/model/host.ts b/apps/cua-spaces-desktop/src/model/host.tsindex 4d1ce46ed2..6d8856beb3 100644--- a/apps/cua-spaces-desktop/src/model/host.ts+++ b/apps/cua-spaces-desktop/src/model/host.ts@@ -18,7 +18,7 @@ import { sleep } from "./time";/** Why relay setup could not get an account token (`HostSetupAuthError`); worded as "Sign in to Cua". */export class HostSetupAuthError extends Error {- static readonly signedOut = "Not signed in to Cua: sign in to set up this computer for access.";+ static readonly signedOut = "Not signed in to Cua: sign in to set up this machine for access.";static readonly signInNotFinished = "Not signed in to Cua: the sign-in did not finish.";constructor(readonly reason: "signedOut" | "signInNotFinished") {super(HostSetupAuthError[reason]);@@ -140,7 +140,7 @@ export class HostModel {*/async setUp(request: AppHostSetupRequest): Promise<void> {const host = this.host;- if (!host) throw new Error("This computer can't be set up for access in this build");+ if (!host) throw new Error("This machine can't be set up for access in this build");try {const status = request.mode === "relay" ? await this.setUpRelay(host, request) : await this.setup(host, request, undefined);this.apply(status);diff --git a/apps/cua-spaces-desktop/src/model/windows-runtime.test.ts b/apps/cua-spaces-desktop/src/model/windows-runtime.test.tsindex 113799b26f..0b0b19abb2 100644--- a/apps/cua-spaces-desktop/src/model/windows-runtime.test.ts+++ b/apps/cua-spaces-desktop/src/model/windows-runtime.test.ts@@ -31,7 +31,7 @@ describe("windowsRuntimeAdvice", () => {it("says virtualization is off and offers nothing to install", () => {const a = windowsRuntimeAdvice({ ...CLEAN, virtualization: "off" }, IDLE, 0);expect(a.reason).toMatch(/virtualization is turned off/);- expect(a.reason).toMatch(/another computer/);+ expect(a.reason).toMatch(/another machine/);expect(a.fix).toBeNull();});diff --git a/apps/cua-spaces-desktop/src/model/windows-runtime.ts b/apps/cua-spaces-desktop/src/model/windows-runtime.tsindex 12ec52091a..33dbd9ea87 100644--- a/apps/cua-spaces-desktop/src/model/windows-runtime.ts+++ b/apps/cua-spaces-desktop/src/model/windows-runtime.ts@@ -83,7 +83,7 @@ export function windowsRuntimeAdvice(facts: WindowsRuntimeFacts, phase: FixPhaseif (facts.virtualization === "off") {return {reason:- "This PC can't run local Spaces: virtualization is turned off. Turn on Intel VT-x or AMD-V (SVM) in the PC's firmware (BIOS/UEFI) settings, or run Spaces on another computer.",+ "This PC can't run local Spaces: virtualization is turned off. Turn on Intel VT-x or AMD-V (SVM) in the PC's firmware (BIOS/UEFI) settings, or run Spaces on another machine.",fix: null,};}diff --git a/apps/cua-spaces-desktop/test/agents-fixtures.ts b/apps/cua-spaces-desktop/test/agents-fixtures.tsindex e42971cfb5..1e223467d5 100644--- a/apps/cua-spaces-desktop/test/agents-fixtures.ts+++ b/apps/cua-spaces-desktop/test/agents-fixtures.ts@@ -91,6 +91,7 @@ export class FakeAgentKeysTools {this.calls.push([tool, args]);switch (tool) {case "agent_keys.list":+ case "agent_keys.check":break;case "agent_keys.set": {const provider = String(args.provider ?? "");diff --git a/apps/cua-spaces-desktop/test/agents.test.ts b/apps/cua-spaces-desktop/test/agents.test.tsindex ad6eed441f..1bb6096e94 100644--- a/apps/cua-spaces-desktop/test/agents.test.ts+++ b/apps/cua-spaces-desktop/test/agents.test.ts@@ -452,6 +452,10 @@ describe.skipIf(!built)("agents", () => {const { bridge } = makeBridge();const listed = (await call(bridge, "agentKeys.list")) as { keys: { env: string }[] };expect(listed.keys.map((k) => k.env)).toEqual(["OPENAI_API_KEY"]);+ // The check is the daemon's `agent_keys.check` (the providers are asked there), answered like the list.+ const checked = (await call(bridge, "agentKeys.check")) as { keys: { env: string }[] };+ expect(keys.calls.at(-1)).toEqual(["agent_keys.check", {}]);+ expect(checked.keys.map((k) => k.env)).toEqual(["OPENAI_API_KEY"]);const set = await call(bridge, "agentKeys.set", { provider: "anthropic", value: "sk-ant-test-0000" });expect(keys.calls.at(-1)).toEqual(["agent_keys.set", { provider: "anthropic", value: "sk-ant-test-0000" }]);expect(JSON.stringify(set)).not.toContain("sk-ant");diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.tsindex 99188b0deb..80330d2cac 100644--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts@@ -508,7 +508,7 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()await model.devices.refresh();const notes = system.notes.filter((n) => n.id.startsWith("device-"));expect(notes.map((n) => n.id)).toEqual(["device-dev_work", "device-dev_old"]);- expect(notes[0]).toMatchObject({ route: "/settings/devices" });+ expect(notes[0]).toMatchObject({ route: "/machines" });expect(notes[0]!.title.length).toBeGreaterThan(0);started.stop();});diff --git a/apps/cua-spaces-desktop/test/host-failure.test.ts b/apps/cua-spaces-desktop/test/host-failure.test.tsindex c650440368..4d45feace6 100644--- a/apps/cua-spaces-desktop/test/host-failure.test.ts+++ b/apps/cua-spaces-desktop/test/host-failure.test.ts@@ -4,7 +4,7 @@// A failed host setup or This machine button in words (the SwiftUI app's// HostSetupFailureTests): the kind from the raw error, a title and message// that never carry a URL or the raw error, which stays whole as Details, and-// Sign In or Retry. On Windows and Linux the words name the computer.+// Sign In or Retry. On Windows and Linux the words name the machine.import { describe, expect, it } from "vitest";import { classify, presentHostFailure } from "../src/model/host-failure";@@ -106,15 +106,15 @@ describe("host setup failures", () => {expect(presentHostFailure("relay: invalid account token: ExpiredSignature", "darwin", "signedOut").actionLabel).toBe("Sign In");});- it("names the computer and its system on Windows and Linux", () => {+ it("names the machine and its system on Windows and Linux", () => {expect(presentHostFailure("odd", "win32").title).toBe("Couldn’t set up this PC for access");- expect(presentHostFailure("odd", "linux").title).toBe("Couldn’t set up this computer for access");+ expect(presentHostFailure("odd", "linux").title).toBe("Couldn’t set up this machine for access");const svc = presentHostFailure("schtasks /Create failed: access denied", "win32");expect(svc.kind).toBe("service");expect(svc.message).toContain("Windows didn’t start");expect(svc.message).toContain("Run as administrator");expect(svc.message).not.toContain("restart this PC");- expect(presentHostFailure("systemctl --user start failed", "linux").message).toContain("restart this computer");- expect(presentHostFailure("relay: HTTP 401", "linux").message).toBe("Your Cua account isn’t signed in on this computer. Sign in, then try again.");+ expect(presentHostFailure("systemctl --user start failed", "linux").message).toContain("restart this machine");+ expect(presentHostFailure("relay: HTTP 401", "linux").message).toBe("Your Cua account isn’t signed in on this machine. Sign in, then try again.");});});diff --git a/apps/cua-spaces-desktop/test/space-ready.test.ts b/apps/cua-spaces-desktop/test/space-ready.test.tsindex f8a90abb2e..c0b2ee9223 100644--- a/apps/cua-spaces-desktop/test/space-ready.test.ts+++ b/apps/cua-spaces-desktop/test/space-ready.test.ts@@ -24,9 +24,9 @@ describe("the Space ready note", () => {expect(spaceReadyNote({ id: "a", name: "a", os: "unknown" }, "darwin").body).toBe("A fresh computer inside this Mac. Your agent can use it now.");});- it("says this computer where the app does not run on a Mac", () => {+ it("says this machine where the app does not run on a Mac", () => {for (const platform of ["win32", "linux"] as const) {- expect(spaceReadyNote({ id: "a", name: "a", os: "linux" }, platform).body).toBe("A fresh Linux computer inside this computer. Your agent can use it now.");+ expect(spaceReadyNote({ id: "a", name: "a", os: "linux" }, platform).body).toBe("A fresh Linux computer inside this machine. Your agent can use it now.");}});diff --git a/apps/cua-spaces-macos/README.md b/apps/cua-spaces-macos/README.mdindex 0c52fb81c9..4ce8366ce7 100644--- a/apps/cua-spaces-macos/README.md+++ b/apps/cua-spaces-macos/README.md@@ -119,7 +119,7 @@ at the matching page (`MainUIRouter`): a launch (the first run at`/onboarding?due=1` while it is due; never at login), the Dock icon, the menubar item, the notch, File, New Space (⌘N), the View menu, Help, GettingStarted, ⌘⇧Space and the app's notifications (a Space that came up: its page;-a device asking to join: Settings, Devices; an agent: Agents). A Space's+a machine asking to be added: Machines; an agent: Agents). A Space'sdesktop opens in its own native window (video stays native).There is no native main window and no switch back: the "Use classic UI"diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swiftindex 1f340fb715..4818d6c633 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift@@ -409,7 +409,7 @@ public enum AppEnvironment {/// The Settings page a `settings-*` start view names.static func settingsRoute(_ view: String) -> MainUIRoute {switch view {- case "settings-devices": return .path("/settings/devices")+ case "settings-devices": return .path("/machines")case "settings-about": return .path("/settings/about")case "settings-experiments": return .path("/settings/experiments")default: return .settings@@ -495,7 +495,7 @@ public enum AppEnvironment {case "device-approval", "device-enroll", "device-enroll-code":// The web Devices page has the enroll and approval sheets.await model.devices.refresh()- web(.path("/settings/devices"))+ web(.path("/machines"))case "space":model.select("local:aurora")web(.space("local:aurora"))diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swiftindex 29a064125a..c70a31c433 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift@@ -449,7 +449,7 @@ public final class DevicesModel {/// A row's second line: platform and state, then when it was last seen.public func rowDetail(_ r: AppDeviceRow) -> String {guard let seen = r.lastSeen else { return r.detail }- return "\(r.detail) \u{b7} \(view.labels.lastSeen) \(relativeText(seen))"+ return "\(r.detail), \(view.labels.lastSeen.lowercased()) \(relativeText(seen))"}// MARK: - Refreshdiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swiftindex 5b3bbdb61b..c568b20768 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift@@ -111,11 +111,11 @@ struct MainUIRouter {}/// The page a click on one of the app's notifications opens: a Space that- /// came up (its page), a device asking to join (Settings, Devices, with- /// its approval), an agent's answer or request (Agents), else Spaces.+ /// came up (its page), a machine asking to be added (Machines, where+ /// it waits with Add machine and Not me), an agent's answer or request (Agents), else Spaces.static func route(forNotification id: String) -> MainUIRoute {if let spaceId = SpaceReadyNote.spaceId(fromIdentifier: id) { return .space(spaceId) }- if id.hasPrefix("device-") { return .path("/settings/devices") }+ if id.hasPrefix("device-") { return .path("/machines") }if id.hasPrefix("agent-") { return .agents }return .home}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex bf5847dd4c..d7685df97c 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -81,6 +81,8 @@ extension WebUIBridge {// Settings, Connectors: the daemon's agent_keys methods (the key travels// once, in agentKeys.set's arguments; answers never carry one).case "agentKeys.list": return try await model.agentKeys.call("agent_keys.list")+ // The providers are asked whether the saved API keys still work (answers cached for minutes).+ case "agentKeys.check": return try await model.agentKeys.call("agent_keys.check")case "agentKeys.set":var keyArgs: [String: Any] = ["provider": try string(args, "provider"), "value": try string(args, "value")]if let env = args["env"] as? String, !env.isEmpty { keyArgs["env"] = env }diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex 6a4a524e0d..9f91a2517c 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -81,7 +81,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {// A persistent agent's Memory, Routines and Access (`PersistentModel`)."agents.detail", "agents.readFile", "agents.restoreFile", "agents.addRoutine", "agents.setRoutine","agents.removeRoutine", "agents.allowComputer", "agents.revokeComputer",- "agentKeys.list", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell",+ "agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell",// New Space's address form and Connect a cloud, Teleport and Share,// Cua Volume, Settings and Notifications, a Space's detail and This// machine (WebUIBridge+Pages.swift).diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUICapture.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUICapture.swiftindex 7993385a3e..28e3a9fa27 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUICapture.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUICapture.swift@@ -13,7 +13,7 @@ import WebKit/// `CUA_SPACES_OFFSCREEN=1` too, nothing shows on screen (`OffscreenRun`).extension WebUIWindowController {static let captureRoutes = ["onboarding", "spaces", "machines", "agents", "keyvault", "notifications", "settings",- "settings/about", "settings/devices"]+ "settings/about"]/// The base page routes resolve under: the window may have opened at/// another route (the first run, at `/onboarding`).diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swiftindex 240d8d8c0d..7d793995db 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift@@ -18,7 +18,7 @@ final class FakeAgentKeysTools: AgentsToolRunning, @unchecked Sendable {func agentsTool(_ tool: String, _ args: [String: Any]) async throws -> Any {calls.append((tool, args))switch tool {- case "agent_keys.list": break+ case "agent_keys.list", "agent_keys.check": breakcase "agent_keys.set":let provider = args["provider"] as? String ?? ""let env = provider == "anthropic" ? "ANTHROPIC_API_KEY" : provider == "openai" ? "OPENAI_API_KEY" : args["env"] as? String ?? ""@@ -102,7 +102,7 @@ struct AgentKeysTests {}@Test func theWebBridgeRoutesAgentKeysToTheDaemon() {- for m in ["agentKeys.list", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell"] {+ for m in ["agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell"] {#expect(WebUIBridge.methods.contains(m))}}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex 7aa074af0b..7994b41711 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -248,7 +248,7 @@ struct BridgeContractTests {("agents.setRoutine", ["id": "R1", "enabled": false]), ("agents.removeRoutine", ["id": "R1"]),("agents.allowComputer", ["agent": "ada", "machine": "relay:0123"]),("agents.revokeComputer", ["agent": "ada", "machine": "relay:0123"]),- ("agentKeys.list", [:]), ("agentKeys.set", ["provider": "anthropic", "value": "sk-ant-test-0000"]),+ ("agentKeys.list", [:]), ("agentKeys.check", [:]), ("agentKeys.set", ["provider": "anthropic", "value": "sk-ant-test-0000"]),("agentKeys.remove", ["env": "ANTHROPIC_API_KEY"]),("agentKeys.shell", [:]), ("agentKeys.fromShell", ["env": "ANTHROPIC_API_KEY"]),("clouds.status", [:]), ("clouds.test", ["target": ["provider": "aws", "region": "us-west-2"]]),diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swiftindex 9fcf7e4cc0..67b74f1914 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift@@ -66,9 +66,9 @@ struct DevicesTests {await m.refresh()#expect(announced.count == 2, "a device asks once per launch")#expect(m.view.thisDevice.kind == .enrolled)- #expect(m.thisDeviceText(m.view.thisDevice) == "Enrolled until Feb 8, 2027")+ #expect(m.thisDeviceText(m.view.thisDevice) == "Trusted until Feb 8, 2027")let studio = m.view.rows.first { $0.id == "dev_studio" }!- #expect(m.rowDetail(studio) == "Linux \u{b7} Enrolled \u{b7} re-verify in 12 days \u{b7} Last seen 3 hours ago")+ #expect(m.rowDetail(studio) == "Linux, Trusted, check again in 12 days, last seen 3 hours ago")#expect(m.view.recent.first?.text == "MacBook Pro opened build-box")}@@ -82,7 +82,7 @@ struct DevicesTests {#expect(presence.asked.isEmpty, "Approve needs the whole code")m.setCode("k7qxm2rp")await m.approve()- #expect(presence.asked == ["approve \u{201c}Work laptop\u{201d} for your Cua account"])+ #expect(presence.asked == ["add \u{201c}Work laptop\u{201d} to your Cua account"])#expect(fixture.calls.isEmpty, "no presence, no relay call")#expect(m.approvalView?.error == "Approval was cancelled")#expect(m.approvalView?.busy == false)@@ -123,7 +123,7 @@ struct DevicesTests {await m.deny()#expect(fixture.calls == ["revoke:dev_work"])m.openApproval(deviceId: "dev_old", in: .settings)- #expect(m.approvalView?.denyLabel == "Not Now")+ #expect(m.approvalView?.denyLabel == "Not now")await m.deny()#expect(fixture.calls == ["revoke:dev_work"], "Not Now calls nothing")#expect(m.approval == nil)@@ -139,7 +139,7 @@ struct DevicesTests {"(ids in `cua devices ls`)"await m.approve()#expect(m.approvalView?.error == "The code expired.")- #expect(m.approvalView?.approveLabel == "Approve by ID")+ #expect(m.approvalView?.approveLabel == "Add machine")#expect(m.approvalView?.canApprove == true)fixture.failApprove = nilawait m.approve()diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachineAccessTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachineAccessTests.swiftindex a73d7abd55..68ab7c34b2 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachineAccessTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachineAccessTests.swift@@ -149,9 +149,9 @@ struct MachineAccessTests {@Test func notEnrolledPendingAndExpiredListMachinesWithConnectGreyedOut() async throws {for (e, kind, status) in [- (MachinesFixture.Enrollment.never, AppEnrollmentKind.needsEnrollment, "Not enrolled"),- (.pending, .waiting, "Waiting for approval"),- (.expired, .due, "Re-verification due"),+ (MachinesFixture.Enrollment.never, AppEnrollmentKind.needsEnrollment, "Not trusted yet"),+ (.pending, .waiting, "Waiting to be added"),+ (.expired, .due, "Needs a quick check"),] {let m = await MachinesFixture.model(rows: MachinesFixture.rows(reachable: false), enrollment: e)let notice = try #require(m.devices.accessNotice)diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachinesViewTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachinesViewTests.swiftindex 98f5405826..2a2ffa86d8 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachinesViewTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachinesViewTests.swift@@ -142,11 +142,14 @@ struct MachinesViewTests {// A device of its own leaves the account by revoking it.let work = view.machines.first { $0.name == "Work laptop" }#expect(work?.remove?.device == "dev_work")- #expect(work?.remove?.label == "Remove from account")- #expect(work?.line == "Signed-in device, not shared")- #expect(view.groups.first { $0.id == "devices" }?.ids.contains("dev_work") == true)+ #expect(work?.remove?.label == "Revoke")+ #expect(work?.line == "Signed in, not sharing")+ // One list: no separate group for it.+ #expect(view.groups.first { $0.id == "devices" } == nil)+ #expect(view.groups.contains { $0.ids.contains("dev_work") })// No Space actions on a machine: its Spaces only lead to the Space.- #expect(view.machines.allSatisfy { $0.newSpace.label == "New Space here" })+ #expect(view.machines.filter { $0.line != "Signed in, not sharing" }.allSatisfy { $0.newSpace.label == "New Space here" })+ #expect(work?.newSpace.label == "")let bridge = WebUIBridge(model: m, allowedOrigins: [])let answer = bridge.machines()["view"] as? [String: Any]diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swiftindex 9bd96e5849..21f0bce36d 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift@@ -68,7 +68,7 @@ struct MainUIRouteTests {@Test func aNotificationOpensItsPage() {let ready = SpaceReadyNote.identifierPrefix + "local:aurora"#expect(MainUIRouter.route(forNotification: ready) == .space("local:aurora"))- #expect(MainUIRouter.route(forNotification: "device-abc").webPath == "/settings/devices")+ #expect(MainUIRouter.route(forNotification: "device-abc").webPath == "/machines")#expect(MainUIRouter.route(forNotification: "agent-42") == .agents)#expect(MainUIRouter.route(forNotification: "other") == .home)}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TipsTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TipsTests.swiftindex afc01699a5..f1628b87a8 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TipsTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TipsTests.swift@@ -19,7 +19,7 @@ struct TipsTests {#expect(AppModel.sidebarTip(machinesOnline: 1, tips: none) == nil)let tip = AppModel.sidebarTip(machinesOnline: 2, tips: none)#expect(tip?.id == "on-auto")- #expect(tip?.text == "New Spaces can go to whichever computer has room.")+ #expect(tip?.text == "New Spaces can go to whichever machine has room.")#expect(tip?.code == "cua create --on auto")#expect(tip?.action.value == "cua create --on auto")#expect(tip?.action.doneLabel == "Copied")diff --git a/apps/cua-spaces-web/README.md b/apps/cua-spaces-web/README.mdindex 7d0d787d50..a02bc6b6b9 100644--- a/apps/cua-spaces-web/README.md+++ b/apps/cua-spaces-web/README.md@@ -61,8 +61,7 @@ CUA_WEBUI_DIST=$PWD/../cua-spaces-web/dist scripts/build-app.sh debugCUA_SPACES_START_VIEW=webui ".build/app/Cua Spaces.app/Contents/MacOS/CuaSpacesMac"```-In the app, this is Settings > Experiments > "New UI (preview)" (off by-default), then File > "Open New UI (preview)" (⇧⌘U). A debug build with+The app opens this UI as its only window. A debug build with`CUA_WEBUI_DEV=1` loads this app's dev server instead. The page runs in`webkit` mode against the app's own view models (see`src/bridge/README.md`). `CUA_SPACES_WEBUI_CAPTURE=<dir>` saves every route,diff --git a/apps/cua-spaces-web/e2e/agent-keys.ts b/apps/cua-spaces-web/e2e/agent-keys.tsindex 33599be73e..eb97531e0d 100644--- a/apps/cua-spaces-web/e2e/agent-keys.ts+++ b/apps/cua-spaces-web/e2e/agent-keys.ts@@ -2,18 +2,17 @@// Copyright (c) 2026 Cua AI, Inc./**- * Screen checks for the `agent-keys` flow (Settings, Connectors, Account keys): each section,+ * Screen checks for the `agent-keys` flow (Settings, Connectors, Providers): each section,* sheet and Remove question the replay reached goes on the real screen* through `window.__cuaParity.showAgentKeys`, and the screen must show the* core's words. Then a key is added and removed for real on the demo host,* and the key never shows up in the page.*/-import { expect, type Locator, type Page } from "@playwright/test";+import { expect, type Page } from "@playwright/test";import type { ParityCheckpoint } from "../src/bridge/parity";import type { AgentKeysCheckpoint } from "../src/bridge/parity-agent-keys";-import { KEYS_ADD_OTHER_BUTTON, KEYS_OTHER_HELP, KEYS_TITLE, plainKeysIntro } from "../src/lib/settings-copy";type Of<K extends AgentKeysCheckpoint["kind"]> = Extract<AgentKeysCheckpoint, { kind: K }>;@@ -28,53 +27,22 @@ const unique = <K extends AgentKeysCheckpoint["kind"]>(cps: ParityCheckpoint[],});};-const texts = (l: Locator) => l.evaluateAll((els) => els.map((el) => (el.textContent ?? "").trim()));-const attrs = (l: Locator, name: string) => l.evaluateAll((els, n) => els.map((el) => el.getAttribute(n) ?? ""), name);-/** A key the checks type; it must never be drawn. */const TYPED = "sk-ant-test-0000";-/**- * Account keys are the classic Connectors page (the new design's Providers- * are the `connectors` flow): this flow checks them with the new design off- * on this device, as a person who hasn't turned it on sees them.- */-async function classicConnectors(page: Page): Promise<void> {- await page.evaluate(() => localStorage.setItem("cua.flag.spaces_redesign", "0"));- await page.reload();- await page.waitForFunction(() => window.__cuaParity !== undefined);- expect(await page.evaluate(() => window.__cuaParity!.coreStatus), "the wasm core loaded").toBe("ready");-}-export async function checkAgentKeys(page: Page, checkpoints: ParityCheckpoint[]): Promise<number> {let checked = 0;- await classicConnectors(page);+ await page.goto("/settings/connectors?bridge=demo&parity");+ await page.waitForFunction(() => window.__cuaParity !== undefined);+ expect(await page.evaluate(() => window.__cuaParity!.coreStatus), "the wasm core loaded").toBe("ready");for (const { input, view } of unique(checkpoints, "agent-keys")) {await page.evaluate((i) => window.__cuaParity!.showAgentKeys(i), input);const step = `Settings, Connectors with ${input.keys.map((k) => k.env).join(", ") || "no keys"}${view.notice ? " (notice)" : ""}`;- const rows = page.locator("[data-agent-key-row]");- await expect.poll(() => attrs(rows, "data-agent-key-row"), { message: step }).toEqual(view.rows.map((r) => r.env));- expect(await texts(page.locator("[data-agent-key-title]")), step).toEqual(view.rows.map((r) => r.title));- expect(await texts(page.locator("[data-agent-key-status]")), step).toEqual(view.rows.map((r) => r.status));- expect(await texts(page.locator("[data-agent-key-detail]")), step).toEqual(view.rows.map((r) => r.detail));- expect(await texts(page.locator("[data-agent-key-action]")), step).toEqual(view.rows.map((r) => r.actionLabel));- expect(await texts(page.locator("[data-agent-key-remove]")), step).toEqual(view.rows.flatMap((r) => (r.removeLabel ? [r.removeLabel] : [])));- // The date is the page's; the label before it is the core's.- const added = await texts(page.locator("[data-agent-key-added]"));- expect(added.length, step).toBe(view.rows.filter((r) => r.addedMs !== null).length);- for (const a of added) expect(a.startsWith(`${view.addedLabel} `), step).toBe(true);- await expect(page.locator("[data-agent-keys-intro]"), step).toHaveText(plainKeysIntro(view.intro));- // The page says Account keys where the core says Agents; the rest of the words are the core's.- await expect(page.locator("[data-agent-keys-title]"), step).toHaveText(KEYS_TITLE);- await expect(page.locator("[data-agent-key-add-other]"), step).toHaveText(KEYS_ADD_OTHER_BUTTON);- await expect(page.locator("[data-agent-key-other-help]"), step).toHaveText(KEYS_OTHER_HELP);- if (view.notice) await expect(page.locator("[data-agent-keys-notice]"), step).toContainText(view.notice);- else await expect(page.locator("[data-agent-keys-notice]"), step).toHaveCount(0);- for (const b of await page.locator("[data-agent-key-action], [data-agent-key-add-other]").all()) {- if (view.canEdit) await expect(b, step).toBeEnabled();- else await expect(b, step).toBeDisabled();- }+ // The Providers group draws the core's view of the same keys: the add button follows canEdit.+ await expect(page.locator("[data-connectors-providers]"), step).toBeVisible();+ if (view.canEdit) await expect(page.locator("[data-agent-key-add-other]"), step).toBeEnabled();+ else await expect(page.locator("[data-agent-key-add-other]"), step).toBeDisabled();checked++;}@@ -121,21 +89,21 @@ export async function checkAgentKeys(page: Page, checkpoints: ParityCheckpoint[]checked++;}- // For real on the demo host: add an Anthropic key, then remove it.+ // For real on the demo host: add another company's key, then remove it.await page.goto("/settings/connectors?bridge=demo");- const anthropic = page.locator('[data-agent-key-row="ANTHROPIC_API_KEY"]');- await expect(anthropic.locator("[data-agent-key-status]")).toHaveText("Not set");- await anthropic.locator("[data-agent-key-action]").click();+ await page.locator("[data-agent-key-add-other]").click();const sheet = page.locator("[data-agent-key-sheet]");await expect(sheet.locator("[data-agent-key-save]")).toBeDisabled();+ await sheet.locator("[data-agent-key-name]").fill("ACME_API_KEY");await sheet.locator("[data-agent-key-value]").fill(TYPED);await sheet.locator("[data-agent-key-save]").click();await expect(sheet).toHaveCount(0);- await expect(anthropic.locator("[data-agent-key-status]")).toHaveText("•••• 0000");+ const acme = page.locator('[data-agent-key-row="ACME_API_KEY"]');+ await expect(acme).toContainText("•••• 0000");expect(await page.content(), "the key is never drawn").not.toContain(TYPED);- await anthropic.locator("[data-agent-key-remove]").click();+ await acme.getByRole("button", { name: "Remove" }).click();await page.getByRole("alertdialog").getByRole("button", { name: "Remove" }).click();- await expect(anthropic.locator("[data-agent-key-status]")).toHaveText("Not set");+ await expect(acme).toHaveCount(0);checked++;return checked;}diff --git a/apps/cua-spaces-web/e2e/flows.ts b/apps/cua-spaces-web/e2e/flows.tsindex 9275e6db89..7b90b37562 100644--- a/apps/cua-spaces-web/e2e/flows.ts+++ b/apps/cua-spaces-web/e2e/flows.ts@@ -24,7 +24,6 @@ export type ParityScreen =| "settings/about"| "settings/advanced"| "settings/connected-apps"- | "settings/devices"| "notifications"| "machines"| "agents"@@ -64,7 +63,7 @@ export const FLOW_PLAN: Record<string, FlowPlan> = {"create-progress": { status: "run", screen: "spaces" },"create-stages": { status: "run", screen: "spaces" },"create-retry": { status: "run", screen: "spaces" },- devices: { status: "run", screen: "settings/devices" },+ devices: { status: "run", screen: "machines" },"driver-card": { status: "run", screen: "settings/connected-apps" },"share-sheet": { status: "run", screen: "share" },"agents-page": { status: "run", screen: "agents" },diff --git a/apps/cua-spaces-web/e2e/parity.spec.ts b/apps/cua-spaces-web/e2e/parity.spec.tsindex 1e6975d787..2097cb706e 100644--- a/apps/cua-spaces-web/e2e/parity.spec.ts+++ b/apps/cua-spaces-web/e2e/parity.spec.ts@@ -45,7 +45,6 @@ const PATHS: Record<ParityScreen, string> = {"settings/about": "/settings/about","settings/advanced": "/settings/advanced","settings/connected-apps": "/settings/connectors",- "settings/devices": "/settings/devices",notifications: "/notifications",machines: "/machines",agents: "/agents/all",diff --git a/apps/cua-spaces-web/e2e/playwright.config.ts b/apps/cua-spaces-web/e2e/playwright.config.tsindex 28181e8a1c..264eecedd8 100644--- a/apps/cua-spaces-web/e2e/playwright.config.ts+++ b/apps/cua-spaces-web/e2e/playwright.config.ts@@ -42,9 +42,6 @@ export default defineConfig({cwd: "..",url: `http://localhost:${PORT}`,reuseExistingServer: !process.env.CI,- // The flows run on the new design (`spaces_redesign`); the classic pages- // keep their own tests in src/legacy/__tests__.- env: { VITE_CUA_FLAG_SPACES_REDESIGN: process.env.VITE_CUA_FLAG_SPACES_REDESIGN ?? "1" },timeout: 60_000,},});diff --git a/apps/cua-spaces-web/e2e/settings-checks.ts b/apps/cua-spaces-web/e2e/settings-checks.tsindex d41eb8f75d..725feeb6f5 100644--- a/apps/cua-spaces-web/e2e/settings-checks.ts+++ b/apps/cua-spaces-web/e2e/settings-checks.ts@@ -14,7 +14,7 @@ import { expect, type Locator, type Page } from "@playwright/test";import type { ParityCheckpoint } from "../src/bridge/parity";import type { SettingsCheckpoint } from "../src/bridge/parity-settings";import type { SettingsRow } from "../src/bridge/contracts/host";-import { LAUNCH_HELP, LAUNCH_LABEL, lastChecked, plainDevice, plainDeviceSentence, plainStorage } from "../src/lib/settings-copy";+import { LAUNCH_HELP, LAUNCH_LABEL, lastChecked, plainStorage } from "../src/lib/settings-copy";import { checkAgentKeys } from "./agent-keys";type Of<K extends SettingsCheckpoint["kind"]> = Extract<SettingsCheckpoint, { kind: K }>;@@ -116,7 +116,7 @@ async function checkAbout(page: Page, checkpoints: ParityCheckpoint[]): Promise<return states.length;}-/* ---- Devices --------------------------------------------------------------- */+/* ---- Machines: this machine's trust, the machines waiting, the enroll sheet ---------- */async function checkDevices(page: Page, checkpoints: ParityCheckpoint[]): Promise<number> {let checked = 0;@@ -126,30 +126,25 @@ async function checkDevices(page: Page, checkpoints: ParityCheckpoint[]): Promislast = cp;const { input, now, view: v } = cp;await page.evaluate(([i, n]) => window.__cuaParity!.settings.showDevices(i, n), [input, now] as const);- const step = `Devices: ${v.thisDevice.title}`;- if (v.banner) await expect(page.locator("[data-banner-text]"), step).toHaveText(plainDeviceSentence(v.banner.text));- else await expect(page.locator("[data-devices-banner]"), step).toHaveCount(0);- await expect(page.locator("[data-this-device-status]"), step).toHaveAttribute("data-this-device-status", v.thisDevice.kind);- await expect(page.locator("[data-this-device-status]"), step).toContainText(plainDevice(v.thisDevice.title));- await expect(page.locator("[data-this-device-enroll]"), step).toHaveCount(v.thisDevice.actionLabel ? 1 : 0);- await expect.poll(() => attrs(page.locator("[data-device-row]"), "data-device-row"), { message: step }).toEqual(v.rows.map((r) => r.id));- expect(await texts(page.locator("[data-device-title]")), step).toEqual(v.rows.map((r) => r.title));- const details = await texts(page.locator("[data-device-detail]"));- v.rows.forEach((r, i) => expect(details[i], `${step}: ${r.id}`).toContain(plainDevice(r.detail)));- for (const r of v.rows) {- const row = page.locator(`[data-device-row="${r.id}"]`);- await expect(row.locator("[data-device-approve]"), `${step}: ${r.id} Approve`).toHaveCount(r.actions.includes("approve") ? 1 : 0);- await expect(row.locator("[data-device-menu]"), `${step}: ${r.id} menu`).toHaveCount(r.actions.some((a) => a === "rename" || a === "revoke") ? 1 : 0);- }- expect(await texts(page.locator("[data-recent-text]")), step).toEqual(v.recent.map((a) => plainDeviceSentence(a.text)));- expect(await attrs(page.locator("[data-unconfirmed-machine]"), "data-unconfirmed-machine"), step).toEqual(v.unconfirmedMachines.map((m) => m.id));+ const step = `Machines: ${v.thisDevice.title}`;+ // This machine's page says what the core says under Details: its trust, and what to do about it.+ const toggle = page.locator("[data-machine-details-toggle]");+ if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();+ await expect(page.locator("[data-machine-trust]"), step).toHaveAttribute("data-machine-trust", v.thisDevice.kind);+ await expect(page.locator("[data-machine-trust-status]"), step).toContainText(v.thisDevice.title);+ await expect(page.locator("[data-machine-trust-action]"), step).toHaveCount(v.thisDevice.actionLabel ? 1 : 0);+ if (v.banner) await expect(page.locator("[data-machine-trust-text]"), step).toHaveText(v.banner.text);+ else await expect(page.locator("[data-machine-trust-text]"), step).toHaveCount(0);+ // The machines waiting to be added are the top group.+ const waiting = [...v.unconfirmedMachines.map((m) => m.id), ...v.approvals.map((a) => a.deviceId)];+ await expect.poll(() => attrs(page.locator("[data-pending-machine]"), "data-pending-machine"), { message: step }).toEqual(waiting);checked++;} else if (cp.kind === "enroll" && last) {const { state, view: v } = cp;await page.evaluate(([i, n, s]) => window.__cuaParity!.settings.showDevices(i, n, { enroll: s }), [last.input, last.now, state] as const);const sheet = page.locator("[data-enroll]");const step = `Enroll sheet, ${state.phase}`;- await expect(sheet.locator("[data-enroll-title]"), step).toHaveText(plainDeviceSentence(v.title));+ await expect(sheet.locator("[data-enroll-title]"), step).toHaveText(v.title);expect(await attrs(sheet.locator("[data-enroll-option]"), "data-enroll-option"), step).toEqual(v.options.map((o) => o.method));await expect(sheet.locator("[data-enroll-code]"), step).toHaveCount(v.code ? 1 : 0);if (v.code) await expect(sheet.locator("[data-enroll-code]"), step).toHaveText(v.code);@@ -160,22 +155,6 @@ async function checkDevices(page: Page, checkpoints: ParityCheckpoint[]): Promisawait expect(sheet.locator("[data-enroll-back]"), step).toHaveCount(v.backLabel ? 1 : 0);await expect(sheet.locator("[data-enroll-close]"), step).toHaveText(v.closeLabel);checked++;- } else if (cp.kind === "approve" && last) {- const { state, view: v } = cp;- await page.evaluate(([i, n, s]) => window.__cuaParity!.settings.showDevices(i, n, { approve: s }), [last.input, last.now, state] as const);- const sheet = page.locator("[data-approve]");- const step = `Approval sheet for ${state.name}, code "${state.code}"${state.busy ? ", busy" : ""}`;- await expect(sheet.locator("[data-approve-title]"), step).toHaveText(plainDeviceSentence(v.title));- await expect(sheet.locator("[data-approve-message]"), step).toHaveText(plainDeviceSentence(v.message));- await expect(sheet.locator("[data-approve-code]"), step).toHaveCount(v.needsCode ? 1 : 0);- if (v.needsCode) await expect(sheet.locator("[data-approve-code]"), step).toHaveValue(v.code);- if (v.error) await expect(sheet.locator("[data-approve-error]"), step).toHaveText(v.error);- else await expect(sheet.locator("[data-approve-error]"), step).toHaveCount(0);- await expect(sheet.locator("[data-approve-submit]"), step).toHaveText(v.approveLabel);- if (v.canApprove) await expect(sheet.locator("[data-approve-submit]"), step).toBeEnabled();- else await expect(sheet.locator("[data-approve-submit]"), step).toBeDisabled();- await expect(sheet.locator("[data-approve-deny]"), step).toHaveText(v.denyLabel);- checked++;}}return checked;diff --git a/apps/cua-spaces-web/e2e/settings-tab-layout.spec.ts b/apps/cua-spaces-web/e2e/settings-tab-layout.spec.tsindex a507e5ea16..f55022c361 100644--- a/apps/cua-spaces-web/e2e/settings-tab-layout.spec.ts+++ b/apps/cua-spaces-web/e2e/settings-tab-layout.spec.ts@@ -14,7 +14,6 @@ const TABS = [["Account", "/settings"],["General", "/settings/general"],["Connectors", "/settings/connectors"],- ["Trusted machines", "/settings/devices"],["Advanced", "/settings/advanced"],["About", "/settings/about"],] as const;diff --git a/apps/cua-spaces-web/package.json b/apps/cua-spaces-web/package.jsonindex 1f5e785e8c..3a2610929b 100644--- a/apps/cua-spaces-web/package.json+++ b/apps/cua-spaces-web/package.json@@ -16,7 +16,7 @@"contract": "scripts/bridge-contract.sh","contract:shapes": "UPDATE_BRIDGE_SHAPES=1 vitest run src/bridge/__tests__/contract.test.ts","parity": "node scripts/build-core-wasm.mjs && playwright test -c e2e/playwright.config.ts",- "parity:electron": "node scripts/build-core-wasm.mjs && VITE_CUA_FLAG_SPACES_REDESIGN=${VITE_CUA_FLAG_SPACES_REDESIGN:-1} vite build && (cd ../cua-spaces-desktop && rm -rf dist-electron && npx tsdown && node scripts/check-channels.mjs) && PARITY_HOST=electron playwright test -c e2e/playwright.config.ts",+ "parity:electron": "node scripts/build-core-wasm.mjs && vite build && (cd ../cua-spaces-desktop && rm -rf dist-electron && npx tsdown && node scripts/check-channels.mjs) && PARITY_HOST=electron playwright test -c e2e/playwright.config.ts","screenshots": "node scripts/screenshots.mjs","perf": "node scripts/perf.mjs","scale": "node scripts/scale-bench.mjs"diff --git a/apps/cua-spaces-web/scripts/scale-bench.mjs b/apps/cua-spaces-web/scripts/scale-bench.mjsindex 7dbb8718b6..383d3a7f44 100644--- a/apps/cua-spaces-web/scripts/scale-bench.mjs+++ b/apps/cua-spaces-web/scripts/scale-bench.mjs@@ -35,7 +35,7 @@ if (!has("--no-build")) {["node", ["scripts/build-core-wasm.mjs"]],["npx", ["vite", "build", "--logLevel", "warn"]],]) {- const r = spawnSync(cmd, a, { cwd: root, stdio: ["ignore", "ignore", "inherit"], env: { ...process.env, VITE_CUA_FLAG_SPACES_REDESIGN: "1" } });+ const r = spawnSync(cmd, a, { cwd: root, stdio: ["ignore", "ignore", "inherit"], env: process.env });if (r.status !== 0) process.exit(r.status ?? 1);}}diff --git a/apps/cua-spaces-web/scripts/screenshots.mjs b/apps/cua-spaces-web/scripts/screenshots.mjsindex 03c5f107e7..ac07c155c9 100644--- a/apps/cua-spaces-web/scripts/screenshots.mjs+++ b/apps/cua-spaces-web/scripts/screenshots.mjs@@ -16,7 +16,7 @@ import { chromium } from "@playwright/test";const root = fileURLToPath(new URL("..", import.meta.url));const outDir = process.env.OUT_DIR ?? `${root}docs/screenshots`;-const ROUTES = ["spaces", "machines", "agents", "volume", "keyvault", "settings", "settings/devices", "settings/experiments", "settings/about", "notifications", "onboarding"];+const ROUTES = ["spaces", "machines", "agents", "volume", "keyvault", "settings", "settings/experiments", "settings/about", "notifications", "onboarding"];// Pages under a parameter: [path, file name].const DETAIL_ROUTES = [[`spaces/${encodeURIComponent("relay:mac-mini/qa-windows")}`, "space-detail"],@@ -137,13 +137,13 @@ async function newSpaceSteps(theme) {await context.close();}-/** Devices' approval sheet, then General with Storage (the Cua Volume experiment on). */+/** A machine waiting to be added ("Add this machine?"), then General with Storage (the Cua Volume experiment on). */async function settingsStates(page, theme) {- await page.goto(`${base}/settings/devices`, { waitUntil: "networkidle" });- await page.locator('[data-device-row="dev_work"] [data-device-approve]').click();+ await page.goto(`${base}/machines`, { waitUntil: "networkidle" });+ await page.locator('[data-pending-machine="dev_work"] button').first().click();+ await page.locator('[data-pending-detail="dev_work"]').waitFor();await page.waitForTimeout(300);- await page.screenshot({ path: `${outDir}/settings-devices-approve-${theme}.png` });- await page.keyboard.press("Escape");+ await page.screenshot({ path: `${outDir}/machines-add-this-machine-${theme}.png` });await page.goto(`${base}/settings/experiments`, { waitUntil: "networkidle" });// The demo starts with Cua Volume on (the Volume page's demo); turn it on only if it's off.const volumeSwitch = page.locator('[data-setting-row="experiment:cua_volume"] [data-slot="switch"]');diff --git a/apps/cua-spaces-web/src/__tests__/agent-failure.test.tsx b/apps/cua-spaces-web/src/__tests__/agent-failure.test.tsxindex 0bc76794b2..34e565ff96 100644--- a/apps/cua-spaces-web/src/__tests__/agent-failure.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/agent-failure.test.tsx@@ -18,6 +18,8 @@ stubBrowserApis();const q = (s: string) => document.querySelector<HTMLElement>(s);const qa = (s: string) => [...document.querySelectorAll<HTMLElement>(s)];const path = `/spaces/${encodeURIComponent(DEMO_THREAD_SPACE)}`;+/** The failed agent's reply (its own row: the one with a Connect), named by what it says. */+const failureReply = (who: string) => qa("[data-entry]").find((e) => e.querySelector("[data-failure-connect]") && e.textContent?.includes(who));const host = { failsCreates: false, listsGhost: false, demo: { threadAuthFailed: true } };describe("an agent that is not connected", () => {@@ -36,7 +38,9 @@ describe("an agent that is not connected", () => {expect(claude.querySelector("[data-task-chip]")).toBeNull();const own = claude.querySelector(":scope > [data-entry]")!;expect(own.querySelector("[data-task-chip]")).toBeNull();- const reply = claude.querySelector("[data-task-replies] [data-entry]")!;+ // Flat: the reply is its own row after the task, not inside it.+ expect(claude.querySelector("[data-task-replies]")).toBeNull();+ const reply = failureReply("Claude")!;expect(reply.querySelector("[data-failure-connect]")).not.toBeNull();expect(reply.textContent).toContain("I can't reach Claude yet. Connect Claude, then try again.");expect(reply.textContent).not.toMatch(/401|authentication_error|OAuth/);@@ -52,8 +56,7 @@ describe("an agent that is not connected", () => {await mountApp(path, host);const reply = await waitFor(() => {- const t = qa('[data-task-state="failed"]').find((x) => x.textContent?.includes("@claude hi"));- const r = t?.querySelector("[data-task-replies] [data-entry]");+ const r = failureReply("Claude");expect(r).toBeTruthy();return r as HTMLElement;},@@ -71,7 +74,7 @@ describe("an agent that is not connected", () => {expect(reply.querySelector("[data-failure-copy]")).not.toBeNull();});- it("shows a failed member's reason whole in the member list", async () => {+ it("says one word for a failed member in the member list, and keeps the whole error under Show details", async () => {await mountApp(path, host);const row = await waitFor(() => {@@ -82,7 +85,16 @@ describe("an agent that is not connected", () => {{ timeout: 5000 },);const caption = row.querySelector<HTMLElement>("[data-member-caption]")!;+ // A short word, never the raw error.expect(caption.textContent).toBe("Not connected");- expect(caption.className).not.toContain("truncate");+ expect(row.textContent).not.toMatch(/401|OAuth|authentication/i);+ const details = q("[data-member-details] [data-failure-details]");+ expect(details).not.toBeNull();+ await act(async () => {+ fireEvent.click(details!);+ });+ const message = q("[data-member-details] [data-failure-message]")!;+ expect(message.className).toContain("select-text");+ expect(message.textContent!.length).toBeGreaterThan(20);});});diff --git a/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx b/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsxindex 6e80057d86..4573dbca02 100644--- a/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx@@ -1,7 +1,7 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-// Ask first with the redesign: Start goes straight to the Space being made,+// Ask first: Start goes straight to the Space being made,// and the job is its thread's first message, @mentioning the agent. When the// agent can't be woken (Claude Code with no Anthropic sign-in) the message// is still posted, with "Claude Code isn't connected yet" and Connect under@@ -141,7 +141,7 @@ describe.skipIf(!wasmBuilt)("notes only you see", () => {});});-describe.skipIf(!wasmBuilt)("@ any agent in a Space (redesign)", () => {+describe.skipIf(!wasmBuilt)("@ any agent in a Space ", () => {it("offers the agents that can start here and adds one on send", async () => {setFlagOverride("spaces_ask_first_home", null);const calls: { op: string; args: Record<string, unknown> }[] = [];diff --git a/apps/cua-spaces-web/src/__tests__/ask-first-start-failed.test.tsx b/apps/cua-spaces-web/src/__tests__/ask-first-start-failed.test.tsxindex ba21dd66e4..87b5e6ad25 100644--- a/apps/cua-spaces-web/src/__tests__/ask-first-start-failed.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/ask-first-start-failed.test.tsx@@ -31,8 +31,6 @@ beforeEach(() => {localStorage.clear();resetAskTasks();setFlagOverride("spaces_ask_first_home", true);- // Ask first on its own: its task page (with the redesign too, see ask-first-in-space.test.tsx).- vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");});async function pickThisMac() {@@ -54,7 +52,7 @@ describe.skipIf(!wasmBuilt)("This Mac as a task's computer (real routes, wasm coit("defaults to a new Linux computer, and This Mac asks once, then starts on this Mac's Space id", async () => {await mountApp("/home", HOST);await screen.findByText("What do you want to do?");- expect(document.querySelector('[data-picker="where"]')!.textContent).toContain("A new Linux computer");+ expect(document.querySelector('[data-picker="where"]')!.textContent).toContain("New Space");await pickThisMac();await screen.findByText("Work on this Mac?");expect(screen.getByText(/Claude Code will work directly on this Mac, with your files and apps\. It can't be undone by throwing the computer away\./)).toBeTruthy();@@ -65,8 +63,8 @@ describe.skipIf(!wasmBuilt)("This Mac as a task's computer (real routes, wasm coawait waitFor(() => expect(document.querySelector('[data-picker="where"]')!.textContent).toContain("This Mac"));await startJob("Tidy my Downloads folder");const id = askTasks()[0]!.id;- await waitFor(() => expect(askTask(id)?.runId).toBeTruthy(), { timeout: 5000 });- expect(askTask(id)).toMatchObject({ spaceId: HOST_SPACE, onHost: true, error: null });+ // The job goes to this Mac's own Space, as the first message of its thread.+ await waitFor(() => expect(askTask(id)).toMatchObject({ spaceId: HOST_SPACE, onHost: true, error: null }), { timeout: 5000 });});it("Pick another keeps the default and reopens the picker", async () => {@@ -78,7 +76,7 @@ describe.skipIf(!wasmBuilt)("This Mac as a task's computer (real routes, wasm co});await screen.findByRole("menuitem", { name: /A new Linux computer on this Mac/ });expect(thisMacConfirmed()).toBe(false);- expect(document.querySelector('[data-picker="where"]')!.textContent).toContain("A new Linux computer");+ expect(document.querySelector('[data-picker="where"]')!.textContent).toContain("New Space");});it("doesn't ask again once answered on this device", async () => {diff --git a/apps/cua-spaces-web/src/__tests__/chatroom-thread.test.tsx b/apps/cua-spaces-web/src/__tests__/chatroom-thread.test.tsxnew file mode 100644index 0000000000..8ec38737dc--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/chatroom-thread.test.tsx@@ -0,0 +1,133 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The thread as a chatroom (CUA-2640): streaming text arrives as whole-text snapshots drawn at most+// every LIVE_COALESCE_MS, "Working for 1m 05s" ticks by writing its own text (no render per tick), a+// reply quotes what it answers only when that is not right above it, and an error is never cut.++import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { Profiler } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { ThreadItem } from "@/bridge";+import { ToastProvider, toast } from "@/components/ui/toast";+import { aboveSeq } from "@/components/space-thread/thread-view";+import { elapsedText, WorkingFor } from "@/components/space-thread/live-row";++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++describe("the working row's clock", () => {+ it("says how long, in the shortest words", () => {+ expect(elapsedText(0)).toBe("0s");+ expect(elapsedText(12_000)).toBe("12s");+ expect(elapsedText(65_000)).toBe("1m 05s");+ expect(elapsedText(3_725_000)).toBe("1h 02m");+ });++ it("ticks by writing its own text, without rendering again", () => {+ vi.useFakeTimers();+ let t = 1_000_000;+ const now = () => t;+ const renders: string[] = [];+ render(+ <Profiler id="clock" onRender={(_, phase) => renders.push(phase)}>+ <WorkingFor sinceMs={t - 65_000} now={now} />+ </Profiler>,+ );+ const el = document.querySelector("[data-live-elapsed]")!;+ expect(el.textContent).toBe("Working for 1m 05s");+ for (let i = 0; i < 3; i++) {+ t += 1000;+ act(() => {+ vi.advanceTimersByTime(1000);+ });+ }+ expect(el.textContent).toBe("Working for 1m 08s");+ // Mounted once; three seconds passed and React drew nothing more.+ expect(renders).toEqual(["mount"]);+ });+});++describe("a reply and what it answers", () => {+ const item = (seq: number, type: ThreadItem["type"] = "message") => ({ type, key: `k${seq}`, entry: { seq } }) as unknown as ThreadItem;++ it("knows the entry right above it, past notes and the unread divider", () => {+ const items = [item(1), item(2, "system"), { type: "unread", key: "unread" } as ThreadItem, item(4)];+ expect(aboveSeq(items, 0)).toBeNull();+ expect(aboveSeq(items, 3)).toBe(1);+ });+});++describe("an error is never cut", () => {+ beforeEach(() => vi.useRealTimers());++ it("an error toast shows every word of a long message, selectable, with Copy", async () => {+ const long = `Failed to authenticate. ${"API Error: 401 OAuth access token is invalid. ".repeat(12)}Refresh your existing token.`;+ render(<ToastProvider>{null}</ToastProvider>);+ act(() => {+ toast("Couldn't start the agent", { description: long, type: "error" });+ });+ const body = await screen.findByText((_, el) => el?.textContent === long && el.className.includes("select-text"));+ // Wrapped, not clipped: no ellipsis class on it, and the full text is in the DOM.+ expect(body.className).not.toContain("truncate");+ expect(body.className).toContain("break-words");+ const copy = document.querySelector<HTMLButtonElement>("[data-toast-copy]")!;+ const write = vi.fn(() => Promise.resolve());+ Object.assign(navigator, { clipboard: { writeText: write } });+ fireEvent.click(copy);+ expect(write).toHaveBeenCalledWith(long);+ });+});++describe("streaming snapshots", () => {+ it("draws the latest snapshot at most every LIVE_COALESCE_MS, and a new stage at once", async () => {+ const { BridgeProvider } = await import("@/bridge");+ const { useSpaceThread, LIVE_COALESCE_MS } = await import("@/bridge/thread");+ const { noCore } = await import("@/bridge/__tests__/testCore");+ const snapshot = (stage: string, text?: string) => ({ key: `ada=${stage}#${text?.length ?? 0}`, agents: [{ agent: "ada", stage, ...(text ? { text } : {}) }] });+ const page = (live: ReturnType<typeof snapshot>) => ({ entries: [], cursor: 1, caughtUp: true, unread: 0, readSeq: 1, me: "me", hasMoreBefore: false, role: null, live });+ // The follow answers at once, three snapshots of one stage (what is said grows), then waits.+ const script = [page(snapshot("replying", "Hel")), page(snapshot("replying", "Hello")), page(snapshot("replying", "Hello wor"))];+ let follows = 0;+ const adapter = {+ mode: "demo",+ subscribe: () => () => {},+ call: async (op: string, args: Record<string, unknown>) => {+ if (op === "thread.read" && args.followMs) {+ const next = script[follows++];+ // Each snapshot a few ms after the last, well inside one window.+ return next ? new Promise((r) => setTimeout(() => r(next), 5)) : new Promise(() => {});+ }+ if (op === "thread.read") return page({ key: "", agents: [] });+ if (op === "thread.members") return { members: [] };+ return [];+ },+ } as never;+ const env = globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT?: boolean };+ const was = env.IS_REACT_ACT_ENVIRONMENT;+ env.IS_REACT_ACT_ENVIRONMENT = false;+ const drawn: (string | undefined)[] = [];+ function Probe() {+ const t = useSpaceThread("local:dev");+ drawn.push(t.live[0]?.text);+ return null;+ }+ render(+ <BridgeProvider adapter={adapter} core={noCore}>+ <Probe />+ </BridgeProvider>,+ );+ // Outside act(), so every render React makes is a render the page would draw.+ await new Promise((r) => setTimeout(r, LIVE_COALESCE_MS * 4));+ const texts = drawn.filter((t, i) => t !== undefined && drawn[i - 1] !== t);+ // The stage appearing shows at once ("Hel"); the two snapshots that followed within the window were+ // drawn as one: the latest, whole.+ expect(texts[0]).toBe("Hel");+ expect(texts).not.toContain("Hello");+ expect(texts.at(-1)).toBe("Hello wor");+ env.IS_REACT_ACT_ENVIRONMENT = was;+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/connect-other-machine.test.tsx b/apps/cua-spaces-web/src/__tests__/connect-other-machine.test.tsxnew file mode 100644index 0000000000..0e3ea5e5bb--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/connect-other-machine.test.tsx@@ -0,0 +1,112 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// CUA-2644: an agent that runs on another machine (the customer's Hermes on Linux, driving their+// MacBook). Connect says which machine it set up and which it did not touch, and has an "On another+// machine" block with the host, the exact commands, the permissions and the reload note. The first+// run offers "An agent on another machine", which opens the join sheet.++import { createMemoryHistory, createRootRoute, createRouter, RouterProvider } from "@tanstack/react-router";+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import { BridgeProvider } from "@/bridge";+import { createDemoAdapter } from "@/bridge/adapters/demo";+import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";+import { ConnectAgentDialog } from "@/components/agents/connect-dialog";+import { mountApp, stubBrowserApis } from "./app-harness";++afterEach(cleanup);+stubBrowserApis();++const q = (sel: string) => document.querySelector<HTMLElement>(sel);++async function mountDialog() {+ const adapter = createDemoAdapter({ latencyMs: 0 });+ const routeTree = createRootRoute({ component: () => <ConnectAgentDialog open onOpenChange={() => {}} /> });+ const router = createRouter({ routeTree, history: createMemoryHistory({ initialEntries: ["/"] }) });+ render(+ <BridgeProvider adapter={adapter} core={await testCore()}>+ <RouterProvider router={router} />+ </BridgeProvider>,+ );+ return adapter;+}++describe.skipIf(!wasmBuilt)("an agent on another machine", () => {+ it("Connect names the machine it edits, and its On another machine block has the host, commands, permissions and reload note", async () => {+ await mountDialog();+ const here = await waitFor(() => {+ const h = q("[data-connect-here]");+ if (!h || !/^On \S/.test(h.textContent ?? "") || /this machine$/.test(h.textContent ?? "") === false) throw new Error("not named yet");+ return h;+ });+ const name = here.textContent!.replace(/^On /, "").replace(/this machine$/, "");+ const block = q("[data-connect-other-machine]")!;+ expect(screen.getByRole("heading", { name: "On another machine" })).toBeTruthy();+ expect(block.textContent).toContain(`Host to name: ${name}`);+ // The exact commands for the chosen agent: the same account, then the agent's setup.+ expect(block.textContent).toContain("cua auth login");+ expect(block.textContent).toContain("cua agents setup --agents hermes --yes");+ fireEvent.click(within(block).getByRole("button", { name: "Codex" }));+ expect(block.textContent).toContain("cua agents setup --agents codex --yes");+ expect(q("[data-connect-other-permissions]")?.textContent).toMatch(/share its desktop/);+ expect(q("[data-connect-other-reload]")?.textContent).toMatch(/Restart the agent/);+ expect(block.textContent).not.toMatch(/·|\bdevices?\b/i);+ });++ it("after Set up it says which machine it configured and which others it did not touch", async () => {+ await mountDialog();+ const setUp = await screen.findByRole("button", { name: /^Set up \d+ agent/ }, { timeout: 5000 }).catch(() => null);+ if (setUp) await act(async () => fireEvent.click(setUp));+ await waitFor(() => expect(q("[data-connect-done]")).not.toBeNull(), { timeout: 5000 });+ const done = q("[data-connect-done]")!;+ expect(done.textContent).toMatch(/^Set up on \S/);+ // The demo account has other machines: they are named, and Connect says it left them alone.+ expect(q("[data-connect-others]")?.textContent).toMatch(/Not touched: .+/);+ });++ it("Settings, Connectors names the machine it edits, what it leaves alone, and shows how to use it from another machine", async () => {+ await mountApp("/settings/connectors", { failsCreates: false, listsGhost: false });+ const footer = await waitFor(() => {+ const f = q("[data-connectors-machine]");+ if (!f) throw new Error("no footer");+ return f;+ });+ expect(footer.textContent).toMatch(/^On \S+/);+ // The demo account has other machines: named, and left alone.+ expect(footer.textContent).toMatch(/Not touched: .+/);+ expect(q("[data-connect-other-machine]")).toBeNull();+ fireEvent.click(q("[data-connectors-other-toggle]")!);+ const block = await waitFor(() => {+ const b = q("[data-connect-other-machine]");+ if (!b) throw new Error("not open");+ return b;+ });+ expect(block.textContent).toContain("cua auth login");+ expect(block.textContent).toContain("cua agents setup --agents hermes --yes");+ expect(q("[data-connect-other-permissions]")?.textContent).toMatch(/share its desktop/);+ expect(q("[data-connect-other-reload]")?.textContent).toMatch(/Restart the agent/);+ expect(block.textContent).not.toMatch(/·|\bdevices?\b/i);+ // An app's own page says which machine it is on.+ cleanup();+ await mountApp("/settings/connectors/claude-code", { failsCreates: false, listsGhost: false });+ await waitFor(() => expect(q("[data-connector-on]")?.textContent).toMatch(/^On \S+/));+ });++ it("the first run offers An agent on another machine, which opens the join sheet", async () => {+ await mountApp("/onboarding?demo=fresh", { failsCreates: false, listsGhost: false });+ const skip = await screen.findByRole("button", { name: "Get started" });+ fireEvent.click(skip);+ const skipSignIn = await screen.findByRole("button", { name: "Skip", exact: true } as never).catch(() => null);+ if (skipSignIn) fireEvent.click(skipSignIn);+ const row = await waitFor(() => {+ const r = q("[data-first-run-other-machine]");+ if (!r) throw new Error("not on the connect step yet");+ return r;+ }, { timeout: 8000 });+ expect(row.textContent).toContain("An agent on another machine");+ fireEvent.click(q("[data-first-run-other-machine-open]")!);+ await waitFor(() => expect(q('[data-add-agent="connect"]')).not.toBeNull());+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx b/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsxindex dc1f1ce47f..becbd0d9c6 100644--- a/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx@@ -1,7 +1,7 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-// Settings, Connectors with the redesign: each coding app has Connect (Cua's+// Settings, Connectors: each coding app has Connect (Cua's// tools and its sign-in, once) and a chevron to its own page; Providers has// Connect or Sign out. Connect on Claude Code runs only its own token// command (`signIn: true` for Claude Code alone) and connects Anthropic too.@@ -43,7 +43,7 @@ function host(calls: { op: string; args: unknown }[]) {return { failsCreates: false, listsGhost: false, intercept: (op: string, args: unknown) => (calls.push({ op, args }), undefined) };}-describe.skipIf(!wasmBuilt)("Settings, Connectors (redesign)", () => {+describe.skipIf(!wasmBuilt)("Settings, Connectors", () => {it("lists apps with Connect and a chevron, then Providers; no switches per app", async () => {await mountApp("/settings/connectors", host([]));const claude = await found("[data-connector-app=claude-code]");@@ -170,7 +170,7 @@ describe.skipIf(!wasmBuilt)("Settings, Connectors (redesign)", () => {expect(way.textContent).toContain("Use ANTHROPIC_API_KEY from your shell");await click(way);await waitFor(() => expect(q("[data-connector-provider=anthropic]")!.dataset.state).toBe("connected"));- expect(calls.filter((c) => c.op.startsWith("agentKeys.") && c.op !== "agentKeys.list").map((c) => c.op)).toEqual(["agentKeys.shell", "agentKeys.fromShell"]);+ expect(calls.filter((c) => c.op.startsWith("agentKeys.") && c.op !== "agentKeys.list" && c.op !== "agentKeys.check").map((c) => c.op)).toEqual(["agentKeys.shell", "agentKeys.fromShell"]);});it("an app's page switches one part off and on, leaving the other", async () => {@@ -182,12 +182,4 @@ describe.skipIf(!wasmBuilt)("Settings, Connectors (redesign)", () => {await waitFor(() => expect(q("[data-connector-toggle=mcp]")!.getAttribute("aria-checked") ?? q("[data-connector-toggle=mcp]")!.dataset.checked).toMatch(/false|unchecked/));expect(q("[data-connector-toggle=skills]")!.getAttribute("aria-checked") ?? "true").not.toBe("false");});-- it("redesign off: the page as it was, with switches and Account keys", async () => {- vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");- await mountApp("/settings/connectors", host([]));- await found('[data-connected-app="claude-code"]');- expect(q("[data-connectors-redesign]")).toBeNull();- await found("[data-agent-keys]");- });});diff --git a/apps/cua-spaces-web/src/__tests__/flags.test.ts b/apps/cua-spaces-web/src/__tests__/flags.test.tsnew file mode 100644index 0000000000..a10b8d0ce0--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/flags.test.ts@@ -0,0 +1,38 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Flags: defaults, overrides, and the retired `spaces_redesign` (the classic design is gone, so a+// leftover override of it, such as a stale "0" from a test, is cleared and never read).++import { afterEach, describe, expect, it, vi } from "vitest";++import { clearRetiredFlagOverrides, flagOn, setFlagOverride } from "@/bridge/flags";++afterEach(() => {+ vi.unstubAllEnvs();+ localStorage.clear();+});++describe("flags", () => {+ it("are off by default; an override or the build's env turns one on", () => {+ vi.stubEnv("VITE_CUA_FLAG_SPACES_ASK_FIRST_HOME", "");+ setFlagOverride("spaces_ask_first_home", null);+ expect(flagOn("spaces_ask_first_home")).toBe(false);+ vi.stubEnv("VITE_CUA_FLAG_SPACES_ASK_FIRST_HOME", "1");+ expect(flagOn("spaces_ask_first_home")).toBe(true);+ // This device's explicit choice wins over the env, both ways.+ setFlagOverride("spaces_ask_first_home", false);+ expect(flagOn("spaces_ask_first_home")).toBe(false);+ vi.stubEnv("VITE_CUA_FLAG_SPACES_ASK_FIRST_HOME", "");+ setFlagOverride("spaces_ask_first_home", true);+ expect(flagOn("spaces_ask_first_home")).toBe(true);+ });++ it("clears a stale spaces_redesign override on start, and leaves the other flags alone", () => {+ localStorage.setItem("cua.flag.spaces_redesign", "0");+ localStorage.setItem("cua.flag.spaces_ask_first_home", "1");+ clearRetiredFlagOverrides();+ expect(localStorage.getItem("cua.flag.spaces_redesign")).toBeNull();+ expect(localStorage.getItem("cua.flag.spaces_ask_first_home")).toBe("1");+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/home-agents.test.tsx b/apps/cua-spaces-web/src/__tests__/home-agents.test.tsxindex 99984a10ef..9cfd0006e7 100644--- a/apps/cua-spaces-web/src/__tests__/home-agents.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/home-agents.test.tsx@@ -4,8 +4,7 @@// Home and the Agents page draw ONE list (`agentList.view`): a job whose// Space is still being made and an agent that isn't connected show on both,// with the same words and the same Connect; a row opens its Space's thread.-// Home's order: the composer, Your agents, Your Spaces. With the redesign-// off, Home keeps its Tasks list.+// Home's order: the composer, Your agents, Your Spaces.import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -113,13 +112,4 @@ describe.skipIf(!wasmBuilt)("Your agents and the Agents page: one list", () => {expect(q("[data-home-agents]")).toBeNull();expect(q("[data-home-spaces]")).toBeNull();});-- it("redesign off: Home keeps its Tasks list", async () => {- vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");- await mountApp("/home", { failsCreates: false, listsGhost: false });- await start("tidy the repo");- fireEvent.click(await found("a[href='/home']"));- await found("[data-task-row]");- expect(q("[data-home-agents]")).toBeNull();- });});diff --git a/apps/cua-spaces-web/src/__tests__/machines-account.test.tsx b/apps/cua-spaces-web/src/__tests__/machines-account.test.tsxnew file mode 100644index 0000000000..99d27caace--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/machines-account.test.tsx@@ -0,0 +1,185 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// One list of machines (CUA-2621): the machines waiting to be added are the top group with+// "Add machine" and "Not me" and a count on the sidebar, a machine that is only signed in is a row+// in the state "Signed in, not sharing" that Revoke removes, each page has Rename, Revoke, recent+// access and (this machine) its trust, and the old Settings tab lands on Machines.++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 { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";+import type { DevicesInput, MachineRow, MachinesView } from "@/bridge";+import { mountApp, stubBrowserApis, type TestHost } from "./app-harness";++afterEach(cleanup);+stubBrowserApis();++type Calls = [string, unknown][];++/** The demo host, noting the calls it is asked for; `extra` rewrites what the relay says of the account. */+function host(calls: Calls, extra?: (d: DevicesInput) => DevicesInput): TestHost {+ return {+ failsCreates: false,+ listsGhost: false,+ answer: (op, out) => (op === "devices.get" && extra ? extra(out as DevicesInput) : out),+ intercept: (op, args) => {+ calls.push([op, args]);+ return undefined;+ },+ };+}++/** The approved mockup, drawn by the core with a signed-in machine that shares nothing (Ana's laptop). */+async function mockupHost(calls: Calls): Promise<TestHost> {+ const fixture = JSON.parse(readFileSync(resolve(process.cwd(), "../../libs/cua/crates/cua-spaces-app-core/parity/machines.json"), "utf8"));+ const view = (await testCore()).call<MachinesView>("machines.view", { input: fixture.views[0].input });+ const rows: MachineRow[] = view.machines.map((m) => ({ id: m.id, name: m.name, via: m.current ? "local" : "relay", online: m.online, os: m.os, current: m.current || undefined, limits: [] }));+ return {+ failsCreates: false,+ listsGhost: false,+ answer: (op, out) => (op === "machines.list" ? rows : out),+ intercept: (op, args) => {+ if (op === "machines.remove" || op === "machines.rename" || op === "machines.checkHealth" || op === "host.openSettings" || op === "host.action") {+ calls.push([op, args]);+ return null;+ }+ return undefined;+ },+ machinesView: () => view,+ };+}++const q = (sel: string) => document.querySelector<HTMLElement>(sel);+const names = () => [...document.querySelectorAll("[data-pending-machine]")].map((e) => e.querySelector("span.truncate")?.textContent);+const sentFor = (calls: Calls, op: string) => calls.filter(([o]) => o === op).map(([, a]) => a);++describe.skipIf(!wasmBuilt)("one list of machines (real routes, wasm core)", () => {+ it("puts the machines waiting to be added first, each with Add machine and Not me, and counts them in the sidebar", async () => {+ await mountApp("/machines", host([]));+ await waitFor(() => expect(q('[data-machine-group="pending"]')).not.toBeNull());+ expect(names()).toEqual(["Work laptop", "Old laptop"]);+ // First in the list, above the clouds and the machines.+ expect(document.querySelector("[data-machine-group], [data-cloud-group]")?.getAttribute("data-machine-group")).toBe("pending");+ for (const row of document.querySelectorAll("[data-pending-machine]")) {+ expect(within(row as HTMLElement).getByRole("button", { name: "Add machine" })).toBeTruthy();+ expect(within(row as HTMLElement).getByRole("button", { name: "Not me" })).toBeTruthy();+ }+ expect(q("[data-pending-badge]")?.textContent).toBe("2");+ // The count is on every page, not only on Machines.+ cleanup();+ await mountApp("/spaces", host([]));+ await waitFor(() => expect(q("[data-pending-badge]")?.textContent).toBe("2"));+ });++ it("Add machine adds the waiting machine by its id, with no code to type, and it leaves the waiting group", async () => {+ const calls: Calls = [];+ await mountApp("/machines", host(calls));+ await waitFor(() => expect(names()).toContain("Work laptop"));+ fireEvent.click(within(q('[data-pending-machine="dev_work"]')!).getByRole("button", { name: "Add machine" }));+ await waitFor(() => expect(sentFor(calls, "devices.approve")).toEqual([{ code: null, deviceId: "dev_work" }]));+ await waitFor(() => expect(names()).toEqual(["Old laptop"]));+ expect(q("[data-pending-badge]")?.textContent).toBe("1");+ });++ it("Not me refuses the waiting machine, and it leaves the list", async () => {+ const calls: Calls = [];+ await mountApp("/machines", host(calls));+ await waitFor(() => expect(names()).toContain("Work laptop"));+ fireEvent.click(within(q('[data-pending-machine="dev_work"]')!).getByRole("button", { name: "Not me" }));+ await waitFor(() => expect(sentFor(calls, "devices.revoke")).toEqual([{ id: "dev_work" }]));+ await waitFor(() => expect(names()).toEqual(["Old laptop"]));+ expect(q('[data-machine-id="dev_work"]')).toBeNull();+ });++ const withUnknown = (d: DevicesInput): DevicesInput => ({ ...d, machines: [...(d.machines ?? []), { id: "m3", name: "unknown-box", confirmed: false }] });++ it("a machine that registered without proof is confirmed with Add machine", async () => {+ const calls: Calls = [];+ await mountApp("/machines", host(calls, withUnknown));+ await waitFor(() => expect(names()).toContain("unknown-box"));+ fireEvent.click(within(q('[data-pending-machine="m3"]')!).getByRole("button", { name: "Add machine" }));+ await waitFor(() => expect(sentFor(calls, "devices.confirmMachine")).toEqual([{ id: "m3" }]));+ });++ it("Not me on a machine that registered without proof asks first, then removes it from the account", async () => {+ const calls: Calls = [];+ await mountApp("/machines", host(calls, withUnknown));+ await waitFor(() => expect(names()).toContain("unknown-box"));+ fireEvent.click(within(q('[data-pending-machine="m3"]')!).getByRole("button", { name: "Not me" }));+ const dialog = await screen.findByRole("alertdialog");+ expect(sentFor(calls, "machines.remove")).toEqual([]);+ fireEvent.click(within(dialog).getByRole("button", { name: "Remove" }));+ await waitFor(() => expect(sentFor(calls, "machines.remove")).toEqual([{ machine: "m3", device: null }]));+ });++ it("the waiting machine's page asks 'Add this machine?' with its name and system and two buttons", async () => {+ await mountApp("/machines", host([]));+ await waitFor(() => expect(names()).toContain("Work laptop"));+ act(() => q('[data-pending-machine="dev_work"] button')!.click());+ const page = await waitFor(() => q('[data-pending-detail="dev_work"]')!);+ expect(within(page).getByRole("heading", { name: "Add this machine?" })).toBeTruthy();+ expect(page.textContent).toContain("Work laptop");+ expect(page.textContent).toContain("Windows");+ expect(within(page).getByRole("button", { name: "Add machine" })).toBeTruthy();+ expect(within(page).getByRole("button", { name: "Not me" })).toBeTruthy();+ expect(page.textContent).not.toMatch(/device|computer|enroll/i);+ });++ it("a machine that is only signed in is a row 'Signed in, not sharing', with no Spaces switches, and Revoke asks first", async () => {+ const calls: Calls = [];+ await mountApp("/machines", await mockupHost(calls));+ const row = await waitFor(() => {+ const r = q('[data-machine-id="dev_lap"]');+ if (!r) throw new Error("no row");+ return r;+ });+ expect(row.querySelector("[data-machine-line]")?.textContent).toBe("Signed in, not sharing");+ expect(q('[data-machine-group="yours"]')?.contains(row)).toBe(true);+ expect(document.body.textContent).not.toMatch(/Your devices|Signed-in device/);+ act(() => row.click());+ const page = await screen.findByRole("region", { name: "Ana's laptop details" });+ expect(page.querySelector("[data-machine-status]")?.textContent).toContain("Signed in, not sharing");+ expect(page.querySelector("[data-machine-toggle]")).toBeNull();+ // Rename and Revoke are on its page.+ expect(page.querySelector("[data-machine-rename]")).not.toBeNull();+ const revoke = page.querySelector<HTMLElement>('[data-machine-remove="dev_lap"]')!;+ expect(revoke.textContent).toBe("Revoke");+ fireEvent.click(revoke);+ const dialog = await screen.findByRole("alertdialog");+ expect(dialog.textContent).toMatch(/Revoke/);+ expect(dialog.textContent).not.toMatch(/device/i);+ fireEvent.click(within(dialog).getByRole("button", { name: "Revoke" }));+ await waitFor(() => expect(sentFor(calls, "machines.remove")).toEqual([{ machine: null, device: "dev_lap" }]));+ });++ it("each machine's page has its recent access, and this machine's page says how far it is trusted", async () => {+ await mountApp("/machines", host([]));+ // The trust lines live under Details, not on the page itself.+ await waitFor(() => expect(q("[data-machine-details-toggle]")).toBeTruthy());+ expect(q("[data-machine-trust]")).toBeNull();+ act(() => q("[data-machine-details-toggle]")?.click());+ const trust = await waitFor(() => {+ const t = q("[data-machine-trust]");+ if (!t) throw new Error("no trust section");+ return t;+ });+ expect(trust.getAttribute("data-machine-trust")).toBe("enrolled");+ expect(trust.querySelector("[data-machine-trust-status]")?.textContent).toMatch(/^Trusted until/);+ // The demo's relay says studio-mac and mac-mini were reached.+ act(() => q('[data-machine-id="mac-mini"]')?.click());+ const recent = await waitFor(() => {+ const r = q("[data-machine-recent]");+ if (!r) throw new Error("no recent access");+ return r;+ });+ expect(recent.textContent).not.toMatch(/device|computer|enrolled/i);+ });++ it("the old Trusted machines address lands on Machines", async () => {+ const { router } = await mountApp("/settings/devices", host([]));+ await waitFor(() => expect(router.state.location.pathname).toBe("/machines"));+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/machines-page.test.tsx b/apps/cua-spaces-web/src/__tests__/machines-page.test.tsxindex d686284e9c..a2bc3d23ec 100644--- a/apps/cua-spaces-web/src/__tests__/machines-page.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/machines-page.test.tsx@@ -91,7 +91,7 @@ describe.skipIf(!wasmBuilt)("the Machines page (real routes, wasm core)", () =>const { router, hooks } = await mountApp("/machines", stopped(calls));await router.load();await waitFor(() => expect(hooks.machines.view?.machines.some((m) => m.id === "studio")).toBe(true));- await screen.findByText(hooks.machines.view!.summary);+ await screen.findByText(new RegExp(`^${hooks.machines.view!.summary}`));const row = document.querySelector('[data-machine-id="studio"]') as HTMLElement;expect(row.querySelector("[data-machine-line]")?.textContent).toBe("Not sharing");@@ -112,16 +112,17 @@ describe.skipIf(!wasmBuilt)("the Machines page (real routes, wasm core)", () =>const calls: [string, unknown][] = [];const { router } = await mountApp("/machines", hostDrawn(view, calls));await router.load();- await screen.findByText(view.summary);+ await screen.findByText(new RegExp(`^${view.summary}`));- // Groups, with the old machines collapsed.+ // Groups, with the old machines collapsed. The machines waiting to be added come first; a+ // machine that is only signed in sits in the one list.const groups = [...document.querySelectorAll("[data-machine-group]")].map((g) => g.getAttribute("data-machine-group"));- expect(groups).toEqual(["yours", "devices", "old", "team"]);- const devices = document.querySelector<HTMLElement>('[data-machine-group="devices"]')!;- expect(devices.textContent).toContain("Your devices");- const lap = devices.querySelector<HTMLElement>('[data-machine-id="dev_lap"]')!;+ expect(groups).toEqual(["pending", "yours", "old", "team"]);+ expect(document.body.textContent).not.toMatch(/Your devices|Signed-in device/);+ const yours = document.querySelector<HTMLElement>('[data-machine-group="yours"]')!;+ const lap = yours.querySelector<HTMLElement>('[data-machine-id="dev_lap"]')!;expect(lap.hidden).toBe(false);- expect(lap.querySelector("[data-machine-line]")?.textContent).toBe("Signed-in device, not shared");+ expect(lap.querySelector("[data-machine-line]")?.textContent).toBe("Signed in, not sharing");const old = document.querySelector<HTMLElement>('[data-machine-id="old1"]')!;expect(old.hidden).toBe(true);fireEvent.click(screen.getByRole("button", { name: /Offline for 30\+ days/ }));@@ -424,6 +425,8 @@ describe.skipIf(!wasmBuilt)("the Machines page (real routes, wasm core)", () =>act(() => (sheet.querySelector("[data-cloud-approve]") as HTMLElement).click());await waitFor(() => expect(calls).toEqual([["clouds.approve", { provider: "aws", approve: true }]]));await waitFor(() => expect(hooks.machines.view?.clouds?.pages[0]?.status).toBe("Connected"));+ // Let the dialog finish closing so nothing settles after the test ends.+ await waitFor(() => expect(document.querySelector("[data-cloud-approve]")).toBeNull());});it("lists the clouds above your machines, in the order the core gives", async () => {@@ -432,14 +435,15 @@ describe.skipIf(!wasmBuilt)("the Machines page (real routes, wasm core)", () =>await waitFor(() => expect(hooks.machines.view?.clouds?.group.rows.length).toBe(2));expect(hooks.machines.view!.order).toEqual(["clouds", "yours"]);const sections = [...document.querySelectorAll("[data-cloud-group], [data-machine-group]")].map((s) => s.getAttribute("data-cloud-group") ?? s.getAttribute("data-machine-group"));- expect(sections).toEqual(["clouds", "yours"]);- // Even with no cloud connected, "Connect a cloud" is the first row.+ // What waits for you is first; the clouds come before the machines.+ expect(sections).toEqual(["pending", "clouds", "yours"]);+ // Even with no cloud connected, "Connect a cloud" comes before the machines (after what waits for you).cleanup();resetNewSpaceSession();await mountApp("/machines", { failsCreates: false, listsGhost: false }).then(async ({ router: r }) => r.load());await waitFor(() => expect(document.querySelector("[data-connect-a-cloud]")).not.toBeNull());- const first = document.querySelector("[data-cloud-group], [data-machine-group]");- expect(first?.getAttribute("data-cloud-group")).toBe("clouds");+ const groups = [...document.querySelectorAll("[data-cloud-group], [data-machine-group]")].filter((g) => g.getAttribute("data-machine-group") !== "pending");+ expect(groups[0]?.getAttribute("data-cloud-group")).toBe("clouds");});it("scrolls the list and the detail pane on their own, under a header that stays put", async () => {@@ -492,7 +496,7 @@ describe.skipIf(!wasmBuilt)("the Machines page (real routes, wasm core)", () =>const page = await detailOf("AWS");expect(page.querySelector("[data-cloud-status]")?.textContent).toBe("Connected");expect(page.querySelector("[data-cloud-issues]")).toBeNull();- expect(page.querySelector("[data-cloud-setting=access]")?.textContent).toContain("The AWS CLI's sign-in on this computer");+ expect(page.querySelector("[data-cloud-setting=access]")?.textContent).toContain("The AWS CLI's sign-in on this machine");act(() => (page.querySelector("[data-cloud-switch=switch-oidc]") as HTMLElement).click());const sheet = await waitFor(() => document.querySelector("[data-connect-cloud]")!);await waitFor(() => expect(sheet.querySelector("[data-cloud-title]")?.textContent).toContain("AWS"));@@ -545,5 +549,6 @@ describe.skipIf(!wasmBuilt)("the Machines page (real routes, wasm core)", () =>await waitFor(() => expect(calls).toEqual([["clouds.approve", { provider: "aws", approve: false }]]));await waitFor(() => expect(hooks.machines.view?.clouds?.pages[0]?.status).toBe("Connected"));expect(hooks.machines.view?.clouds?.pages[0]?.settings.find((s) => s.id === "budget")?.value).toBe("$200");+ await waitFor(() => expect(document.querySelector("[data-cloud-deny]")).toBeNull());});});diff --git a/apps/cua-spaces-web/src/__tests__/native-parity.test.tsx b/apps/cua-spaces-web/src/__tests__/native-parity.test.tsxindex ec3ef6c50d..d753b88fb8 100644--- a/apps/cua-spaces-web/src/__tests__/native-parity.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/native-parity.test.tsx@@ -2,7 +2,7 @@// Copyright (c) 2026 Cua AI, Inc.// What the New UI on a Mac must show as the SwiftUI app does (real routes, the wasm core, the demo host with the Mac's answers):-// Devices when this device is not enrolled, Settings, General as the core+// This machine's trust when it is not trusted yet, Settings, General as the core// lays it out, and the Keyvault's reason when it is unavailable.import { createMemoryHistory, createRouter, RouterProvider } from "@tanstack/react-router";@@ -52,32 +52,36 @@ const NOT_ENROLLED ="permission denied: relay: this device is not enrolled for your cua.ai account: sign in again (`cua auth login`) to enroll it, run `cua devices enroll`, or approve it from the Cua Spaces app on an enrolled device";describe.skipIf(!wasmBuilt)("as the SwiftUI app (real routes, wasm core)", () => {- it("Devices: a device the relay has not enrolled gets one Enroll…, named as its system names it, as the SwiftUI page", async () => {- await mount("/settings/devices", (op) =>+ it("Machines: a machine the relay has not trusted gets one Trust this machine, on its own page", async () => {+ await mount("/machines", (op) =>op === "devices.get" ? Promise.resolve({ devices: [], audit: [], readError: NOT_ENROLLED, deviceName: "cua's Mac Studio" }) : undefined,);+ const toggle = await waitFor(() => {+ const t = document.querySelector<HTMLElement>("[data-machine-details-toggle]");+ if (!t) throw new Error("no Details on this machine's page");+ return t;+ });+ fireEvent.click(toggle);const status = await waitFor(() => {- const s = document.querySelector<HTMLElement>("[data-this-device-status]");- if (!s) throw new Error("no This Device row");+ const s = document.querySelector<HTMLElement>("[data-machine-trust]");+ if (!s) throw new Error("no trust section on this machine's page");return s;});- expect(status.getAttribute("data-this-device-status")).toBe("needs-enrollment");- expect(document.querySelector("[data-this-device-name]")?.textContent).toBe("cua's Mac Studio");- // One Enroll…: the row's. The line under it says what it is for.+ expect(status.getAttribute("data-machine-trust")).toBe("needs-enrollment");+ // One button; the line under it says what it is for.expect(screen.getAllByRole("button", { name: /^Trust this machine/ })).toHaveLength(1);- expect(document.querySelector("[data-banner-text]")?.textContent).toMatch(/Trust this machine/);- // "Enrolled", "Revoke" and "Re-verify" are the core's words; the page says them plainly.- expect(document.body.textContent).not.toMatch(/enroll/i);- // The relay's refusal is what "Needs enrollment" already says.+ expect(document.querySelector("[data-machine-trust-text]")?.textContent).toMatch(/Trust this machine/);+ // The core's words are plain: no enrolling, no devices.+ expect(document.body.textContent).not.toMatch(/enroll|\bdevices?\b/i);+ // The relay's refusal is what "Not trusted yet" already says.expect(document.querySelector("[data-devices-read-error]")).toBeNull();expect(document.body.textContent).not.toContain("permission denied");- expect(document.querySelector("[data-devices-error]")).toBeNull();- fireEvent.click(document.querySelector("[data-this-device-enroll]")!);+ fireEvent.click(document.querySelector("[data-machine-trust-action]")!);await waitFor(() => expect(screen.getByRole("dialog")).toBeTruthy());});- it("Devices: another read failure still says why", async () => {- await mount("/settings/devices", (op, _a, base) =>+ it("Machines: another read failure still says why", async () => {+ await mount("/machines", (op, _a, base) =>op === "devices.get" ? base(op, {}).then((d) => ({ ...(d as object), readError: "relay: timed out" })) : undefined,);await waitFor(() => expect(document.querySelector("[data-devices-read-error]")?.textContent).toBe("relay: timed out"));diff --git a/apps/cua-spaces-web/src/__tests__/needs-reconnect.test.tsx b/apps/cua-spaces-web/src/__tests__/needs-reconnect.test.tsxnew file mode 100644index 0000000000..da8e45b941--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/needs-reconnect.test.tsx@@ -0,0 +1,80 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// "Connected" must mean valid (CUA-2680): opening Settings, Connectors or the Agents page asks the+// providers whether the saved sign-ins and keys still work; a refused one reads "Needs reconnect" with+// a Reconnect button, on its provider row and on the apps that read it. Reconnecting clears it.++import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { resetConnectedAppsState } from "@/hooks/use-connected-apps";+import { resetConnectState } from "@/hooks/use-connectors";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetConnectedAppsState();+ resetConnectState();+});+afterEach(cleanup);++const q = (s: string) => document.querySelector<HTMLElement>(s);+const found = (s: string) =>+ waitFor(() => {+ const el = q(s);+ expect(el).not.toBeNull();+ return el!;+ });+const click = (el: Element) =>+ act(async () => {+ fireEvent.click(el);+ });++function host(calls: string[], rejected: string[] = []) {+ return { failsCreates: false, listsGhost: false, demo: { rejectedKeys: rejected }, intercept: (op: string) => (calls.push(op), undefined) };+}++describe.skipIf(!wasmBuilt)("a saved sign-in the provider refuses", () => {+ it("is re-checked when Settings, Connectors opens, and reads Needs reconnect with Reconnect", async () => {+ const calls: string[] = [];+ await mountApp("/settings/connectors", host(calls, ["OPENAI_API_KEY"]));+ await waitFor(() => expect(q("[data-connector-provider=openai]")?.textContent).toContain("Needs reconnect"));+ expect(calls).toContain("agentKeys.check");+ const row = q("[data-connector-provider=openai]")!;+ expect(row.dataset.state).toBe("not-connected");+ expect(row.querySelector("[data-connector-provider-action]")?.textContent).toBe("Reconnect");+ // Not "Connected", and no Sign out for a credential that does not work.+ expect(row.textContent).not.toContain("Sign out");+ expect(row.querySelector("[data-connector-status]")?.textContent).not.toContain("Connected");+ });++ it("is re-checked when the Agents page opens", async () => {+ const calls: string[] = [];+ await mountApp("/agents", host(calls));+ await waitFor(() => expect(calls).toContain("agentKeys.check"));+ });++ it("a key the provider accepts stays Connected", async () => {+ const calls: string[] = [];+ await mountApp("/settings/connectors", host(calls));+ await waitFor(() => expect(calls).toContain("agentKeys.check"));+ await waitFor(() => expect(q("[data-connector-provider=openai]")?.dataset.state).toBe("connected"));+ expect(q("[data-connector-provider=openai]")!.textContent).not.toContain("Needs reconnect");+ });++ it("Reconnect saves the key again and the row is Connected", async () => {+ const calls: string[] = [];+ await mountApp("/settings/connectors", host(calls, ["OPENAI_API_KEY"]));+ await waitFor(() => expect(q("[data-connector-provider=openai]")?.textContent).toContain("Needs reconnect"));+ await click(q("[data-connector-provider=openai] [data-connector-provider-action]")!);+ await found("[data-provider-sheet=openai]");+ await click(q("[data-provider-way=key]")!);+ fireEvent.change(await found("[data-provider-key]"), { target: { value: "sk-openai-new-0000-9z9z" } });+ await click(q("[data-provider-save]")!);+ await waitFor(() => expect(q("[data-connector-provider=openai]")?.dataset.state).toBe("connected"));+ expect(q("[data-connector-provider=openai]")!.textContent).not.toContain("Needs reconnect");+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/profile-cards.test.tsx b/apps/cua-spaces-web/src/__tests__/profile-cards.test.tsxindex 9fb44b0bd1..8aded48bb8 100644--- a/apps/cua-spaces-web/src/__tests__/profile-cards.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/profile-cards.test.tsx@@ -1,11 +1,10 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-// The cards people and agents open to on the redesigned Space page: a+// The cards people and agents open to on the Space page: a// person's (email, access, Active now; Change access and Remove for the// owner), your own, and an agent of yours with no sign-in (Not-// connected, with Connect). Mentions open the same cards. With the redesign-// off, the page as it was has none.+// connected, with Connect). Mentions open the same cards.import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -41,7 +40,7 @@ const click = (el: Element) =>await new Promise((r) => setTimeout(r, 10));});-describe.skipIf(!wasmBuilt)("profile cards (redesign)", () => {+describe.skipIf(!wasmBuilt)("profile cards", () => {it("the owner opens an editor's card: email, Can edit, Active now, Change access, Remove; no Copy email", async () => {const calls: { op: string; args: unknown }[] = [];await mountApp(path, { failsCreates: false, listsGhost: false, intercept: (op, args) => (calls.push({ op, args }), undefined) });@@ -148,11 +147,4 @@ describe.skipIf(!wasmBuilt)("profile cards (redesign)", () => {await click(chip.closest("[data-profile-trigger]")!);await found("[data-profile-card='agent'][data-profile='hermes']");});-- it("redesign off: the page as it was, no cards", async () => {- vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");- await mountApp(path, { failsCreates: false, listsGhost: false });- await waitFor(() => expect(document.body.textContent).toContain("ubuntu-build"));- expect(q("[data-profile-trigger]")).toBeNull();- });});diff --git a/apps/cua-spaces-web/src/__tests__/redesign-flag.test.tsx b/apps/cua-spaces-web/src/__tests__/redesign-flag.test.tsxdeleted file mode 100644index b9f775a4eb..0000000000--- a/apps/cua-spaces-web/src/__tests__/redesign-flag.test.tsx+++ /dev/null@@ -1,94 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--// `spaces_redesign` (Settings → Advanced → Labs) switches whole pages: on,-// the default, the redesign; off, each gated route draws the classic page-// (src/legacy/). Both states render, so neither can quietly break.--import { cleanup, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";--import { wasmBuilt } from "@/bridge/__tests__/testCore";-import { DEMO_THREAD_SPACE } from "@/bridge/adapters/demo/thread";-import { mountApp, stubBrowserApis } from "./app-harness";--stubBrowserApis();-afterEach(() => {- cleanup();- vi.unstubAllEnvs();-});--const HOST = { failsCreates: false, listsGhost: false };-const q = (sel: string) => document.querySelector(sel);-const flag = (on: boolean) => vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", on ? "1" : "0");--describe.skipIf(!wasmBuilt)("the redesign flag", () => {- it("is on by default, and an override or the build's env turns it off", async () => {- const { flagOn, setFlagOverride } = await import("@/bridge/flags");- setFlagOverride("spaces_redesign", null);- vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "");- expect(flagOn("spaces_redesign")).toBe(true);- // The build's env.- vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");- expect(flagOn("spaces_redesign")).toBe(false);- // This device's explicit choice wins over the env, both ways.- vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "");- setFlagOverride("spaces_redesign", false);- expect(flagOn("spaces_redesign")).toBe(false);- vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");- setFlagOverride("spaces_redesign", true);- expect(flagOn("spaces_redesign")).toBe(true);- setFlagOverride("spaces_redesign", null);- // The Ask first Home stays off by default.- vi.stubEnv("VITE_CUA_FLAG_SPACES_ASK_FIRST_HOME", "");- expect(flagOn("spaces_ask_first_home")).toBe(false);- });-- it("Spaces page: the toolbar and the new sidebar on; the page and the getting-started checklist as they were off", async () => {- flag(true);- await mountApp("/spaces", HOST);- await waitFor(() => expect(q("[data-spaces-toolbar]")).not.toBeNull());- expect(q("[data-account-line]")).not.toBeNull();- cleanup();-- flag(false);- await mountApp("/spaces", HOST);- await waitFor(() => expect(q("[data-space-id]")).not.toBeNull());- expect(q("[data-spaces-toolbar]")).toBeNull();- expect(q("[data-account-line]")).toBeNull();- });-- it("a Space: the thread and Stream rail on; the page as it was off", async () => {- const path = `/spaces/${encodeURIComponent(DEMO_THREAD_SPACE)}`;- flag(true);- await mountApp(path, HOST);- await waitFor(() => expect(q("[data-composer]")).not.toBeNull());- cleanup();-- flag(false);- await mountApp(path, HOST);- await waitFor(() => expect(document.body.textContent).toContain("ubuntu-build"));- expect(q("[data-composer]")).toBeNull();- });-- it("Agents: the chat on; the page as it was off", async () => {- flag(true);- await mountApp("/agents", HOST);- await waitFor(() => expect(q("[data-agents-chat]")).not.toBeNull());- cleanup();-- flag(false);- await mountApp("/agents", HOST);- await waitFor(() => expect(q("[data-agents-section], [data-agents-empty]")).not.toBeNull());- expect(q("[data-agents-chat]")).toBeNull();- });-- it("Computers keeps the clouds (Connect a cloud is on for everyone) in both states", async () => {- for (const on of [true, false]) {- flag(on);- await mountApp("/machines", HOST);- await waitFor(() => expect(q("[data-connect-a-cloud]")).not.toBeNull());- cleanup();- }- });-});diff --git a/apps/cua-spaces-web/src/__tests__/resources.test.tsx b/apps/cua-spaces-web/src/__tests__/resources.test.tsxindex 376ea43105..cbb389f750 100644--- a/apps/cua-spaces-web/src/__tests__/resources.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/resources.test.tsx@@ -168,7 +168,7 @@ describe.skipIf(!wasmBuilt)("resources on Home and a Space's page", () => {expect(panel.querySelector('[data-resource-card="Memory"]')?.textContent).toContain("Given 4 GB of this Mac’s 64 GB");});- it("another computer's running Space has no panel with only its size there", async () => {+ it("another machine's running Space has no panel with only its size there", async () => {await mountApp(`/spaces/${encodeURIComponent("relay:mac-mini/qa-windows")}`, { failsCreates: false, listsGhost: false, noThread: true });await waitFor(() => expect(document.querySelector("[data-detail-title]")).not.toBeNull());await act(() => new Promise((r) => setTimeout(r, 50)));diff --git a/apps/cua-spaces-web/src/__tests__/settings-advanced.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-advanced.test.tsxindex 622e70d694..7614c08f60 100644--- a/apps/cua-spaces-web/src/__tests__/settings-advanced.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/settings-advanced.test.tsx@@ -26,7 +26,7 @@ const host: TestHost = {};describe.skipIf(!wasmBuilt)("account usage and self-hosting in Settings (real routes, wasm core)", () => {- it("says what the time away from this computer is, in plain words", async () => {+ it("says what the time away from this machine is, in plain words", async () => {const { router } = await mountApp("/settings", host);await router.load();const usage = await waitFor(() => {@@ -34,7 +34,7 @@ describe.skipIf(!wasmBuilt)("account usage and self-hosting in Settings (real roexpect(el).toBeTruthy();return el as HTMLElement;});- expect(usage.textContent).toContain("Time away from this computer");+ expect(usage.textContent).toContain("Time away from this machine");expect(usage.textContent).toContain("away from the machine you're using");expect(document.body.textContent).not.toMatch(/relay hours|remote hours/i);});diff --git a/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsxindex 2f50b400ad..ef642653bb 100644--- a/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx@@ -7,8 +7,8 @@// installed app with a notice and Undo.import { createMemoryHistory, createRootRoute, createRouter, RouterProvider } from "@tanstack/react-router";-import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";import { BridgeProvider } from "@/bridge";import { createDemoAdapter } from "@/bridge/adapters/demo";import { noCore, wasmBuilt } from "@/bridge/__tests__/testCore";@@ -17,10 +17,7 @@ import { RunAgentDialog } from "@/components/agents/run-agent-dialog";import { connectedAppsState, resetConnectedAppsState, setConnectedAppsState } from "@/hooks/use-connected-apps";import { mountApp, stubBrowserApis } from "./app-harness";-// The Connectors page as it was (`spaces_redesign` off); the redesign's is connectors-redesign.test.tsx.-beforeEach(() => vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0"));afterEach(() => {- vi.unstubAllEnvs();cleanup();localStorage.clear();resetConnectedAppsState();@@ -56,64 +53,9 @@ describe("configured agents without binary evidence", () => {});});-const app = (id: string) => document.querySelector<HTMLElement>(`[data-connected-app="${id}"]`);-const switchOf = (id: string) => within(app(id)!).getByRole("switch");+const app = (id: string) => document.querySelector<HTMLElement>(`[data-connector-app="${id}"]`);describe.skipIf(!wasmBuilt)("Settings, Connectors", () => {- it("lists the coding apps on this computer with one switch each, file paths only under Advanced", { timeout: 20_000 }, async () => {- await mountApp("/settings/connectors", { failsCreates: false, listsGhost: false });- await waitFor(() => expect(app("hermes")).not.toBeNull(), { timeout: 8000 });- expect(within(app("claude-code")!).getByText("Claude Code")).toBeTruthy();- expect(switchOf("claude-code").getAttribute("aria-checked")).toBe("true");- expect(switchOf("hermes").getAttribute("aria-checked")).toBe("false");- // No file paths, skill counts or "Not installed" rows until Show all.- expect(document.body.textContent).not.toMatch(/\.claude\.json|Not installed|skills/);- expect(document.querySelector('[data-connected-missing="gemini-cli"]')).toBeNull();- fireEvent.click(document.querySelector("[data-connected-show-all]")!);- await waitFor(() => expect(document.querySelector('[data-connected-missing="gemini-cli"]')).not.toBeNull());- // Rows stay icon, name and switch; paths and Add it by hand wait in a closed Advanced.- expect(app("claude-code")!.textContent).not.toContain(".claude.json");- const advanced = document.querySelector<HTMLDetailsElement>("[data-connected-advanced]")!;- expect(advanced.open).toBe(false);- expect(advanced.querySelector('[data-connected-file="claude-code"]')!.textContent).toContain("~/.claude.json");- expect(advanced.querySelector("[data-connected-by-hand]")).not.toBeNull();- });-- it("switches one app on and off, remembers an app turned off, and offers Undo", { timeout: 20_000 }, async () => {- await mountApp("/settings/connectors", { failsCreates: false, listsGhost: false });- await waitFor(() => expect(app("hermes")).not.toBeNull(), { timeout: 8000 });- fireEvent.click(switchOf("hermes"));- await waitFor(() => expect(switchOf("hermes").getAttribute("aria-checked")).toBe("true"));- fireEvent.click(switchOf("hermes"));- await waitFor(() => expect(switchOf("hermes").getAttribute("aria-checked")).toBe("false"));- expect(connectedAppsState().off).toContain("hermes");- // The notice says what happened and how to take it back.- const undo = await screen.findByRole("button", { name: "Undo" });- expect(document.body.textContent).toContain("Hermes turned off");- expect(document.body.textContent).toContain("Cua took itself out of Hermes's settings");- fireEvent.click(undo);- await waitFor(() => expect(switchOf("hermes").getAttribute("aria-checked")).toBe("true"));- expect(connectedAppsState().off).not.toContain("hermes");- });-- it("says why a setup failed in plain words, and offers Try again and the file to edit by hand", { timeout: 20_000 }, async () => {- await mountApp("/settings/connectors", { failsCreates: false, listsGhost: false, demo: { agentsReadOnly: ["hermes"] } });- await waitFor(() => expect(app("hermes")).not.toBeNull(), { timeout: 8000 });- fireEvent.click(switchOf("hermes"));- const failure = await waitFor(() => {- const f = document.querySelector<HTMLElement>('[data-connected-failure="hermes"]');- expect(f).not.toBeNull();- return f!;- });- expect(failure.textContent).toContain("Couldn't set up Hermes. Cua can't change this file because it is read-only or belongs to another user.");- expect(document.body.textContent).not.toMatch(/os error/);- expect(switchOf("hermes").getAttribute("aria-checked")).toBe("false");- expect(within(failure).getByRole("button", { name: "Try again" })).toBeTruthy();- fireEvent.click(within(failure).getByRole("button", { name: "Add it by hand" }));- expect(failure.textContent).toContain("mcp_servers:");- expect(failure.textContent).toContain("Paste this into the file, then restart Hermes.");- });-it("keeps Set up new apps automatically in the saved state", { timeout: 20_000 }, async () => {await mountApp("/settings/connectors", { failsCreates: false, listsGhost: false });await waitFor(() => expect(document.querySelector("[data-connected-auto]")).not.toBeNull(), { timeout: 8000 });@@ -144,7 +86,7 @@ describe.skipIf(!wasmBuilt)("a newly installed coding app", () => {const { router } = await mountApp("/settings/connectors", { failsCreates: false, listsGhost: false });await waitFor(() => expect(app("hermes")).not.toBeNull(), { timeout: 8000 });await router.load();- expect(switchOf("hermes").getAttribute("aria-checked")).toBe("false");+ expect(app("hermes")!.querySelector("[data-connector-connect]")).not.toBeNull();expect(document.body.textContent).not.toContain("can now use Cua");}});diff --git a/apps/cua-spaces-web/src/__tests__/settings-host-rows.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-host-rows.test.tsxindex fd09d3d2eb..ea92004fc8 100644--- a/apps/cua-spaces-web/src/__tests__/settings-host-rows.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/settings-host-rows.test.tsx@@ -98,7 +98,7 @@ describe.skipIf(!wasmBuilt)("Settings, Advanced: which software runs Spaces (reait("has one row per kind, in plain words, and none of the old per-OS rows", async () => {await mountAdvanced();await waitFor(() => expect(kindRow("microvm")).toBeTruthy());- expect(document.body.textContent).toContain("Which software runs Spaces on this computer");+ expect(document.body.textContent).toContain("Which software runs Spaces on this machine");for (const [kind, label] of KINDS) {const r = row(`runtime:${kind}`)!;expect(within(r).getByText(label)).toBeTruthy();diff --git a/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsxindex 88f1319398..3cd99863a5 100644--- a/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx@@ -1,10 +1,10 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-// Settings' six tabs on the real routes and the wasm core: Account, General,-// Connectors, Trusted machines, Advanced, About. The old addresses-// (Agents, Experiments) still land on the right tab, and what moved is where-// the audit put it.+// Settings' five tabs on the real routes and the wasm core: Account, General,+// Connectors, Advanced, About. The old addresses (Agents, Experiments) still+// land on the right tab, the old Trusted machines tab lands on Machines, and+// what moved is where the audit put it.import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";@@ -25,24 +25,23 @@ const tab = (id: string) => document.querySelector<HTMLElement>(`[data-settings-const labels = () => [...document.querySelectorAll<HTMLElement>('nav[aria-label="Settings"] a')].map((a) => a.textContent);describe.skipIf(!wasmBuilt)("Settings tabs (real routes, wasm core)", () => {- it("has Account, General, Connectors, Trusted machines, Advanced and About, in that order", async () => {+ it("has Account, General, Connectors, Advanced and About, in that order", async () => {await mountApp("/settings", host);await waitFor(() => expect(tab("account")).not.toBeNull());- expect(labels()).toEqual(["Account", "General", "Connectors", "Trusted machines", "Advanced", "About"]);+ expect(labels()).toEqual(["Account", "General", "Connectors", "Advanced", "About"]);});it.each([["/settings", "Account"],["/settings/general", "General"],["/settings/connectors", "Connectors"],- ["/settings/devices", "Trusted machines"],["/settings/advanced", "Advanced"],["/settings/about", "About"],])("marks only the tab for %s as selected (%s)", async (path, label) => {await mountApp(path, host);const tabs = () => [...document.querySelectorAll<HTMLElement>('[role="tablist"][aria-label="Settings"] [role="tab"]')];await waitFor(() => expect(tabs().filter((t) => t.getAttribute("aria-selected") === "true").map((t) => t.textContent)).toEqual([label]));- expect(tabs().filter((t) => t.getAttribute("aria-selected") === "false")).toHaveLength(5);+ expect(tabs().filter((t) => t.getAttribute("aria-selected") === "false")).toHaveLength(4);});it.each([@@ -55,6 +54,12 @@ describe.skipIf(!wasmBuilt)("Settings tabs (real routes, wasm core)", () => {await waitFor(() => expect(tab(id)).not.toBeNull());});+ it("sends the old Trusted machines address to the Machines tab", async () => {+ const { router } = await mountApp("/settings/devices", host);+ await waitFor(() => expect(router.state.location.pathname).toBe("/machines"));+ expect(document.querySelector('[data-settings-tab]')).toBeNull();+ });+it("keeps General to the everyday settings: no Keyboard shortcuts, Shared links, Storage or Runtimes", async () => {await mountApp("/settings/general", host);await waitFor(() => expect(tab("general")).not.toBeNull());@@ -66,13 +71,11 @@ describe.skipIf(!wasmBuilt)("Settings tabs (real routes, wasm core)", () => {});it("puts Connectors where Agents was, with the account keys and Terminal", async () => {- // The page as it was (the redesign's Providers: connectors-redesign.test.tsx).- vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");await mountApp("/settings/connectors", host);- await waitFor(() => expect(document.querySelector("[data-agent-keys]")).not.toBeNull(), { timeout: 8000 });+ await waitFor(() => expect(document.querySelector("[data-connectors-providers]")).not.toBeNull(), { timeout: 8000 });const text = tab("connectors")!.textContent!;- expect(text).toContain("Account keys");- expect(text).toContain("Add a key for another AI company");+ expect(text).toContain("Providers");+ expect(document.querySelector("[data-agent-key-add-other]")).not.toBeNull();expect(text).not.toMatch(/provider key/i);});diff --git a/apps/cua-spaces-web/src/__tests__/share-add-agent.test.tsx b/apps/cua-spaces-web/src/__tests__/share-add-agent.test.tsxindex 9fde05cb8f..1b374f682b 100644--- a/apps/cua-spaces-web/src/__tests__/share-add-agent.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/share-add-agent.test.tsx@@ -1,11 +1,10 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-// Share and Add an agent lead to each other on the redesigned Space page:+// Share and Add an agent lead to each other on the Space page:// Share's footer has "Add an agent" left of Done, and Add an agent has// "Share with a person". Each replaces the other (one dialog at a time,-// focus in the one that opened, Escape closes it). With the redesign off-// the Share sheet stays as it was.+// focus in the one that opened, Escape closes it).import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";@@ -24,7 +23,6 @@ const HOST = { failsCreates: false, listsGhost: false };const path = `/spaces/${encodeURIComponent(DEMO_THREAD_SPACE)}`;const q = (sel: string) => document.querySelector<HTMLElement>(sel);const dialogs = () => document.querySelectorAll("[role=dialog]").length;-const flag = (on: boolean) => vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", on ? "1" : "0");async function openShare() {const share = await screen.findAllByRole("button", { name: "Share" });@@ -35,8 +33,7 @@ async function openShare() {}describe.skipIf(!wasmBuilt)("Share and Add an agent", () => {- it("redesign: Share opens Add an agent in its place, and Add an agent opens Share back", async () => {- flag(true);+ it("Share opens Add an agent in its place, and Add an agent opens Share back", async () => {await mountApp(path, HOST);await waitFor(() => expect(q("[data-composer]")).not.toBeNull());await openShare();@@ -63,13 +60,4 @@ describe.skipIf(!wasmBuilt)("Share and Add an agent", () => {await waitFor(() => expect(q("[data-add-agent]")).toBeNull());expect(dialogs()).toBe(1);});-- it("redesign off: the Share sheet has no Add an agent", async () => {- flag(false);- await mountApp(path, HOST);- await waitFor(() => expect(document.body.textContent).toContain("ubuntu-build"));- await openShare();- expect(q("[data-share-add-agent]")).toBeNull();- expect(screen.getByRole("button", { name: "Done" })).toBeTruthy();- });});diff --git a/apps/cua-spaces-web/src/__tests__/shell-parity.test.tsx b/apps/cua-spaces-web/src/__tests__/shell-parity.test.tsxindex d39fd80c7b..ada205a11c 100644--- a/apps/cua-spaces-web/src/__tests__/shell-parity.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/shell-parity.test.tsx@@ -52,22 +52,25 @@ const found = <T extends Element>(selector: string) =>});describe.skipIf(!wasmBuilt)("the shell as the SwiftUI main window (real routes, wasm core)", () => {- it("shows the enroll bar above every page while this device is not enrolled, and Enroll… opens the sheet", async () => {+ it("shows the trust bar above every page while this machine is not trusted, and its button opens the sheet", async () => {const { router } = await mount("/spaces", { unenrolled: true });const bar = await found<HTMLElement>("[data-shell-devices-banner]");- expect(bar.textContent).toMatch(/Enroll this device/);+ expect(bar.textContent).toMatch(/Trust this machine/);await router.navigate({ to: "/keyvault" });await found("[data-shell-devices-banner]");fireEvent.click(await found("[data-shell-banner-enroll]"));- await waitFor(() => expect(router.state.location.pathname).toBe("/settings/devices"));+ await waitFor(() => expect(router.state.location.pathname).toBe("/machines"));await found("[data-enroll]");- // The Devices page says it under its own row: no second bar there.+ // This machine's page says it under its own name: no second bar there.expect(document.querySelector("[data-shell-devices-banner]")).toBeNull();fireEvent.click(await found('[data-enroll-option="sign-in"]'));- await waitFor(() => expect(document.querySelector('[data-this-device-status="enrolled"]')).toBeTruthy());+ await waitFor(() => expect(document.querySelector("[data-machine-details-toggle]")).toBeTruthy());+ const details = document.querySelector<HTMLElement>("[data-machine-details-toggle]")!;+ if (details.getAttribute("aria-expanded") !== "true") fireEvent.click(details);+ await waitFor(() => expect(document.querySelector('[data-machine-trust="enrolled"]')).toBeTruthy());await router.navigate({ to: "/spaces" });await found("[data-space-id]");expect(document.querySelector("[data-shell-devices-banner]")).toBeNull();diff --git a/apps/cua-spaces-web/src/__tests__/space-detail-device.test.tsx b/apps/cua-spaces-web/src/__tests__/space-detail-device.test.tsxindex cf9a2cd612..5f4567f959 100644--- a/apps/cua-spaces-web/src/__tests__/space-detail-device.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/space-detail-device.test.tsx@@ -17,9 +17,9 @@ stubBrowserApis();const NOTICE = {kind: "needs-enrollment",- status: "Not enrolled",- text: "Enroll this Mac to connect to your other machines.",- actionLabel: "Enroll This Mac…",+ status: "Not trusted yet",+ text: "Trust this Mac to connect to your other machines.",+ actionLabel: "Trust this Mac",};/** One of your machines on the relay, answering with `features`. */@@ -89,7 +89,7 @@ describe.skipIf(!wasmBuilt)("a Space's detail as this device sees it (real routeexpect((screen.getByRole("button", { name: /Share/ }) as HTMLButtonElement).disabled).toBe(true);fireEvent.click(screen.getByRole("button", { name: NOTICE.actionLabel }));- await waitFor(() => expect(router.state.location.pathname).toBe("/settings/devices"));+ await waitFor(() => expect(router.state.location.pathname).toBe("/machines"));await waitFor(() => expect(document.querySelector("[data-enroll]")).not.toBeNull());});diff --git a/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx b/apps/cua-spaces-web/src/__tests__/space-thread.test.tsxindex 47c349c0d1..4e62309156 100644--- a/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx@@ -46,9 +46,15 @@ describe("a Space's thread", () => {// The state is kept for logic only: no Working or Failed chip on anyone's message.expect(qa("[data-task]").map((t) => t.dataset.taskState)).toEqual(expect.arrayContaining(["done", "working", "queued"]));expect(qa("[data-task-chip]")).toHaveLength(0);- // Claude Code's reply sits inside the task it answers, with its files.+ // Flat, like a chatroom: Claude Code's reply is its own row, with its files, not nested in the task it answers.const done = q('[data-task-state="done"]')!;- expect(done.querySelector("[data-task-replies] [data-attachment='report.html']")).not.toBeNull();+ expect(done.querySelector("[data-attachment]")).toBeNull();+ expect(qa("[data-task-replies]")).toHaveLength(0);+ const replyRow = q("[data-attachment='report.html']")!.closest("[data-entry]")!;+ expect(replyRow).not.toBeNull();+ expect(done.contains(replyRow)).toBe(false);+ // Each row has its author and time.+ expect(replyRow.querySelector("time")).not.toBeNull();expect(qa("[data-thread-note]").map((n) => n.textContent)).toContain("Hermes woke up and joined");expect(qa("[data-unread]")).toHaveLength(1);await waitFor(() => expect(q("[data-member='agent:claude']")?.textContent).toContain("Claude Code"));@@ -85,9 +91,11 @@ describe("a Space's thread", () => {return t!;});expect(box.value).toBe("");- // The demo's Hermes picks it up and answers under it.+ // The demo's Hermes picks it up and answers on the next row.await waitFor(() => expect(mine.dataset.taskState).toBe("done"), { timeout: 4000 });- expect(mine.querySelector("[data-task-replies]")?.textContent).toContain("Done.");+ const answer = qa("[data-entry]").find((e) => e.textContent?.includes("Done. Nothing else needed from me."))!;+ expect(answer).toBeDefined();+ expect(mine.contains(answer)).toBe(false);});it("shows a live row for an agent at work: within a second, each stage in order, gone when it replies", async () => {@@ -103,8 +111,17 @@ describe("a Space's thread", () => {const stage = q("[data-live-row='hermes']")?.getAttribute("data-live-stage");if (stage && seen[seen.length - 1] !== stage) seen.push(stage);};- const observer = new MutationObserver(watch);- observer.observe(document.body, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-live-stage"] });+ // What the agent has said so far, as it streams: one entry replaced whole each time.+ const said: string[] = [];+ const watchText = () => {+ const t = q("[data-live-entry='hermes'] .select-text")?.textContent?.trim();+ if (t && said[said.length - 1] !== t) said.push(t);+ };+ const observer = new MutationObserver(() => {+ watch();+ watchText();+ });+ observer.observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true, attributeFilter: ["data-live-stage"] });fireEvent.change(box, { target: { value: "@hermes draft the release note", selectionStart: 30 } });const sent = Date.now();await act(async () => {@@ -127,7 +144,10 @@ describe("a Space's thread", () => {await waitFor(() => expect(mine.dataset.taskState).toBe("done"), { timeout: 6000 });await waitFor(() => expect(q("[data-live-row]")).toBeNull());observer.disconnect();- expect(seen).toEqual(["starting", "installing", "starting", "thinking", "using Bash"]);+ expect(seen).toEqual(["starting", "installing", "starting", "thinking", "using Bash", "replying"]);+ // It streamed as whole-text snapshots (each one replaces the last), then the real reply took its place.+ expect(said).toEqual(["Done.", "Done. Nothing else"]);+ expect(q("[data-live-entry]")).toBeNull();// "woke up and joined" came after the agent was up, not before.expect(qa("[data-thread-note]").map((n) => n.textContent)).toContain("Hermes woke up and joined");// No middle dot in the thread or the member list.diff --git a/apps/cua-spaces-web/src/__tests__/spaces-creating-elsewhere.test.tsx b/apps/cua-spaces-web/src/__tests__/spaces-creating-elsewhere.test.tsxindex 866460252f..555a0041b1 100644--- a/apps/cua-spaces-web/src/__tests__/spaces-creating-elsewhere.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/spaces-creating-elsewhere.test.tsx@@ -24,7 +24,7 @@ async function mount(creating: { current: CreatingElsewhere[] }, noSpaces = falsreturn mountApp("/spaces", { failsCreates: false, listsGhost: false, demo: { noSpaces }, creatingElsewhere: () => creating.current });}-describe("a Space another computer is creating", { timeout: 30_000 }, () => {+describe("a Space another machine is creating", { timeout: 30_000 }, () => {it("shows under that computer's name with how far it got, and goes once it is done", async () => {const creating = { current: [...DEMO_CREATING_ELSEWHERE] };const { emit } = await mount(creating);@@ -46,7 +46,7 @@ describe("a Space another computer is creating", { timeout: 30_000 }, () => {await waitFor(() => expect(tile()).toBeNull(), WAIT);});- it("is not the empty home when this computer has no Space yet", async () => {+ it("is not the empty home when this machine has no Space yet", async () => {await mount({ current: [...DEMO_CREATING_ELSEWHERE] }, true);await waitFor(() => expect(tile()).not.toBeNull(), WAIT);expect(document.querySelector("[data-empty-home]")).toBeNull();@@ -58,6 +58,6 @@ describe("creatingElsewhereLine", () => {it("says what, where and how far in plain words", () => {expect(creatingElsewhereLine({ os: "macos", machineName: "Mac mini", percent: 40 })).toBe("Creating macOS on Mac mini… 40%");expect(creatingElsewhereLine({ os: "linux", machineName: "Studio", percent: 99.6 })).toBe("Creating Linux on Studio… 100%");- expect(creatingElsewhereLine({ os: "", machineName: " ", percent: -3 })).toBe("Creating a Space on another computer… 0%");+ expect(creatingElsewhereLine({ os: "", machineName: " ", percent: -3 })).toBe("Creating a Space on another machine… 0%");});});diff --git a/apps/cua-spaces-web/src/__tests__/tips.test.tsx b/apps/cua-spaces-web/src/__tests__/tips.test.tsxindex 31abd174b1..fb960d188d 100644--- a/apps/cua-spaces-web/src/__tests__/tips.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/tips.test.tsx@@ -105,7 +105,7 @@ describe.skipIf(!wasmBuilt)("tips", () => {await act(() => app.router.navigate({ to: "/machines" }));await waitFor(() => expect(sidebarTip()?.getAttribute("data-tip")).toBe("on-auto"));const s = sidebarTip()!;- expect(s.textContent).toContain("New Spaces can go to whichever computer has room.");+ expect(s.textContent).toContain("New Spaces can go to whichever machine has room.");expect(s.querySelector("[data-tip-code]")!.textContent).toBe("cua create --on auto");// Only × in the sidebar: no Next tip, no Don't show tips.expect(within(s).queryByRole("button", { name: "Next tip" })).toBeNull();diff --git a/apps/cua-spaces-web/src/__tests__/upsell.test.tsx b/apps/cua-spaces-web/src/__tests__/upsell.test.tsxindex 507bfd8f08..eb8894a36c 100644--- a/apps/cua-spaces-web/src/__tests__/upsell.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/upsell.test.tsx@@ -93,7 +93,7 @@ describe.skipIf(!wasmBuilt)("in-app Pro and Teams prompts (real routes, wasm corexpect(sessions.hasAttribute("data-full")).toBe(true);const hours = document.querySelector('[data-usage-meter="Remote hours"]')!;expect(document.body.textContent).toContain("Machines in use right now");- expect(document.body.textContent).toContain("Time away from this computer");+ expect(document.body.textContent).toContain("Time away from this machine");expect(hours.getAttribute("aria-valuenow")).toBe("12");expect(hours.hasAttribute("data-full")).toBe(false);const notice = await waitFor(() => {diff --git a/apps/cua-spaces-web/src/bridge/__tests__/agent-detail.test.tsx b/apps/cua-spaces-web/src/bridge/__tests__/agent-detail.test.tsxindex 28c05e1014..531cbe70e2 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/agent-detail.test.tsx+++ b/apps/cua-spaces-web/src/bridge/__tests__/agent-detail.test.tsx@@ -176,7 +176,7 @@ describe.skipIf(!wasmBuilt)("useAgentDetail with the core", () => {await waitFor(() => expect(got.d!.view!.routines.map((l) => l.id)).not.toContain(added.id));});- it("revokes and allows this computer, and shows the agent's audit", async () => {+ it("revokes and allows this machine, and shows the agent's audit", async () => {const got = mount(await testCore());await waitFor(() => expect(got.d?.view?.access.length).toBe(1));expect(got.d!.view!.access[0]).toMatchObject({ text: "This machine", actionLabel: "Revoke" });diff --git a/apps/cua-spaces-web/src/bridge/__tests__/agent-keys-fresh.test.tsx b/apps/cua-spaces-web/src/bridge/__tests__/agent-keys-fresh.test.tsxindex 2912a8363b..c606756852 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/agent-keys-fresh.test.tsx+++ b/apps/cua-spaces-web/src/bridge/__tests__/agent-keys-fresh.test.tsx@@ -1,16 +1,12 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { Suspense } from "react";-import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { cleanup, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it } from "vitest";import type { DataAdapter } from "../adapter";import { createDemoAdapter } from "../adapters/demo";import { AgentKeysStore, type FocusTarget } from "../agent-keys";-import { BridgeProvider } from "../index";import type { HostEvent, OpArgs, OpName } from "../protocol";-import { AccountKeysSection } from "../../components/settings/account-keys";-import { testCore, wasmBuilt } from "./testCore";afterEach(cleanup);@@ -133,89 +129,3 @@ describe("Settings, Connectors keeps its list fresh", () => {demo.dispose?.();});});--describe.skipIf(!wasmBuilt)("the Settings, Connectors account keys", () => {- const Page = AccountKeysSection;- const status = (provider: string) => document.querySelector(`[data-agent-key-provider="${provider}"] [data-agent-key-status]`)?.textContent;- const click = (provider: string, what: "action" | "remove") => {- const b = document.querySelector(`[data-agent-key-provider="${provider}"] [data-agent-key-${what}]`);- if (!b) throw new Error(`no ${what} button on the ${provider} row`);- fireEvent.click(b);- };-- async function mountPage(h: ReturnType<typeof loggedDemo>) {- // The route's component is code-split: load its chunk before the first render.- await (Page as unknown as { preload?: () => Promise<unknown> }).preload?.();- const core = await testCore();- let view!: ReturnType<typeof render>;- await act(async () => {- view = render(- <BridgeProvider adapter={h.adapter} core={core}>- <Suspense fallback={null}>- <Page />- </Suspense>- </BridgeProvider>,- );- });- await waitFor(() => expect(document.querySelector("[data-agent-keys]")).not.toBeNull());- return view;- }-- it("shows a key removed with the CLI after the window gets focus, and Add key lands on the row clicked", async () => {- const h = loggedDemo();- // The CLI added an Anthropic key before the page was opened.- await h.demo.call("agentKeys.set", { provider: "anthropic", value: "sk-ant-test-0000" });- await mountPage(h);- await waitFor(() => expect(status("anthropic")).toBe("•••• 0000"));- expect(status("openai")).toBe("•••• 3f9a");-- // The CLI removes both. Nothing in the app moved, until the window is back.- await h.demo.call("agentKeys.remove", { env: "ANTHROPIC_API_KEY" });- await h.demo.call("agentKeys.remove", { env: "OPENAI_API_KEY" });- expect(status("anthropic")).toBe("•••• 0000");- act(() => {- window.dispatchEvent(new Event("focus"));- });- await waitFor(() => expect(status("anthropic")).toBe("Not set"));- expect(status("openai")).toBe("Not set");-- // Each row's button opens the sheet of its own provider, and Save sends that provider.- for (const [provider, title] of [["openai", /OpenAI/], ["anthropic", /Anthropic/]] as const) {- click(provider, "action");- await waitFor(() => expect(document.querySelector("[data-agent-key-sheet-title]")?.textContent).toMatch(title));- fireEvent.change(document.querySelector("[data-agent-key-value]")!, { target: { value: `sk-${provider}-test-9999` } });- fireEvent.click(document.querySelector("[data-agent-key-save]")!);- await waitFor(() => expect(document.querySelector("[data-agent-key-sheet]")).toBeNull());- expect(h.calls.filter(([op]) => op === "agentKeys.set").at(-1)?.[1]).toMatchObject({ provider });- await waitFor(() => expect(status(provider)).toBe("•••• 9999"));- }- expect(h.calls.filter(([op]) => op === "agentKeys.set").map(([, a]) => (a as { provider: string }).provider)).toEqual(["openai", "anthropic"]);- h.adapter.dispose?.();- });-- it("reads the keys again each time the page is opened", async () => {- const h = loggedDemo();- const first = await mountPage(h);- await waitFor(() => expect(status("openai")).toBe("•••• 3f9a"));- first.unmount();- // Changed with the CLI while another Settings page was open.- await h.demo.call("agentKeys.remove", { env: "OPENAI_API_KEY" });- await mountPage(h);- await waitFor(() => expect(status("openai")).toBe("Not set"));- h.adapter.dispose?.();- });-- it("removes the key of the row clicked", async () => {- const h = loggedDemo();- await h.demo.call("agentKeys.set", { provider: "anthropic", value: "sk-ant-test-0000" });- await mountPage(h);- await waitFor(() => expect(status("anthropic")).toBe("•••• 0000"));- click("anthropic", "remove");- const confirm = await screen.findByRole("button", { name: "Remove" });- fireEvent.click(confirm);- await waitFor(() => expect(status("anthropic")).toBe("Not set"));- expect(h.calls.filter(([op]) => op === "agentKeys.remove").at(-1)?.[1]).toEqual({ env: "ANTHROPIC_API_KEY" });- expect(status("openai")).toBe("•••• 3f9a");- h.adapter.dispose?.();- });-});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/agent-keys-hosts.test.tsx b/apps/cua-spaces-web/src/bridge/__tests__/agent-keys-hosts.test.tsxindex 3923a8e602..9d83535621 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/agent-keys-hosts.test.tsx+++ b/apps/cua-spaces-web/src/bridge/__tests__/agent-keys-hosts.test.tsx@@ -1,18 +1,10 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { Suspense } from "react";-import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it } from "vitest";-import { createDemoAdapter } from "../adapters/demo";+import { describe, expect, it } from "vitest";import { agentKeyForm, agentKeysView } from "../agent-keys";-import { BridgeProvider } from "../index";-import { AccountKeysSection } from "../../components/settings/account-keys";-import { plainKeysIntro } from "../../lib/settings-copy";import { testCore, wasmBuilt } from "./testCore";-afterEach(cleanup);-/** What Settings, Connectors says about where a saved key stays, per system. */const WORDS = {macos: {@@ -50,34 +42,4 @@ describe.skipIf(!wasmBuilt)("Settings, Connectors says where keys stay in the syexpect(words, os).not.toMatch(/Keychain|Mac/);}});-- it("draws the words of the shell's system (Electron reports its platform)", async () => {- const host = window as unknown as { cuaDesktop?: { platform: string } };- const Page = AccountKeysSection;- await (Page as unknown as { preload?: () => Promise<unknown> }).preload?.();- const core = await testCore();- try {- for (const [platform, os] of [["darwin", "macos"], ["win32", "windows"], ["linux", "linux"]] as const) {- host.cuaDesktop = { platform };- const adapter = createDemoAdapter({ latencyMs: 0, stepMs: 2 });- let view!: ReturnType<typeof render>;- await act(async () => {- view = render(- <BridgeProvider adapter={adapter} core={core}>- <Suspense fallback={null}>- <Page />- </Suspense>- </BridgeProvider>,- );- });- await waitFor(() => expect(document.querySelector("[data-agent-keys-intro]")?.textContent).toBe(plainKeysIntro(WORDS[os].intro)));- fireEvent.click(document.querySelector('[data-agent-key-provider="anthropic"] [data-agent-key-action]')!);- await waitFor(() => expect(document.querySelector("[data-agent-key-value-help]")?.textContent).toBe(WORDS[os].help));- view.unmount();- adapter.dispose?.();- }- } finally {- delete host.cuaDesktop;- }- });});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex f123b820c6..51be83b84d 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -95,6 +95,7 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"sharing.removals": {},"sharing.ackRemovals": {},"agentKeys.list": {},+ "agentKeys.check": {},"agentKeys.set": { provider: "anthropic", value: "sk-ant-test-0000" },"agentKeys.remove": { env: "ANTHROPIC_API_KEY" },"agentKeys.shell": {},diff --git a/apps/cua-spaces-web/src/bridge/__tests__/detail.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/detail.test.tsindex 0edf013ab0..bf1d9d86b0 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/detail.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/detail.test.ts@@ -171,12 +171,12 @@ describe("this device's access to its machines", () => {});});-describe("this computer on the relay (CUA-1527)", () => {+describe("this machine on the relay (CUA-1527)", () => {const HOST = "09c8b17b5a55f89bc1e376eaeabf111f";const wkSpace = (id: string, name: string, host?: string) => ({ space: { id, name, provider: "relay", status: "running", os: "linux", host, hostName: host ? "lg-x11" : undefined } });const status = { configured: true, mode: "relay", machineId: HOST, name: "lg-x11", sharing: true, serviceInstalled: true, serviceRunning: true, serviceKind: "systemd", clients: [], permissions: [] };- it("lists the machine that is set up for access once, as This computer, with its Spaces", () => {+ it("lists the machine that is set up for access once, as This machine, with its Spaces", () => {const spaces = { spaces: [wkSpace("relay:space-16dec1e7810d08b6", "remote-from-wl", HOST), wkSpace(`relay:${HOST}`, "lg-x11")] };const rows = toMachineRows(spaces as never, { devices: null, signedIn: true, host: status } as never, "linux");expect(rows.map((r) => r.name)).toEqual(["This machine"]);@@ -184,7 +184,7 @@ describe("this computer on the relay (CUA-1527)", () => {expect(machines).toHaveLength(1);});- it("puts the Spaces this machine provides on This computer", () => {+ it("puts the Spaces this machine provides on This machine", () => {const rows = toMachineRows({ spaces: [wkSpace("relay:space-16dec1e7810d08b6", "remote-from-wl", HOST)] } as never, { devices: null, signedIn: true, host: status } as never, "linux");const here = rows.find((r) => r.current)!;expect(machineIdOf({ id: "relay:space-16dec1e7810d08b6", provider: "relay", host: HOST }, rows)).toBe(here.id);diff --git a/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.tsindex 43df2ae9da..7e90526032 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts@@ -584,14 +584,14 @@ describe("webkit adapter", () => {});it("maps this Mac's own desktop (status local) to a local, running row", async () => {- const here = { id: "local", name: "This computer", os: "macos", status: "local", detail: "", lastUsedAt: 1, provider: null, sdk: null, power: null };+ const here = { id: "local", name: "This machine", os: "macos", status: "local", detail: "", lastUsedAt: 1, provider: null, sdk: null, power: null };const { win } = webkitHost(() => ok({ loaded: true, selectedId: null, spaces: [{ space: here, deleting: false }] }));const [row] = await createWebkitAdapter(win).call("spaces.list", {});expect(row).toMatchObject({ provider: "local", reachable: true, powerState: "running" });});it("keeps this Mac local while it is not set up for access", async () => {- const mac = { id: "this-mac", name: "This computer", os: "macos", status: "suspended", detail: "Set up for access", lastUsedAt: 1, provider: null, sdk: null, power: null };+ const mac = { id: "this-mac", name: "This machine", os: "macos", status: "suspended", detail: "Set up for access", lastUsedAt: 1, provider: null, sdk: null, power: null };const { win } = webkitHost(() => ok({ loaded: true, selectedId: null, spaces: [{ space: mac, deleting: false }] }));const [row] = await createWebkitAdapter(win).call("spaces.list", {});expect(row).toMatchObject({ provider: "local", reachable: false, powerState: "suspended" });diff --git a/apps/cua-spaces-web/src/bridge/__tests__/settings.test.tsx b/apps/cua-spaces-web/src/bridge/__tests__/settings.test.tsxindex e7dc3f397d..c82613834d 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/settings.test.tsx+++ b/apps/cua-spaces-web/src/bridge/__tests__/settings.test.tsx@@ -108,7 +108,7 @@ describe.skipIf(!wasmBuilt)("Settings and Notifications through the core", () =>hooks.devices.setApprovalCode("k7qx m2rp");await waitFor(() => expect(hooks.devices.data?.approve?.view?.code).toBe("K7QX-M2RP"));await hooks.devices.approve();- await waitFor(() => expect(hooks.devices.data?.view?.rows.find((r) => r.id === "dev_work")?.subtitle).toMatch(/^Enrolled/));+ await waitFor(() => expect(hooks.devices.data?.view?.rows.find((r) => r.id === "dev_work")?.subtitle).toMatch(/^Trusted/));expect(hooks.devices.data?.approve).toBeNull();await hooks.devices.revoke("dev_studio");await waitFor(() => expect(hooks.devices.data?.view?.rows.find((r) => r.id === "dev_studio")?.subtitle).toBe("Revoked"));diff --git a/apps/cua-spaces-web/src/bridge/__tests__/sign-in-adds-computer.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/sign-in-adds-computer.test.tsindex 438571de00..09734cd63b 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/sign-in-adds-computer.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/sign-in-adds-computer.test.ts@@ -26,7 +26,7 @@ function host({ signedIn, configured }: { signedIn: boolean; configured: booleanreturn { adapter, setups };}-describe.skipIf(!wasmBuilt)("signing in adds this computer", () => {+describe.skipIf(!wasmBuilt)("signing in adds this machine", () => {it("a sign-in on a computer that isn't set up sets it up to provide Spaces, its screen private", async () => {const { adapter, setups } = host({ signedIn: false, configured: false });const store = new BridgeStore(adapter, await testCore());diff --git a/apps/cua-spaces-web/src/bridge/__tests__/thread.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/thread.test.tsindex d35f9de826..8101272c78 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/thread.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/thread.test.ts@@ -160,7 +160,7 @@ describe("the thread tools' JSON", () => {});describe("folding the thread", () => {- it("folds a task's state from its updates and nests its replies", () => {+ it("folds a task's state from its updates, and its reply is its own row, in order", () => {seq = 0;const task = entry({ text: "@claude run the suite", task: { to: "claude", session: null } });const entries = [@@ -172,10 +172,17 @@ describe("folding the thread", () => {entry({ author: GRACE, text: "nice" }),];const items = foldThread(entries);- expect(items.map((i) => i.type)).toEqual(["task", "message"]);+ // Flat: the task, its reply, then the next message, one row each, nothing nested.+ expect(items.map((i) => i.type)).toEqual(["task", "message", "message"]);const t = items[0] as Extract<(typeof items)[number], { type: "task" }>;expect(t.state).toBe("done");- expect(t.replies.map((r) => r.text)).toEqual(["146 passed, 2 failed"]);+ expect("replies" in t || "notes" in t).toBe(false);+ const reply = items[1] as Extract<(typeof items)[number], { type: "message" }>;+ expect(reply.entry.text).toBe("146 passed, 2 failed");+ // The reply knows what it answers (for a quote, and for Retry); an ordinary message does not.+ expect(reply.quote).toMatchObject({ seq: task.seq, text: "@claude run the suite" });+ expect(reply.taskText).toBe("@claude run the suite");+ expect((items[2] as Extract<(typeof items)[number], { type: "message" }>).quote).toBeNull();});it("keeps a task queued until it is picked up, and shows a failure", () => {@@ -197,14 +204,13 @@ describe("folding the thread", () => {entry({ author: SYSTEM, kind: "system", text: "Hermes woke up and joined" }),entry({ author: GRACE, kind: "answer", text: "Approved", answer: { approval: ask.seq, approve: true, note: null } }),]);- // The update's note belongs to its task; a note about no task stands alone.- expect(items.map((i) => (i.type === "system" ? i.text : i.type))).toEqual(["approval", "task", "Hermes woke up and joined"]);- expect((items[1] as Extract<(typeof items)[number], { type: "task" }>).notes.map((n) => n.text)).toEqual(["Session 2 picked this up"]);+ // Notes are muted lines in sequence, whether or not they are about a task.+ expect(items.map((i) => (i.type === "system" ? i.text : i.type))).toEqual(["approval", "task", "Session 2 picked this up", "Hermes woke up and joined"]);const a = items[0] as Extract<(typeof items)[number], { type: "approval" }>;expect(a.answer).toMatchObject({ approve: true, by: GRACE });});- it("shows a note about a task inside that task, in order with its replies", () => {+ it("puts a note about a task, and its reply, in sequence with everything else", () => {seq = 0;const task = entry({ author: CLAUDE, task: { to: "hermes", session: null } });const woke = entry({ author: SYSTEM, kind: "system", text: "Hermes woke up and joined", noteFor: task.seq });@@ -212,10 +218,7 @@ describe("folding the thread", () => {const claimed = update(task.seq, "claimed", "Session 2 picked this up");const elsewhere = entry({ author: SYSTEM, kind: "system", text: "about a task not on this page", noteFor: 999 });const items = foldThread([task, woke, reply, claimed, elsewhere]);- expect(items.map((i) => i.type)).toEqual(["task", "system"]);- const t = items[0] as Extract<(typeof items)[number], { type: "task" }>;- expect(t.notes.map((n) => n.text)).toEqual(["Hermes woke up and joined", "Session 2 picked this up"]);- expect(t.replies).toEqual([reply]);+ expect(items.map((i) => (i.type === "system" ? i.text : i.type))).toEqual(["task", "Hermes woke up and joined", "message", "Session 2 picked this up", "about a task not on this page"]);});it("puts the unread divider before the first entry someone else wrote after the cursor", () => {@@ -225,8 +228,8 @@ describe("folding the thread", () => {const task = entry({ task: { to: "claude", session: null } });const reply = entry({ author: CLAUDE, replyTo: task.seq, text: "done" });const items = foldThread([read, mine, task, reply], { readSeq: read.seq, me: "acct_ada" });- // Mine and my task are not unread; Claude's reply nested in the task is.- expect(items.map((i) => i.type)).toEqual(["message", "message", "unread", "task"]);+ // Mine and my task are not unread; Claude's reply (its own row now) is, and the divider sits before it.+ expect(items.map((i) => i.type)).toEqual(["message", "message", "task", "unread", "message"]);expect(foldThread([read], { readSeq: read.seq, me: "acct_ada" }).some((i) => i.type === "unread")).toBe(false);expect(foldThread([read, mine], { readSeq: null }).some((i) => i.type === "unread")).toBe(false);});@@ -253,7 +256,7 @@ describe("the demo host's thread", () => {expect(states).toEqual(expect.arrayContaining(["done", "working", "queued"]));expect(items.some((i) => i.type === "approval" && i.answer === null)).toBe(true);expect(items.some((i) => i.type === "unread")).toBe(true);- expect(items.some((i) => i.type === "task" && i.notes.some((n) => n.text === "Hermes woke up and joined"))).toBe(true);+ expect(items.some((i) => i.type === "system" && i.text === "Hermes woke up and joined")).toBe(true);expect(page.hasMoreBefore).toBe(false);const posted = await demo.call("thread.post", { spaceId: "local:design-review", text: "hello" });expect(posted?.text).toBe("hello");diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo-agents.ts b/apps/cua-spaces-web/src/bridge/adapters/demo-agents.tsindex 5e0413cd1c..8e06d32c14 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo-agents.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo-agents.ts@@ -398,7 +398,7 @@ export function demoStartedRun(space: string, runId: string, agent: string, promspace,live: true,events: s.events,- asks: { title: "Sign in to GitHub", detail: "The agent needs a GitHub sign-in on this computer to post the result." },+ asks: { title: "Sign in to GitHub", detail: "The agent needs a GitHub sign-in on this machine to post the result." },run: {runId,agent,@@ -418,7 +418,7 @@ export function demoReply(rec: DemoRunRecord, text: string, t: number): void {const s = Script.after(written, t).prompt(text);if (/sign|signed|logged|done|go ahead|yes/i.test(text)) {s.tool("execute", "gh pr comment --body-file result.md", "completed", "Posted a comment", 2200)- .say("Posted the result on your pull request. You can keep this computer for the next check, or throw it away.", 80);+ .say("Posted the result on your pull request. You can keep this machine for the next check, or throw it away.", 80);} else {s.thought("Read the reply and carry on.", 800).say("Got it. I'll go on with that.", 80);}diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex 7865cebed5..8030574882 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -73,6 +73,10 @@ export interface DemoOptions {keyvaultLocked?: boolean;/** Start with no Keyvault (`?demo=novault`). */noVault?: boolean;+ /** Machines that are only signed in (`?demo=signed-in-machines`): rows in the one list, "Signed in, not sharing", and the two that wait to be added. */+ signedInMachines?: boolean;+ /** Saved credentials the provider refuses (`?demo=rejected-key`: the OpenAI key): a check marks them as needing a reconnect. */+ rejectedKeys?: string[];/** Start with no Spaces (the first-Space empty state). */noSpaces?: boolean;/** This many more Spaces on the list, for scale (`?demo=scale-1000`;@@ -172,6 +176,16 @@ const DEMO_NOTES = "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3* Space and the first Space offers see it too), and `?demo=intel-mac` /* `?demo=linux-pc` (an Intel Mac, an x64 Linux PC with QEMU), and* `?demo=creating-elsewhere` (the Mac mini is creating a Space). */+/** The account's signed-in machines that share nothing, as a host lists them (`?demo=signed-in-machines`): one enrolled, and the demo devices that wait. */+function demoSignedInRows(nowMs: number): MachineRow[] {+ const t = Math.floor(nowMs / 1000);+ return [+ { id: "dev_laptop", name: "Ana's laptop", via: "relay", online: false, os: "macos", device: true, deviceState: "enrolled", lastSeen: t - 2 * 3600, limits: [] },+ { id: "dev_work", name: "Work laptop", via: "relay", online: false, os: "windows", device: true, deviceState: "pending", lastSeen: t - 120, limits: [] },+ { id: "dev_old", name: "Old laptop", via: "relay", online: false, os: "linux", device: true, deviceState: "expired", lastSeen: t - 33 * 86_400, limits: [] },+ ];+}+/** `count` plain Spaces for scale: alternating systems, places and states,* each with its own id, name and time (`?demo=scale-N`). */export function demoScaleRows(now: number, count: number): SpaceRow[] {@@ -206,6 +220,8 @@ export function demoOptionsFromSearch(search: string): DemoOptions {onboarded: !flags.has("fresh"),keyvaultLocked: flags.has("locked"),noVault: flags.has("novault"),+ ...(flags.has("signed-in-machines") ? { signedInMachines: true } : {}),+ ...(flags.has("rejected-key") ? { rejectedKeys: ["OPENAI_API_KEY"] } : {}),noSpaces: flags.has("empty"),...(() => {const scale = [...flags].find((f) => /^scale-\d+$/.test(f));@@ -317,7 +333,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re// A named allowance is for showing the prompts, which wait for no agent run.runs: options.usage ? [] : demoRunRecords(now()),imported: [],- keyStore: demoKeyStore(now),+ keyStore: demoKeyStore(now, options.rejectedKeys ?? []),readOnlyAgents: options.agentsReadOnly ?? [],agentSetup: demoAgentSetup(options.onboarded === false || options.agents === "unset", options.agents === "none" ? [] : options.agents === "codex" ? ["codex"] : null),platform: options.platform ?? MAC_DEMO_PLATFORM,@@ -588,6 +604,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...demoMachineRows(now(), state.host, state.platform),...(options.manyMachines ? Array.from({ length: 14 }, (_, i) => demoExtraMachine(i)) : []),...state.paired.map((m) => ({ ...m, limits: [...m.limits] })),+ ...(options.signedInMachines ? demoSignedInRows(now()) : []),].filter((m) => !state.removed.includes(m.id)).map((m) => (state.renamed[m.id] ? { ...m, name: state.renamed[m.id]! } : m)),@@ -855,7 +872,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re"agents.signIn": async ({ agent }) => {const row = state.agentSetup.find((r) => r.agent === agent);if (!row?.signIn) throw new Error(`${row?.name ?? agent} has no sign-in Cua can start`);- if (!row.installed) throw new Error(`${row.name} isn't installed on this computer`);+ if (!row.installed) throw new Error(`${row.name} isn't installed on this machine`);setTimeout(() => {state.agentSetup = state.agentSetup.map((r) => (r.agent === agent ? { ...r, signedIn: true } : r));}, step * 40);diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.tsindex 0e22c01cb5..1d8505d4fa 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.ts@@ -20,10 +20,13 @@ const providerOf = (env: string): AgentKeyProvider => PROVIDERS.find((p) => p.en/** The demo's saved keys, shared with Connect (a sign-in Connect copies lands here, as in the daemon's store). */export interface DemoKeyStore {keys: AgentKeyInfo[];+ /** Variables the provider refuses: a check marks them `expired` (needs a reconnect). `?demo=rejected-key`. */+ rejected: string[];}-export const demoKeyStore = (now: () => number): DemoKeyStore => ({+export const demoKeyStore = (now: () => number, rejected: string[] = []): DemoKeyStore => ({keys: [{ provider: "openai", env: "OPENAI_API_KEY", last4: "3f9a", addedMs: now() - 6 * 24 * 3600_000 }],+ rejected,});export function demoAgentKeysHandlers({@@ -36,11 +39,17 @@ export function demoAgentKeysHandlers({stepMs: number;now: () => number;store?: DemoKeyStore;-}): DemoHandlers<"agentKeys.list" | "agentKeys.set" | "agentKeys.remove" | "agentKeys.shell" | "agentKeys.fromShell"> {+}): DemoHandlers<"agentKeys.list" | "agentKeys.check" | "agentKeys.set" | "agentKeys.remove" | "agentKeys.shell" | "agentKeys.fromShell"> {const keys = () => store.keys;const report = (): AgentKeysReport => ({ keys: keys().map((k) => ({ ...k })), providers: PROVIDERS, available: true, unavailable: null });return {"agentKeys.list": () => report(),+ // The providers answer: the keys they refuse need a reconnect, and a key saved again is not refused.+ "agentKeys.check": async () => {+ await wait(stepMs / 2);+ const r = report();+ return { ...r, keys: r.keys.map((k) => (store.rejected.includes(k.env) ? { ...k, expired: true } : k)) };+ },"agentKeys.set": async ({ provider, env, value }) => {const name = provider === "other" ? (env ?? "").trim() : PROVIDERS.find((p) => p.id === provider)?.env;if (!name) throw new HostError(`unknown provider ${provider}`);@@ -50,6 +59,7 @@ export function demoAgentKeysHandlers({if (!v) throw new HostError("the key is empty");// The Keychain write.await wait(stepMs / 2);+ store.rejected = store.rejected.filter((e) => e !== name);store.keys = [...keys().filter((k) => k.env !== name), { provider: providerOf(name), env: name, last4: v.length >= 12 ? v.slice(-4) : "", addedMs: now() }].sort((a, b) => a.env.localeCompare(b.env),);diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/host-setup.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/host-setup.tsindex 469faa6e32..fadac56aff 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/host-setup.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/host-setup.ts@@ -54,7 +54,7 @@ export function demoHostSetupHandlers({ state, now, wait, emit, stepMs }: DemoCo"host.action": async ({ action }) => {await wait(stepMs);const h = state.host;- if (!h.configured) throw new HostError("This computer is not set up for access", "not_configured");+ if (!h.configured) throw new HostError("This machine is not set up for access", "not_configured");switch (action) {case "stop-sharing":return set({ ...h, sharing: false, clients: [] });diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/new-space.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/new-space.tsindex fcf4f0471a..18b4f89b42 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/new-space.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/new-space.ts@@ -181,7 +181,7 @@ function applyDemoClouds(providers: CloudProviderWire[], variant: DemoClouds): vif (variant === "revoked") {Object.assign(aws, {status: "failed",- issue: "AWS was disconnected on another device, and 3 machines this computer made may still run there. Reconnect, then delete them, or delete them in the AWS console.",+ issue: "AWS was disconnected on another device, and 3 machines this machine made may still run there. Reconnect, then delete them, or delete them in the AWS console.",});}}@@ -337,7 +337,7 @@ export function newSpaceDemoHandlers({ state, wait, emit, step, now }: NewSpaceDconst p = find(target);await wait(step * 2);if (!p.credentials?.found && !target.token) {- return { provider: p.name, ok: false, checks: [{ name: "credentials", ok: false, detail: p.name === "hetzner" ? "paste a Hetzner project API token" : `no ${p.title} sign-in on this computer` }] };+ return { provider: p.name, ok: false, checks: [{ name: "credentials", ok: false, detail: p.name === "hetzner" ? "paste a Hetzner project API token" : `no ${p.title} sign-in on this machine` }] };}const where = placeOf(p, target);return {@@ -374,7 +374,7 @@ export function newSpaceDemoHandlers({ state, wait, emit, step, now }: NewSpaceDObject.assign(p, limits, { connected: true, auth: "oidc", status: "connected", account: target.account_id, label: `AWS · ${region}`, suggest_auth: "", issue: "", profile: "" });return { ...p, checks: [{ name: "credentials", ok: true, detail: `account ${target.account_id}` }], verify: "cua cloud status aws" };}- if (!p.credentials?.found && !target.token) throw new HostError(`no ${p.title} sign-in on this computer`, "failed");+ if (!p.credentials?.found && !target.token) throw new HostError(`no ${p.title} sign-in on this machine`, "failed");const where = placeOf(p, target);p.connected = true;p.status = "connected";diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.tsindex 12f608573c..8c193c4c9d 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts@@ -77,16 +77,17 @@ export function demoDevices(nowMs: number, unenrolled = false): DevicesInput {{ id: "dev_old", name: "Old laptop", state: "expired", platform: "linux", enrolledUntil: now - 2 * DAY, lastSeen: now - 33 * DAY },],audit: [- { ts: now - 5 * 3600, kind: "machine_access", device: "dev_studio", machine: "m1", detail: "owner" },- { ts: now - 2 * 3600, kind: "shared_access", machine: "m1", subject: "[email protected]" },+ { ts: now - 5 * 3600, kind: "machine_access", device: "dev_studio", machine: "studio-pc", detail: "owner" },+ { ts: now - 2 * 3600, kind: "shared_access", machine: "studio-pc", subject: "[email protected]" },{ ts: now - 1800, kind: "device_registered", device: "dev_work" },- { ts: now - 600, kind: "machine_access", device: "dev_mac", machine: "m2", detail: "owner" },+ { ts: now - 900, kind: "machine_access", device: "dev_studio", machine: "this-mac", detail: "owner" },+ { ts: now - 600, kind: "machine_access", device: "dev_mac", machine: "mac-mini", detail: "owner" },],enforceAfter: now - 30 * DAY,- machineNames: { m1: "studio-mac", m2: "mac-mini" },+ machineNames: { "studio-pc": "Studio PC", "mac-mini": "Mac mini", "this-mac": "This Mac" },machines: [- { id: "m1", name: "studio-mac", confirmed: true },- { id: "m2", name: "mac-mini", confirmed: true },+ { id: "studio-pc", name: "Studio PC", confirmed: true },+ { id: "mac-mini", name: "Mac mini", confirmed: true },],};}@@ -286,7 +287,7 @@ export function createDemoSettings(ctx: DemoSettingsContext): Handlers {// Works like the relay: one code per machine, 30 minutes, shown once.// The demo's other computer runs the command after a few reads."devices.createPairingCode": async ({ team }) => {- if (!ctx.signedIn()) throw new HostError("Sign in to Cua to add a computer", "signed_out");+ if (!ctx.signedIn()) throw new HostError("Sign in to Cua to add a machine", "signed_out");await wait(stepMs / 2);const t = Math.floor(now() / 1000);pairingSeq += 1;diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/thread.tsindex 0d29829aff..14d1f47a3a 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts@@ -570,17 +570,20 @@ export function demoThreadHandlers({waiting.delete(space);};// Each agent's stage while it works on a task (`thread_read`'s `live`), by Space.- const stages = new Map<string, Map<string, string>>();+ const stages = new Map<string, Map<string, { stage: string; since: number; text?: string }>>();const liveOf = (space: string) => {- const agents = [...(stages.get(space) ?? [])].map(([agent, stage]) => ({ agent, stage })).sort((a, b) => a.agent.localeCompare(b.agent));- return { key: agents.map((a) => `${a.agent}=${a.stage}`).join(";"), agents };+ const agents = [...(stages.get(space) ?? [])]+ .map(([agent, s]) => ({ agent, stage: s.stage, since_ms: s.since, ...(s.text ? { text: s.text } : {}) }))+ .sort((a, b) => a.agent.localeCompare(b.agent));+ // As the daemon keys it: the text's length moves it too, so a follow wakes for a new snapshot.+ return { key: agents.map((a) => `${a.agent}=${a.stage}#${a.text?.length ?? 0}`).join(";"), agents };};- /** Sets (or with null clears) an agent's stage and wakes the thread's followers. */- const setStage = (space: string, agent: string, stage: string | null) => {- const m = stages.get(space) ?? new Map<string, string>();+ /** Sets (or with null clears) an agent's stage, and what it has said so far, and wakes the thread's followers. */+ const setStage = (space: string, agent: string, stage: string | null, text?: string) => {+ const m = stages.get(space) ?? new Map<string, { stage: string; since: number; text?: string }>();stages.set(space, m);if (stage === null) m.delete(agent);- else m.set(agent, stage);+ else m.set(agent, { stage, since: m.get(agent)?.since ?? now(), ...(text ? { text } : {}) });wake(space);};const append = (space: string, e: Json) => {@@ -676,7 +679,13 @@ export function demoThreadHandlers({setStage(space, agent, "using Bash");if (member) Object.assign(member, { activity: "Using Bash" });await wait(stepMs * 2);- append(space, { author: { kind: "agent", id: `agent:${agent}`, name: agent, ...(member ? { identity: member.identity } : {}) }, reply_to: task, text: "Done. Nothing else needed from me." });+ // It starts to answer: what it has said so far streams as one entry, replaced whole each time.+ const said = "Done. Nothing else needed from me.";+ for (const part of [said.slice(0, 5), said.slice(0, 18)]) {+ setStage(space, agent, "replying", part);+ await wait(stepMs);+ }+ append(space, { author: { kind: "agent", id: `agent:${agent}`, name: agent, ...(member ? { identity: member.identity } : {}) }, reply_to: task, text: said });setStage(space, agent, null);append(space, { author: system, kind: "task_update", update: { task, state: "done", session: 1, note: null } });if (member) Object.assign(member, { status: "idle", activity: null });diff --git a/apps/cua-spaces-web/src/bridge/agent-keys.ts b/apps/cua-spaces-web/src/bridge/agent-keys.tsindex d8b8d1f175..e627f031ae 100644--- a/apps/cua-spaces-web/src/bridge/agent-keys.ts+++ b/apps/cua-spaces-web/src/bridge/agent-keys.ts@@ -174,9 +174,9 @@ export class AgentKeysStore {return done;}- private async read(epoch: number): Promise<void> {+ private async read(epoch: number, op: "agentKeys.list" | "agentKeys.check" = "agentKeys.list"): Promise<void> {try {- const report = await this.adapter.call("agentKeys.list", {});+ const report = await this.adapter.call(op, {});if (!this.pinned && epoch === this.epoch) this.set({ report, error: null });} catch (e) {if (this.pinned || epoch !== this.epoch) return;@@ -185,6 +185,17 @@ export class AgentKeysStore {}}+ /**+ * Reads the list after the providers were asked whether the saved API keys still work+ * (`agentKeys.check`: cheap, answers reused for a few minutes, never logged), so a key that was+ * revoked reads "Needs reconnect" instead of "Connected". Falls back to the plain list on a host+ * without the check. Opening Settings, Connectors and the Agents page does this.+ */+ check(): Promise<void> {+ const epoch = this.epoch;+ return this.read(epoch, "agentKeys.check").then(() => undefined);+ }+/** Reads the list now, and again whenever the window gets focus, the document becomes visible* or the host says agents changed. Returns the stop. */watch(target: FocusTarget | undefined = typeof window === "undefined" ? undefined : window): () => void {@@ -265,6 +276,8 @@ export interface AgentKeysHook extends AgentKeysState {view: AgentKeysView | null;core: CoreClient;refresh(): Promise<void>;+ /** The list after the providers were asked whether the saved keys still work. */+ check(): Promise<void>;/** Adds or replaces a key; `env` names an Other key. */save(provider: AgentKeyProvider, value: string, env: string | null): Promise<void>;remove(env: string): Promise<void>;@@ -277,6 +290,15 @@ export interface AgentKeysHook extends AgentKeysState {const noopSubscribe = () => () => {};+/** Asks the providers whether the saved sign-ins and keys still work, once when the page that calls it opens. */+export function useKeysRecheck(): void {+ const ctx = useContext(BridgeContext);+ const store = ctx?.adapter ? agentKeysStore(ctx.adapter) : null;+ useEffect(() => {+ void store?.check();+ }, [store]);+}+/** `watch`: read the list again whenever the page is in front (mounted), the window gets focus* or the document becomes visible, so a key changed with the CLI shows up. */export function useAgentKeys({ watch = false }: { watch?: boolean } = {}): AgentKeysHook {@@ -298,6 +320,7 @@ export function useAgentKeys({ watch = false }: { watch?: boolean } = {}): Agentview: agentKeysView(ctx.core, input),core: ctx.core,refresh: () => (store ? store.refresh() : Promise.resolve()),+ check: () => (store ? store.check() : Promise.resolve()),save: (provider, value, env) => need().save(provider, value, env),remove: (env) => need().remove(env),openSheet: (provider, env = null) => store?.openSheet(provider, env),diff --git a/apps/cua-spaces-web/src/bridge/connectors.ts b/apps/cua-spaces-web/src/bridge/connectors.tsindex 6442ac6e43..a442707553 100644--- a/apps/cua-spaces-web/src/bridge/connectors.ts+++ b/apps/cua-spaces-web/src/bridge/connectors.ts@@ -2,7 +2,7 @@// Copyright (c) 2026 Cua AI, Inc./**- * Settings → Connectors (redesign) and summoning agents in a Space: the+ * Settings → Connectors and summoning agents in a Space: the* app core's `connectors.*` and `summon.*` (`connectors.rs`, `summon.rs`)* over what the host already answers (`agents.setup`, `agentKeys.list`).* Every word, state and rule is the core's; this file only shapes inputsdiff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex f51566c53c..f780a6dcc2 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -7133,6 +7133,9 @@"about.set": {"$ref": "#/$defs/AboutInput"},+ "agentKeys.check": {+ "$ref": "#/$defs/AgentKeysReport"+ },"agentKeys.fromShell": {"$ref": "#/$defs/AgentKeysReport"},@@ -9034,6 +9037,12 @@},"stage": {"type": "string"+ },+ "sinceMs": {+ "type": "number"+ },+ "text": {+ "type": "string"}},"required": [@@ -9170,6 +9179,75 @@"about.set": {"$ref": "#/$defs/AboutInput"},+ "agentKeys.check": {+ "type": "object",+ "properties": {+ "keys": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string"+ },+ "env": {+ "type": "string"+ },+ "last4": {+ "type": "string"+ },+ "added_ms": {+ "type": "number"+ },+ "expired": {+ "type": "boolean"+ }+ },+ "required": [+ "provider",+ "env",+ "last4",+ "added_ms"+ ]+ }+ },+ "providers": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "env": {+ "type": "string"+ },+ "label": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "env"+ ]+ }+ },+ "available": {+ "type": "boolean"+ },+ "unavailable": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "keys",+ "providers",+ "available"+ ]+ },"agentKeys.fromShell": {"type": "object","properties": {diff --git a/apps/cua-spaces-web/src/bridge/contracts/devices.ts b/apps/cua-spaces-web/src/bridge/contracts/devices.tsindex 5986eb49b7..13f2d9e8ad 100644--- a/apps/cua-spaces-web/src/bridge/contracts/devices.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/devices.ts@@ -291,3 +291,63 @@ export interface TeamsList {/** The saved current team (Settings, Teams), or null. */currentTeamId: string | null;}++/* ---- The account's part of the Machines page (`machines_account.rs`) --------- */++/** `machines_account::PendingKind`. */+export type PendingKind = "machine" | "sign-in";++/** A machine waiting to be added (`machines_account::PendingMachine`). */+export interface PendingMachine {+ id: string;+ kind: PendingKind;+ name: string;+ /** `macOS`, `Windows`, `Linux`, or empty. */+ os: string;+ line: string;+ /** When it last reached the relay (Unix seconds). */+ since: number | null;+ /** The question the "Add this machine?" page asks. */+ text: string;+ machine: string | null;+ device: string | null;+ expired: boolean;+ requiresPresence: boolean;+ notifyTitle: string;+ notifyBody: string;+ addLabel: string;+ notMeLabel: string;+}++/** This machine's own trust, in plain words (`machines_account::ThisMachineTrust`). */+export interface ThisMachineTrust {+ kind: EnrollmentKind;+ /** "Trusted until", "Not trusted yet", ... */+ status: string;+ /** Unix seconds; the page formats it. */+ at: number | null;+ text: string | null;+ tone: "warning" | "critical" | null;+ actionLabel: string | null;+}++/** Who reached a machine (`machines_account::AccessLine`). */+export interface AccessLine {+ ts: number;+ text: string;+ notable: boolean;+ machine: string | null;+ device: string | null;+}++/** `machines_account::MachinesAccountView`. */+export interface MachinesAccountView {+ pending: PendingMachine[];+ pendingCount: number;+ pendingTitle: string;+ thisMachine: ThisMachineTrust | null;+ access: AccessLine[];+ recentTitle: string;+ recentEmpty: string;+ readError: string | null;+}diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 76f64fe974..9b89737736 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -975,7 +975,7 @@ const JoinCodeRowShape = obj<JoinCodeRow>()({});const ThreadPageShape = obj<ThreadPage>()({entries: list(ThreadEntryShape),- live: obj<ThreadLive>()({ key: str, agents: list(obj<LiveAgent>()({ agent: str, stage: str })) }),+ live: obj<ThreadLive>()({ key: str, agents: list(obj<LiveAgent>()({ agent: str, stage: str, sinceMs: opt(num), text: opt(str) })) }),cursor: num,caughtUp: bool,unread: num,@@ -1318,6 +1318,7 @@ export const OP_SHAPES: Record<OpName, Schema> = {"sharing.ackRemovals": nul,"agentKeys.list": AgentKeysShape,+ "agentKeys.check": AgentKeysShape,"agentKeys.set": AgentKeysShape,"agentKeys.remove": AgentKeysShape,"agentKeys.shell": object({ names: list(str) }),@@ -1742,6 +1743,7 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"agents.allowComputer": nul,"agents.revokeComputer": nul,"agentKeys.list": AgentKeysWire,+ "agentKeys.check": AgentKeysWire,"agentKeys.set": AgentKeysWire,"agentKeys.remove": AgentKeysWire,"agentKeys.shell": object({ names: list(str) }),diff --git a/apps/cua-spaces-web/src/bridge/derive.ts b/apps/cua-spaces-web/src/bridge/derive.tsindex 0ef65f9cb8..40e61f8770 100644--- a/apps/cua-spaces-web/src/bridge/derive.ts+++ b/apps/cua-spaces-web/src/bridge/derive.ts@@ -362,6 +362,9 @@ export interface Machine {/** This machine only: signed in, but it cannot open the account's* machines (not enrolled): each machine's detail says why. */accessNotice?: MachineAccessNotice;+ /** This machine only: its id on the relay once it is set up for access+ * (`relay:<id>` is its desktop Space, which an agent on another machine names). */+ relayId?: string;}/** The words for a machine's Spaces, as the core says them@@ -562,6 +565,7 @@ export function toMachines(rows: MachineRow[], spaces: Space[], core?: CoreClien...(m.spacesLabel != null ? { spacesLabel: m.spacesLabel } : {}),...(m.device ? { device: true } : {}),...(m.current && m.accessNotice ? { accessNotice: m.accessNotice } : {}),+ ...(m.current && m.host?.machineId ? { relayId: m.host.machineId } : {}),};});}diff --git a/apps/cua-spaces-web/src/bridge/flags.ts b/apps/cua-spaces-web/src/bridge/flags.tsindex 228b21e936..a2b91d587e 100644--- a/apps/cua-spaces-web/src/bridge/flags.ts+++ b/apps/cua-spaces-web/src/bridge/flags.ts@@ -2,8 +2,8 @@// Copyright (c) 2026 Cua AI, Inc./**- * Feature flags for the web UI. A flag takes its default (off, except- * `spaces_redesign`, which is on) unless something sets it, in this order:+ * Feature flags for the web UI. A flag takes its default (off) unless+ * something sets it, in this order:** 1. this device's override (`localStorage` `cua.flag.<name>` = `1` or `0`),* which is how a dev build or a tester forces one;@@ -24,19 +24,26 @@ import { useSyncExternalStore } from "react";* Home page that asks what you want done, starts it on a fresh computer and* follows it as a conversation. Settings → Advanced → Labs turns it on for* this device.- * - `spaces_redesign`: the redesigned Spaces page, Space page (thread, stream- * switching), Agents tab (chat), Add a computer, sidebar and page- * language. On (the default), the redesign is drawn. Off, each of those- * routes draws the classic page (`src/legacy/`); the core, daemon, CLI,- * SDK, MCP, Settings and Connect a cloud are the same either way.- * Settings → Advanced → Labs → "New design" switches back to the classic- * design for this device.*/-export type FlagName = "upsell_cards" | "spaces_ask_first_home" | "spaces_redesign";+export type FlagName = "upsell_cards" | "spaces_ask_first_home";-const DEFAULTS: Record<FlagName, boolean> = { upsell_cards: false, spaces_ask_first_home: false, spaces_redesign: true };+const DEFAULTS: Record<FlagName, boolean> = { upsell_cards: false, spaces_ask_first_home: false };-const key = (name: FlagName) => `cua.flag.${name}`;+const key = (name: string) => `cua.flag.${name}`;++/** Flags that no longer exist: a leftover override of one is cleared on start (a stale "0" kept a build on a design that is gone). */+const RETIRED_FLAGS = ["spaces_redesign"] as const;++/** Clears the stored override of every retired flag. Runs once when this module loads. */+export function clearRetiredFlagOverrides(): void {+ try {+ for (const name of RETIRED_FLAGS) globalThis.localStorage?.removeItem(key(name));+ } catch {+ // No storage: nothing to clear.+ }+}++clearRetiredFlagOverrides();let remote: Partial<Record<FlagName, boolean>> = {};const listeners = new Set<() => void>();const notify = () => {diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex 62a468c3a0..ce26442129 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -61,6 +61,7 @@ export {agentKeyForm,agentKeysView,useAgentKeys,+ useKeysRecheck,type AgentKeyFormView,type AgentKeyRowView,type AgentKeysHook,@@ -158,7 +159,7 @@ export {export { linkEnds, needsRelaySetup, useLinks, type LinksHook } from "./links";export { chatKey, mergeChats, useAgentChats, useAgentDm, type AgentChat, type AgentChats, type AgentChatSpace, type AgentDm, type ChatAttempt, type ChatNeed, type ChatTone, type DmItem } from "./agents-dm";-export { foldThread, readSeqFrom, useSpaceThread, type SpaceThread, type SpaceThreadStatus, type ThreadAnswer, type ThreadItem } from "./thread";+export { foldThread, readSeqFrom, useSpaceThread, type SpaceThread, type SpaceThreadStatus, type ThreadAnswer, type ThreadItem, type ThreadQuote } from "./thread";export {DEFAULT_AGENT_RIGHTS,isMissingThreadTool,diff --git a/apps/cua-spaces-web/src/bridge/onboarding.ts b/apps/cua-spaces-web/src/bridge/onboarding.tsindex c41a9900cb..756ed403a9 100644--- a/apps/cua-spaces-web/src/bridge/onboarding.ts+++ b/apps/cua-spaces-web/src/bridge/onboarding.ts@@ -261,7 +261,7 @@ function fallbackTodos(s: OnboardingFlowState): OnboardingTodo[] {/** How the copy names the computer the app runs on (the core's `this_computer`). */function thisComputer(os: HostOs): string {- return os === "macos" ? "this Mac" : os === "windows" ? "this PC" : "this computer";+ return os === "macos" ? "this Mac" : os === "windows" ? "this PC" : "this machine";}function fallbackView(s: OnboardingFlowState, os: HostOs): OnboardingView {diff --git a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts b/apps/cua-spaces-web/src/bridge/ops/agent-keys.tsindex df512d0216..497789e7cc 100644--- a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts+++ b/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts@@ -63,6 +63,13 @@ declare module "../protocol" {interface HostOperations {/** The stored keys (no values) and whether this machine can keep them. */"agentKeys.list": { args: Record<string, never>; result: AgentKeysReport };+ /**+ * The list, after asking each provider whether the saved API keys still work (a cheap read-only+ * request, answers reused for a few minutes, never logged). A key the provider refuses comes back+ * `expired`: it needs a reconnect. A sign-in token has no check that is known to accept it, so it+ * is listed as it is.+ */+ "agentKeys.check": { args: Record<string, never>; result: AgentKeysReport };/** Adds or replaces a key; `env` names an `other` key. Answers the list after. */"agentKeys.set": { args: { provider: AgentKeyProvider; env?: string | null; value: string }; result: AgentKeysReport };/** Removes the key named `env`. Answers the list after. */@@ -74,7 +81,7 @@ declare module "../protocol" {}}-export const AGENT_KEYS_OPERATIONS = ["agentKeys.list", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell"] as const;+export const AGENT_KEYS_OPERATIONS = ["agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell"] as const;export type AgentKeysOp = (typeof AGENT_KEYS_OPERATIONS)[number];/** The SwiftUI host routes each under its own name. */@@ -83,6 +90,7 @@ export const AGENT_KEYS_WEBKIT_METHODS = AGENT_KEYS_OPERATIONS;/** The daemon method each operation calls. */export const AGENT_KEYS_METHODS = {"agentKeys.list": "agent_keys.list",+ "agentKeys.check": "agent_keys.check","agentKeys.set": "agent_keys.set","agentKeys.remove": "agent_keys.remove","agentKeys.shell": "agent_keys.shell",@@ -91,6 +99,7 @@ export const AGENT_KEYS_METHODS = {export const AGENT_KEYS_COVERAGE = {"agentKeys.list": { webkit: { methods: ["agentKeys.list"] }, tauri: ["agents_tool"] },+ "agentKeys.check": { webkit: { methods: ["agentKeys.check"] }, tauri: ["agents_tool"] },"agentKeys.set": { webkit: { methods: ["agentKeys.set"] }, tauri: ["agents_tool"] },"agentKeys.remove": { webkit: { methods: ["agentKeys.remove"] }, tauri: ["agents_tool"] },"agentKeys.shell": { webkit: { methods: ["agentKeys.shell"] }, tauri: ["agents_tool"] },@@ -100,6 +109,7 @@ export const AGENT_KEYS_COVERAGE = {/** Arguments that take each operation down its usual path (the coverage test). */export const AGENT_KEYS_ARGS: { [K in AgentKeysOp]: OpArgs<K> } = {"agentKeys.list": {},+ "agentKeys.check": {},"agentKeys.set": { provider: "anthropic", value: "sk-ant-test-0000" },"agentKeys.remove": { env: "ANTHROPIC_API_KEY" },"agentKeys.shell": {},@@ -161,6 +171,7 @@ export function tauriAgentKeysOps(invoke: Invoke): Handlers {agentKeysFromWire(await invoke<unknown>("agents_tool", { tool: AGENT_KEYS_METHODS[op], args }));return {"agentKeys.list": () => tool("agentKeys.list"),+ "agentKeys.check": () => tool("agentKeys.check"),"agentKeys.set": (args) => tool("agentKeys.set", setArgs(args)),"agentKeys.remove": ({ env }) => tool("agentKeys.remove", { env }),"agentKeys.shell": async () => shellNamesFromWire(await invoke<unknown>("agents_tool", { tool: AGENT_KEYS_METHODS["agentKeys.shell"], args: {} })),@@ -173,6 +184,7 @@ export function webkitAgentKeysOps(request: Request): Handlers {const call = async (op: AgentKeysOp, args: Record<string, unknown> = {}) => agentKeysFromWire(await request<unknown>(op, args));return {"agentKeys.list": () => call("agentKeys.list"),+ "agentKeys.check": () => call("agentKeys.check"),"agentKeys.set": (args) => call("agentKeys.set", setArgs(args)),"agentKeys.remove": ({ env }) => call("agentKeys.remove", { env }),"agentKeys.shell": async () => shellNamesFromWire(await request<unknown>("agentKeys.shell", {})),diff --git a/apps/cua-spaces-web/src/bridge/ops/thread.ts b/apps/cua-spaces-web/src/bridge/ops/thread.tsindex a1f5dadcf8..50861bc021 100644--- a/apps/cua-spaces-web/src/bridge/ops/thread.ts+++ b/apps/cua-spaces-web/src/bridge/ops/thread.ts@@ -179,6 +179,10 @@ export interface LiveAgent {agent: string;/** In a few plain words: `starting`, `installing`, `thinking`, `replying` or `using Bash`. */stage: string;+ /** When its oldest open task was given (Unix ms): the working row's clock. */+ sinceMs?: number;+ /** What it has said so far this turn, the whole text each time, while it streams; the reply replaces it. */+ text?: string;}/** Every agent with a turn on its way, and a key that changes when any stage does. */@@ -779,7 +783,9 @@ export function threadLiveFromTool(v: unknown): ThreadLive {const r = obj(a);const agent = str(r?.agent);const stage = str(r?.stage);- return agent && stage ? [{ agent, stage }] : [];+ const sinceMs = typeof r?.since_ms === "number" ? r.since_ms : undefined;+ const text = str(r?.text);+ return agent && stage ? [{ agent, stage, ...(sinceMs ? { sinceMs } : {}), ...(text ? { text } : {}) }] : [];});return { key: str(o.key), agents };}diff --git a/apps/cua-spaces-web/src/bridge/settings-derive.ts b/apps/cua-spaces-web/src/bridge/settings-derive.tsindex bcdb953fce..68de385760 100644--- a/apps/cua-spaces-web/src/bridge/settings-derive.ts+++ b/apps/cua-spaces-web/src/bridge/settings-derive.ts@@ -21,6 +21,7 @@ import type {EnrollAction,EnrollState,EnrollView,+ MachinesAccountView,} from "./contracts/devices";import type { SettingsInput, SettingsPage, SettingsRow, SettingsSection } from "./contracts/host";import type { NotificationInput, NotificationsPlan, NotificationsView } from "./contracts/notifications";@@ -71,6 +72,12 @@ export const devicesView = (core: CoreClient, input: DevicesInput, now: number):return core.tryCall<DevicesView>("devices.view", { input: rest, now }) ?? null;};+/** The account's part of the Machines page: machines waiting to be added, this machine's trust and who reached each machine. */+export const machinesAccount = (core: CoreClient, input: DevicesInput, now: number): MachinesAccountView | null => {+ const { readError, deviceName: __, ...rest } = input;+ return core.tryCall<MachinesAccountView>("machines.account", { input: rest, now, readError: readError ?? null }) ?? null;+};+export const enrollInitial = (core: CoreClient): EnrollState | null => core.tryCall<EnrollState>("devices.enrollInitial", {}) ?? null;export const enrollReduce = (core: CoreClient, state: EnrollState, action: EnrollAction): EnrollState =>core.tryCall<EnrollState>("devices.enrollReduce", { state, action }) ?? state;diff --git a/apps/cua-spaces-web/src/bridge/settings-feature.ts b/apps/cua-spaces-web/src/bridge/settings-feature.tsindex ff9fc47b5b..88481d6713 100644--- a/apps/cua-spaces-web/src/bridge/settings-feature.ts+++ b/apps/cua-spaces-web/src/bridge/settings-feature.ts@@ -21,6 +21,7 @@ import type {EnrollMethod,EnrollState,EnrollView,+ MachinesAccountView,} from "./contracts/devices";import type { SettingsPage, SettingsRow, SettingsSection } from "./contracts/host";import type { NotificationInput, NotificationsView, SystemNote } from "./contracts/notifications";@@ -46,6 +47,7 @@ import {chooseExperiment,cleanDeviceName,devicesView,+ machinesAccount,enrollInitial,enrollReduce,enrollView,@@ -100,10 +102,14 @@ export interface LoginItemData {export interface DevicesData {input: DevicesInput;view: DevicesView | null;+ /** The Machines page's account part: waiting machines, this machine's trust, recent access. */+ account: MachinesAccountView | null;/** The enroll sheet, while open. */enroll: { state: EnrollState; view: EnrollView | null } | null;/** The approval sheet, while open. */approve: { state: ApproveSheetState; view: ApproveSheetView | null } | null;+ /** Sign-ins whose "Not now" was chosen this session: they wait quietly. */+ dismissed: string[];/** A row action is running. */busy: boolean;/** The last row action's failure. */@@ -365,8 +371,10 @@ export class SettingsFeature {done({input: this.devices,view: devicesView(this.core, this.devices, now),+ account: machinesAccount(this.core, this.devices, now),enroll: this.enroll ? { state: this.enroll, view: enrollView(this.core, this.enroll) } : null,approve: this.approve ? { state: this.approve, view: approveView(this.core, this.approve, list) } : null,+ dismissed: [...this.dismissed],busy: this.devicesBusy,actionError: this.devicesError,now,@@ -593,6 +601,26 @@ export class SettingsFeature {this.publish("devices");}+ /**+ * "Add machine" on a machine waiting in the list: the machine is approved by its id (the+ * person is signed in and sees it by name and system), with no code to type. The host still asks+ * for presence first. A failure is thrown for the caller to show.+ */+ async addMachine(deviceId: string): Promise<void> {+ const prompt = this.currentDevicesView()?.approvals.find((p) => p.deviceId === deviceId);+ if (!prompt) return;+ // The by-id request is what the core makes of an approval that needs no code.+ this.approve = approveOpen(this.core, { ...prompt, expired: true });+ this.publish("devices");+ await this.approveDevice();+ const failed = this.approve ? approveView(this.core, this.approve, this.devicesList())?.error : null;+ if (failed) {+ this.approve = null;+ this.publish("devices");+ throw new Error(failed);+ }+ }+setApprovalCode(code: string): void {if (!this.approve) return;this.approve = approveReduce(this.core, this.approve, { type: "set-code", code }, this.devicesList());diff --git a/apps/cua-spaces-web/src/bridge/settings-hooks.ts b/apps/cua-spaces-web/src/bridge/settings-hooks.tsindex 445b02f6a4..f1e2ff0587 100644--- a/apps/cua-spaces-web/src/bridge/settings-hooks.ts+++ b/apps/cua-spaces-web/src/bridge/settings-hooks.ts@@ -117,6 +117,8 @@ export interface DevicesHook extends Hook<DevicesData> {/** The sheet's Deny or Not Now. */deny(): Promise<void>;closeApproval(): void;+ /** "Add machine" on a machine that waits: approves it by id (presence first); throws its failure. */+ addMachine(deviceId: string): Promise<void>;/** The row's Deny. */denyDevice(deviceId: string): Promise<void>;rename(id: string, name: string): Promise<void>;@@ -124,7 +126,7 @@ export interface DevicesHook extends Hook<DevicesData> {confirmMachine(id: string): Promise<void>;}-/** Settings, Devices: this device's enrollment, the account's devices, the access log and both sheets. */+/** Machines: this machine's trust, the machines waiting to be added, the access log and the trust sheet. */export function useDevices(): DevicesHook {const r = useFeature<DevicesData>("devices");const run = useRun();@@ -140,6 +142,7 @@ export function useDevices(): DevicesHook {approve: () => run((f) => f.approveDevice()),deny: () => run((f) => f.denyApproval()),closeApproval: () => now((f) => f.closeApproval()),+ addMachine: (id) => run((f) => f.addMachine(id)),denyDevice: (id) => run((f) => f.denyDevice(id)),rename: (id, name) => run((f) => f.renameDevice(id, name)),revoke: (id) => run((f) => f.revokeDevice(id)),diff --git a/apps/cua-spaces-web/src/bridge/store.ts b/apps/cua-spaces-web/src/bridge/store.tsindex baa5b7c749..d41e36df76 100644--- a/apps/cua-spaces-web/src/bridge/store.ts+++ b/apps/cua-spaces-web/src/bridge/store.ts@@ -670,7 +670,7 @@ export class BridgeStore {const space = (this.resources.spaces.data as Space[] | undefined)?.find((s) => s.id === row.id) ?? rowsToSpaces(this.core, [row], this.now())[0]!;// Plain words: a fresh computer inside this one (never "VM" or "container").const system = space.os === "macos" ? "macOS" : space.os === "windows" ? "Windows" : space.os === "linux" ? "Linux" : null;- const body = system ? `A fresh ${system} computer inside ${({ macos: "this Mac", windows: "this PC", linux: "this computer" } as const)[hostOs()]}. Your agent can use it now.` : undefined;+ const body = system ? `A fresh ${system} computer inside ${({ macos: "this Mac", windows: "this PC", linux: "this machine" } as const)[hostOs()]}. Your agent can use it now.` : undefined;this.extras.record({ kind: "message", title: `${spokenName(space.name)} is ready`, ...(body && !machine ? { body } : {}), space: space.id });return space;} catch (e) {diff --git a/apps/cua-spaces-web/src/bridge/thread.ts b/apps/cua-spaces-web/src/bridge/thread.tsindex ef45db0589..d38f387328 100644--- a/apps/cua-spaces-web/src/bridge/thread.ts+++ b/apps/cua-spaces-web/src/bridge/thread.ts@@ -7,13 +7,19 @@* thread with a cursor and long-polls for more (`thread.read` with* `followMs`), posts, answers approvals and lists the members.*- * Folding (nothing in the log is rewritten, DESIGN §3.2):+ * The thread reads like a chatroom (CUA-2640): one row per entry, in order,+ * each with its author and time. Nothing nests. Folding (nothing in the log+ * is rewritten, DESIGN §3.2):* - a message with `task` is a task; its state is the last `task_update`- * for it (`queued` until one arrives), and the replies to it nest under it;+ * for it (`queued` until one arrives), kept for the logic that needs it+ * (Retry, the unread divider) and shown nowhere on the message: the agent's+ * status and its reply tell how it is going;+ * - a reply is a message like any other, in sequence; `quote` names the+ * message it answers, which the page shows only when that message is not+ * right above it;* - an `approval` shows its Approve / Deny until an `answer` names it;- * - `system` entries, and task updates that carry a note, are one-line notes;- * a note about a task (`task_seq` on the note, or the update's task) shows- * inside that task, in order with its replies;+ * - `system` entries, and task updates that carry a note, are one-line muted+ * notes, in sequence;* - the unread divider sits before the first entry after the reader's* cursor as it was when the thread opened, that someone else wrote.*/@@ -43,17 +49,29 @@ export interface ThreadAnswer {note: string | null;}+/** The message a reply answers (the page quotes it when it is not right above). */+export interface ThreadQuote {+ seq: number;+ author: ThreadAuthor;+ text: string;+}+export type ThreadItem =- | { type: "message"; key: string; entry: ThreadEntry }+ | {+ type: "message";+ key: string;+ entry: ThreadEntry;+ /** The message it replies to, when it replies to one. */+ quote: ThreadQuote | null;+ /** What the task it answers asked, for Retry (a failed reply sends it again). */+ taskText: string | null;+ }| {type: "task";key: string;entry: ThreadEntry;state: TaskState;session: number | null;- replies: ThreadEntry[];- /** Notes about this task (a system note's `task`, an update's note), shown inside it in order with the replies. */- notes: { entry: ThreadEntry; text: string }[];}| { type: "approval"; key: string; entry: ThreadEntry; answer: ThreadAnswer | null }/** Someone's agent asks to join (CUA-2264): answered like an approval. */@@ -61,10 +79,11 @@ export type ThreadItem =| { type: "system"; key: string; entry: ThreadEntry; text: string }| { type: "unread"; key: string };-/** The thread's entries (in any order, duplicates allowed) as the page draws them. */+/** The thread's entries (in any order, duplicates allowed) as the page draws them: one row each, in sequence. */export function foldThread(entries: readonly ThreadEntry[], opts: { readSeq?: number | null; me?: string | null } = {}): ThreadItem[] {const sorted = dedupe(entries);const items: ThreadItem[] = [];+ const bySeq = new Map<number, ThreadEntry>(sorted.map((e) => [e.seq, e]));const tasks = new Map<number, Extract<ThreadItem, { type: "task" }>>();const approvals = new Map<number, Extract<ThreadItem, { type: "approval" | "join_request" }>>();for (const e of sorted) {@@ -75,10 +94,7 @@ export function foldThread(entries: readonly ThreadEntry[], opts: { readSeq?: nutask.state = u.state;task.session = u.session ?? task.session;}- if (u?.note) {- if (task) task.notes.push({ entry: e, text: u.note });- else items.push({ type: "system", key: `s${e.seq}`, entry: e, text: u.note });- }+ if (u?.note) items.push({ type: "system", key: `s${e.seq}`, entry: e, text: u.note });continue;}if (e.kind === "answer" && e.answer) {@@ -91,21 +107,9 @@ export function foldThread(entries: readonly ThreadEntry[], opts: { readSeq?: nucontinue;}if (e.kind === "system") {- const task = e.noteFor !== null ? tasks.get(e.noteFor) : undefined;- if (task) {- task.notes.push({ entry: e, text: e.text });- continue;- }items.push({ type: "system", key: `s${e.seq}`, entry: e, text: e.text });continue;}- if (e.replyTo !== null) {- const parent = tasks.get(e.replyTo);- if (parent) {- parent.replies.push(e);- continue;- }- }if (e.kind === "join_request" && e.joinRequest) {const item = { type: "join_request" as const, key: `j${e.seq}`, entry: e, answer: null };approvals.set(e.seq, item);@@ -118,13 +122,20 @@ export function foldThread(entries: readonly ThreadEntry[], opts: { readSeq?: nuitems.push(item);continue;}- if (e.task) {- const item = { type: "task" as const, key: `t${e.seq}`, entry: e, state: "queued" as TaskState, session: e.task.session, replies: [] as ThreadEntry[], notes: [] as { entry: ThreadEntry; text: string }[] };+ if (e.task && e.replyTo === null) {+ const item = { type: "task" as const, key: `t${e.seq}`, entry: e, state: "queued" as TaskState, session: e.task.session };tasks.set(e.seq, item);items.push(item);continue;}- items.push({ type: "message", key: `m${e.seq}`, entry: e });+ const parent = e.replyTo !== null ? bySeq.get(e.replyTo) : undefined;+ items.push({+ type: "message",+ key: `m${e.seq}`,+ entry: e,+ quote: parent ? { seq: parent.seq, author: parent.author, text: parent.text } : null,+ taskText: parent?.task ? parent.text : null,+ });}const readSeq = opts.readSeq;if (readSeq == null) return items;@@ -138,9 +149,7 @@ export function foldThread(entries: readonly ThreadEntry[], opts: { readSeq?: nu}function unreadIn(item: Exclude<ThreadItem, { type: "unread" }>, readSeq: number, me: string | null): boolean {- const fresh = (e: ThreadEntry) => e.seq > readSeq && e.author.id !== me;- if (fresh(item.entry)) return true;- return item.type === "task" && item.replies.some(fresh);+ return item.entry.seq > readSeq && item.entry.author.id !== me;}function dedupe(entries: readonly ThreadEntry[]): ThreadEntry[] {@@ -191,6 +200,16 @@ export interface SpaceThread {removeAgent: ((name: string) => Promise<void>) | null;}+/**+ * Streaming text arrives as whole-text snapshots; they are drawn at most this often (ms), the latest+ * one winning, so a fast stream does not re-render the thread for every snapshot. A stage change, an+ * agent arriving or leaving shows at once.+ */+export const LIVE_COALESCE_MS = 50;++/** The live rows without their streaming text: what makes a change worth drawing at once. */+const liveShape = (agents: readonly LiveAgent[]) => agents.map((a) => `${a.agent}=${a.stage}`).join(";");+const FIRST_PAGE = 100;const MEMBERS_POLL_MS = 5_000;const MAX_BACKOFF_MS = 30_000;@@ -213,8 +232,34 @@ export function useSpaceThread(spaceId: string | null): SpaceThread {const [error, setError] = useState<string | null>(null);const [members, setMembers] = useState<AgentMember[]>([]);const [shares, setShares] = useState<ShareEntry[]>([]);- const [live, setLive] = useState<LiveAgent[]>([]);+ const [live, setLiveNow] = useState<LiveAgent[]>([]);const [hasMoreBefore, setHasMoreBefore] = useState(false);+ // The snapshot waiting for its turn, and when it is drawn.+ const livePending = useRef<LiveAgent[] | null>(null);+ const liveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const liveShown = useRef<LiveAgent[]>([]);+ const setLive = useCallback((agents: LiveAgent[]) => {+ if (liveTimer.current) {+ clearTimeout(liveTimer.current);+ liveTimer.current = null;+ }+ livePending.current = null;+ liveShown.current = agents;+ setLiveNow(agents);+ }, []);+ /** A snapshot of the live rows: drawn now when a stage changed, else within LIVE_COALESCE_MS (the latest wins). */+ const pushLive = useCallback(+ (agents: LiveAgent[]) => {+ if (liveShape(agents) !== liveShape(liveShown.current)) return setLive(agents);+ livePending.current = agents;+ if (liveTimer.current) return;+ liveTimer.current = setTimeout(() => {+ liveTimer.current = null;+ if (livePending.current) setLive(livePending.current);+ }, LIVE_COALESCE_MS);+ },+ [setLive],+ );const loadingEarlier = useRef(false);const merge = useCallback((more: readonly ThreadEntry[]) => {if (!more.length) return;@@ -239,6 +284,8 @@ export function useSpaceThread(spaceId: string | null): SpaceThread {let cursor = 0;// The stage key last seen: the follow also returns when it changes.let liveKey = "";+ // The same without what is said: what moves the members list.+ let liveShapeSeen = "";const markRead = () => {if (!alive || !visible() || cursor <= 0) return;// Re-reads the last entry with mark_read: the daemon moves the@@ -281,14 +328,18 @@ export function useSpaceThread(spaceId: string | null): SpaceThread {setError(null);backoff = 1_000;cursor = Math.max(cursor, page.cursor);- const stageMoved = page.live.key !== liveKey;+ // The daemon's key moves with the stages and with what is said; the members only change with a stage.+ const keyMoved = page.live.key !== liveKey;+ const shape = liveShape(page.live.agents);+ const stageMoved = shape !== liveShapeSeen;+ liveShapeSeen = shape;liveKey = page.live.key;// The stages ride the follow (not the members poll), so a row shows as it changes.- setLive(page.live.agents);+ pushLive(page.live.agents);merge(page.entries);if (page.entries.some((e) => e.kind !== "message") || stageMoved) membersDue.current();// A daemon that answers a follow at once (no long poll) is read every 2 s.- if (!page.entries.length && !stageMoved) await sleep(2_000);+ if (!page.entries.length && !keyMoved) await sleep(2_000);} catch (e) {if (!alive) return;if (isMissingThreadTool(e)) {@@ -304,8 +355,10 @@ export function useSpaceThread(spaceId: string | null): SpaceThread {return () => {alive = false;document.removeEventListener("visibilitychange", onVisible);+ if (liveTimer.current) clearTimeout(liveTimer.current);+ liveTimer.current = null;};- }, [data, spaceId, merge]);+ }, [data, spaceId, merge, setLive, pushLive]);// Members (`agent_members`) every few seconds, and who the Space is shared with once.useEffect(() => {diff --git a/apps/cua-spaces-web/src/components/__tests__/add-computer-sheet.test.tsx b/apps/cua-spaces-web/src/components/__tests__/add-computer-sheet.test.tsxindex e1bf8e2a1e..e4e986fdd6 100644--- a/apps/cua-spaces-web/src/components/__tests__/add-computer-sheet.test.tsx+++ b/apps/cua-spaces-web/src/components/__tests__/add-computer-sheet.test.tsx@@ -68,7 +68,7 @@ const status = () => document.querySelector("[data-add-status]")?.textContent ??const prompt = () => document.querySelector<HTMLTextAreaElement>("#add-agent-prompt")!;const back = () => fireEvent.click(document.querySelector("[data-add-back]")!);-describe("Add a computer: the methods", () => {+describe("Add a machine: the methods", () => {it("lists one row per method, Sign in there first, and a prompt for an agent with the live code", async () => {const { adapter, calls } = host({}, neverUsed);await mount(adapter);@@ -174,7 +174,7 @@ describe("Add a computer: the methods", () => {});});-describe("Add a computer: states", () => {+describe("Add a machine: states", () => {it("waits, then says which machine was added, however it was added", async () => {const { adapter, calls } = host();await mount(adapter);@@ -267,7 +267,7 @@ describe("Add a computer: states", () => {});});-describe("Add a computer: without a code", () => {+describe("Add a machine: without a code", () => {it("signed out: only Sign in there, and a way to sign in", async () => {const { adapter, calls } = host({ signedIn: false });await mount(adapter);@@ -322,7 +322,7 @@ describe("Add a computer: without a code", () => {});});-describe("Add a computer: for a team", () => {+describe("Add a machine: for a team", () => {const acme = "0f1e2d3c-0000-4000-8000-0000000000a1";const teams = (currentTeamId: string | null) => () =>Promise.resolve({diff --git a/apps/cua-spaces-web/src/components/__tests__/this-machine.test.tsx b/apps/cua-spaces-web/src/components/__tests__/this-machine.test.tsxindex 7f638f0ead..e599ddcec6 100644--- a/apps/cua-spaces-web/src/components/__tests__/this-machine.test.tsx+++ b/apps/cua-spaces-web/src/components/__tests__/this-machine.test.tsx@@ -17,7 +17,7 @@ const rows = (n: number, what: string): HostAccessRow[] => Array.from({ length:/** The core's "This machine" page for a machine sharing over the relay, with long logs. */const sharing: HostPanelView = {- title: "This computer",+ title: "This machine",summary: "Sharing · Relay",configured: true,facts: [{ label: "Name", value: "Studio" }],diff --git a/apps/cua-spaces-web/src/components/agents/agent-chat.tsx b/apps/cua-spaces-web/src/components/agents/agent-chat.tsxindex 4f8da26e94..e7bfa5dc96 100644--- a/apps/cua-spaces-web/src/components/agents/agent-chat.tsx+++ b/apps/cua-spaces-web/src/components/agents/agent-chat.tsx@@ -318,8 +318,8 @@ export function AgentDmView({ chat, space, onSpace, identity, onInfo, me }: { ch) : (<>{asleepHere ? <p className="my-1 text-center text-xs text-muted-foreground">{chat.label} is asleep here. A message wakes it.</p> : null}- {dm.items.map((d) => (- <DmRow key={`${d.spaceId}${d.item.key}`} d={d} roster={rosters[d.spaceId]!} spaces={chat.spaces} multi={multi && !space} onAnswer={(seq, ok) => dm.answer(d.spaceId, seq, ok)} onOpenAttachment={openAttachment} onRetry={(text) => dm.send(d.spaceId, text)} />+ {dm.items.map((d, i) => (+ <DmRow key={`${d.spaceId}${d.item.key}`} d={d} above={dmAbove(dm.items, i)} roster={rosters[d.spaceId]!} spaces={chat.spaces} multi={multi && !space} onAnswer={(seq, ok) => dm.answer(d.spaceId, seq, ok)} onOpenAttachment={openAttachment} onRetry={(text) => dm.send(d.spaceId, text)} />))}</>)}@@ -345,11 +345,23 @@ export function AgentDmView({ chat, space, onSpace, identity, onInfo, me }: { ch);}-function DmRow({ d, roster, spaces, multi, onAnswer, onOpenAttachment, onRetry }: { d: DmItem; roster: Roster; spaces: AgentChatSpace[]; multi: boolean; onAnswer: (seq: number, ok: boolean) => Promise<void>; onOpenAttachment: (a: ThreadAttachment) => void; onRetry: (text: string) => Promise<void> }) {+/** The seq of the entry above `items[i]` in the same Space (a reply quotes only what is not right above it). */+function dmAbove(items: readonly DmItem[], i: number): number | null {+ const mine = items[i]!;+ for (let j = i - 1; j >= 0; j--) {+ const it = items[j]!;+ if (it.spaceId !== mine.spaceId) continue;+ if (it.item.type === "system" || it.item.type === "unread") continue;+ return it.item.entry.seq;+ }+ return null;+}++function DmRow({ d, above, roster, spaces, multi, onAnswer, onOpenAttachment, onRetry }: { d: DmItem; above: number | null; roster: Roster; spaces: AgentChatSpace[]; multi: boolean; onAnswer: (seq: number, ok: boolean) => Promise<void>; onOpenAttachment: (a: ThreadAttachment) => void; onRetry: (text: string) => Promise<void> }) {const s = spaces.find((x) => x.spaceId === d.spaceId);// Every message says its Space when the DM shows several.const label = multi && s ? <SpaceLabel name={s.spaceName} os={s.os} /> : undefined;- return <ThreadItemView item={d.item} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRetry={onRetry} label={label} />;+ return <ThreadItemView item={d.item} above={above} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRetry={onRetry} label={label} />;}function SpaceLabel({ name, os }: { name: string; os: AgentChatSpace["os"] }) {diff --git a/apps/cua-spaces-web/src/components/agents/connect-dialog.tsx b/apps/cua-spaces-web/src/components/agents/connect-dialog.tsxindex fd71ae8a63..cd614034f4 100644--- a/apps/cua-spaces-web/src/components/agents/connect-dialog.tsx+++ b/apps/cua-spaces-web/src/components/agents/connect-dialog.tsx@@ -11,12 +11,17 @@ import { Segmented } from "@/components/ui/segmented";import { toast } from "@/components/ui/toast";import { cn } from "@/lib/utils";+import { OtherMachineBlock, useThisAndOthers } from "./other-machine-block";+/*** What the cua MCP server is and how an agent gets it: the agents on this* machine (`agents.setup`, the SDK's agent setup), one button that sets up* every installed one (`agents.configure`, the same as `cua agents setup`),- * and, under a closed "Advanced", the config entry for doing it by hand. Rows- * show the agent and its state only; file paths stay in Advanced.+ * which machine that was and the others it did not touch, "On another+ * machine" (the host to name, the exact commands, the permissions and the+ * reload note for an agent that runs somewhere else), and, under a closed+ * "Advanced", the config entry for doing it by hand. Rows show the agent and+ * its state only; file paths stay in Advanced.*/type Manual = "claude-code" | "codex" | "hermes" | "openclaw";@@ -48,6 +53,9 @@ const MANUAL_OPTIONS = (Object.keys(MANUAL) as Manual[]).map((value) => ({ valueexport function ConnectAgentDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {const { agentSetup, configureAgents } = useAgents();+ // Which machine this edits, and the others: Connect never reaches them.+ const { here, hereName, others } = useThisAndOthers();+ const [doneOn, setDoneOn] = useState<string | null>(null);const [rows, setRows] = useState<AgentSetupRow[] | null>(null);const [detectError, setDetectError] = useState<string | null>(null);const [busy, setBusy] = useState(false);@@ -57,6 +65,7 @@ export function ConnectAgentDialog({ open, onOpenChange }: { open: boolean; onOpif (!open) return;let live = true;setDetectError(null);+ setDoneOn(null);agentSetup().then((r) => live && setRows(r),(e: unknown) => {@@ -78,7 +87,8 @@ export function ConnectAgentDialog({ open, onOpenChange }: { open: boolean; onOpconfigureAgents().then((r) => {setRows(r);- toast("Agents set up", { description: "Restart an agent that is already open so it loads the server." });+ setDoneOn(hereName);+ toast(`Agents set up on ${hereName}`, { description: "Restart an agent that is already open so it loads the server." });}).catch((e: unknown) => toast("Couldn't set up agents", { description: e instanceof Error ? e.message : String(e) })).finally(() => setBusy(false));@@ -96,7 +106,10 @@ export function ConnectAgentDialog({ open, onOpenChange }: { open: boolean; onOp<section className="mt-5"><div className="mb-2 flex items-center justify-between gap-3">- <h3 className="text-xs font-semibold">On this computer</h3>+ <h3 className="text-xs font-semibold" data-connect-here="">+ On {hereName}+ {here ? <span className="ml-1.5 font-normal text-muted-foreground">this machine</span> : null}+ </h3>{rows && rows.length > 0 ? (<Button size="sm" variant={pending.length ? "default" : "outline"} disabled={busy || pending.length === 0} onClick={setUpAll}>{busy ? "Setting up…" : pending.length ? `Set up ${pending.length === 1 ? "1 agent" : `${pending.length} agents`}` : "All set up"}@@ -118,12 +131,29 @@ export function ConnectAgentDialog({ open, onOpenChange }: { open: boolean; onOp</ul>)}</div>+ {doneOn ? (+ <p className="mt-2 text-xs" data-connect-done="">+ Set up on {doneOn}.{" "}+ {others.length > 0 ? (+ <span className="text-muted-foreground" data-connect-others="">+ Not touched: {others.join(", ")}. An agent on {others.length === 1 ? "that machine" : "one of those machines"} needs its own setup (see On another machine below).+ </span>+ ) : null}+ </p>+ ) : null}<p className="mt-2 text-xs text-muted-foreground">Setting up edits each agent's own config and keeps everything else in it. <code className="font-mono">cua agents setup</code> in a terminal does thesame, and <code className="font-mono">cua agents remove</code> undoes it.</p></section>+ <section className="mt-6">+ <h3 className="mb-1 text-xs font-semibold">On another machine</h3>+ <div className="-mx-4">+ <OtherMachineBlock />+ </div>+ </section>+<details className="group mt-6" data-connect-advanced=""><summary className="flex cursor-default list-none items-center gap-1 text-[13px] text-muted-foreground outline-none hover:text-foreground focus-visible:text-foreground [&::-webkit-details-marker]:hidden"><ChevronRightIcon className="size-3.5 transition-transform group-open:rotate-90" aria-hidden /> Advanceddiff --git a/apps/cua-spaces-web/src/components/agents/other-machine-block.tsx b/apps/cua-spaces-web/src/components/agents/other-machine-block.tsxnew file mode 100644index 0000000000..6b71fc771f--- /dev/null+++ b/apps/cua-spaces-web/src/components/agents/other-machine-block.tsx@@ -0,0 +1,81 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { CheckIcon, CopyIcon } from "lucide-react";+import { useState } from "react";++import { useMachines, type Machine } from "@/bridge";+import { Button } from "@/components/ui/button";+import { Segmented } from "@/components/ui/segmented";+import { otherMachineCommand, otherMachinePrompt, OTHER_MACHINE_PERMISSIONS, OTHER_MACHINE_RELOAD } from "@/lib/other-machine";++type Agent = "claude-code" | "codex" | "hermes" | "openclaw";+const AGENTS: { value: Agent; label: string }[] = [+ { value: "claude-code", label: "Claude Code" },+ { value: "codex", label: "Codex" },+ { value: "hermes", label: "Hermes" },+ { value: "openclaw", label: "OpenClaw" },+];++/** This machine, and the other machines of the account: what Connect names and what it did not touch. */+export function useThisAndOthers(): { here: Machine | undefined; hereName: string; others: string[] } {+ const { data: machines } = useMachines();+ const here = machines?.find((m) => m.current);+ return { here, hereName: here?.name ?? "this machine", others: (machines ?? []).filter((m) => !m.current && !m.device).map((m) => m.name) };+}++/**+ * An agent that runs on another machine uses this one: the host to name, the exact commands to run on+ * that machine, what this machine has to allow, and the reload note (CUA-2644).+ */+export function OtherMachineBlock() {+ const { here, hereName } = useThisAndOthers();+ const [agent, setAgent] = useState<Agent>("hermes");+ return (+ <div data-connect-other-machine="" className="px-4 py-3.5">+ <p className="text-xs text-muted-foreground">+ An agent that runs on a different machine can use {hereName} too. Host to name: <span className="font-medium text-foreground select-text">{hereName}</span>+ {here?.relayId ? (+ <>+ , its Space <code className="font-mono select-text">relay:{here.relayId}</code>+ </>+ ) : (+ <>. Set this machine up for access first (its page in Machines) so the agent can find it</>+ )}+ .+ </p>+ <p className="mt-3 mb-2 text-xs font-semibold">Run this on the other machine</p>+ <Segmented aria-label="Agent on the other machine" value={agent} options={AGENTS} onValueChange={setAgent} />+ <Snippet file="Terminal on the other machine" text={otherMachineCommand(agent)} />+ <p className="mt-3 mb-2 text-xs font-semibold">Then tell the agent</p>+ <Snippet file="Message to the agent" text={otherMachinePrompt(hereName, here?.relayId)} />+ <p className="mt-2 text-xs text-muted-foreground" data-connect-other-permissions="">+ {OTHER_MACHINE_PERMISSIONS}+ </p>+ <p className="mt-1 text-xs text-muted-foreground" data-connect-other-reload="">+ {OTHER_MACHINE_RELOAD}+ </p>+ </div>+ );+}++function Snippet({ file, text }: { file: string; text: string }) {+ const [copied, setCopied] = useState(false);+ const copy = () => {+ void navigator.clipboard?.writeText(text).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1200);+ });+ };+ return (+ <div className="mt-2.5 overflow-hidden rounded-lg border bg-muted/40">+ <div className="flex h-8 items-center justify-between border-b pr-1 pl-3">+ <span className="text-2xs text-muted-foreground">{file}</span>+ <Button size="icon-sm" variant="ghost" aria-label="Copy" onClick={copy}>+ {copied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}+ </Button>+ </div>+ <pre className="overflow-x-auto px-3 py-2.5 font-mono text-xs leading-[1.55] select-text">{text}</pre>+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx b/apps/cua-spaces-web/src/components/ask-first/ask-box.tsxindex 1f14bb03b0..a0227ecbab 100644--- a/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx@@ -5,7 +5,7 @@ import { Menu as MenuPrimitive } from "@base-ui/react/menu";import { ArrowUpIcon, CheckIcon, ChevronDownIcon, LaptopIcon, MonitorIcon } from "lucide-react";import { useEffect, useRef, type ReactElement, type ReactNode } from "react";-import { firstMessage, useBridge, useFlag, type Space, type SpaceOs } from "@/bridge";+import { firstMessage, useBridge, type Space, type SpaceOs } from "@/bridge";import { AppMarkImage } from "@/components/agents/harness-mark";import { OsIcon } from "@/components/os-icon";import type { NewKind, TaskWhere } from "@/lib/ask-first";@@ -27,16 +27,12 @@ export const agentName = (id: string) => TASK_AGENTS.find((a) => a.id === id)?.nconst OS_WORD: Record<SpaceOs, string> = { linux: "Linux", macos: "Mac", windows: "Windows", unknown: "" };-/** With the redesign, where it runs is a Space: "New Space", then quieter "Linux on This Mac". */+/** Where it runs is a Space: "New Space", then quieter "Linux on This Mac". */export function whereSpaceLabel(where: TaskWhere): { title: string; detail: string | null } {if (where.kind === "new") return { title: "New Space", detail: `${OS_WORD[where.os]} on This Mac` };return { title: where.kind === "this-mac" ? "This Mac" : where.space.name, detail: null };}-export function whereLabel(where: TaskWhere): string {- return where.kind === "new" ? `A new ${OS_WORD[where.os]} computer · this Mac` : where.kind === "this-mac" ? "This Mac" : where.space.name;-}-export function AppMark({ agent, size = 32 }: { agent: string; size?: number }) {return (<span className="flex shrink-0 items-center justify-center rounded-lg border bg-card dark:bg-background" style={{ width: size, height: size }}>@@ -145,10 +141,9 @@ export function AskBox({if (autoFocus) ref.current?.focus();}, [autoFocus]);const ready = text.trim().length > 0 && !busy;- // With the redesign the agent reads as the @mention the thread will show, and where as a Space.- const redesign = useFlag("spaces_redesign");+ // The agent reads as the @mention the thread will show, and where as a Space.const { core } = useBridge();- const handle = redesign ? (firstMessage(core, { members: [], people: [], canAdd: true, connectors: { apps: [], keys: { keys: [] }, shellKeys: [], auto: false, off: [], busy: [], failures: [] } }, agent, "")?.handle ?? null) : null;+ const handle = firstMessage(core, { members: [], people: [], canAdd: true, connectors: { apps: [], keys: { keys: [] }, shellKeys: [], auto: false, off: [], busy: [], failures: [] } }, agent, "")?.handle ?? null;const agentNote = (id: string) => (id === mostUsed ? "You use it most" : installed.has(id) ? "On this Mac" : "Runs on the new computer with your saved key");return (<div data-ask-box="" className="rounded-2xl border bg-card shadow-xs dark:bg-white/[0.03]">@@ -189,7 +184,7 @@ export function AskBox({<PickerRow key={a.id} icon={<AppMark agent={a.id} size={28} />} title={a.name} note={agentNote(a.id)} selected={a.id === agent} onSelect={() => onAgent(a.id)} />))}</Picker>- <span className="px-1 text-[14px] text-muted-foreground">{redesign ? "in" : "on"}</span>+ <span className="px-1 text-[14px] text-muted-foreground">in</span><WherePickerwhere={where}onWhere={onWhere}@@ -206,14 +201,10 @@ export function AskBox({) : (<MonitorIcon className="size-4 text-muted-foreground" />)}- {redesign ? (- <span className="max-w-80 truncate" data-ask-where="">- {whereSpaceLabel(where).title}- {whereSpaceLabel(where).detail ? <span className="ml-1.5 text-muted-foreground">{whereSpaceLabel(where).detail}</span> : null}- </span>- ) : (- <span className="max-w-72 truncate">{whereLabel(where)}</span>- )}+ <span className="max-w-80 truncate" data-ask-where="">+ {whereSpaceLabel(where).title}+ {whereSpaceLabel(where).detail ? <span className="ml-1.5 text-muted-foreground">{whereSpaceLabel(where).detail}</span> : null}+ </span><ChevronDownIcon className="size-4 text-muted-foreground" /></button>}diff --git a/apps/cua-spaces-web/src/components/ask-first/home-sections.tsx b/apps/cua-spaces-web/src/components/ask-first/home-sections.tsxindex 690933b200..351301a492 100644--- a/apps/cua-spaces-web/src/components/ask-first/home-sections.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/home-sections.tsx@@ -2,7 +2,7 @@// Copyright (c) 2026 Cua AI, Inc./**- * Home's sections with the redesign: "Your agents" (the Agents page's own+ * Home's sections: "Your agents" (the Agents page's own* list, `agentList.view`: agents in your Spaces and this device's runs that* haven't started, with Connect or Try again) and "Your Spaces" (the Spaces* page's tiles). One row each, and See all.diff --git a/apps/cua-spaces-web/src/components/ask-first/home.tsx b/apps/cua-spaces-web/src/components/ask-first/home.tsxindex 936da41093..eaa94c59f2 100644--- a/apps/cua-spaces-web/src/components/ask-first/home.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/home.tsx@@ -1,22 +1,17 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { Link } from "@tanstack/react-router";-import { ChevronRightIcon } from "lucide-react";import { useEffect, useState } from "react";-import { useAgentChats, useAgents, useFlag, useSpaces, useSpaceThumbnail, type AgentRunSummary, type Space } from "@/bridge";+import { useAgentChats, useAgents, useSpaces, type AgentRunSummary } from "@/bridge";import { CuaKey } from "@/components/cua-key";import { useAgentAttempts } from "@/hooks/use-agent-attempts";import { OsIcon } from "@/components/os-icon";-import { SpaceCanvas } from "@/components/space-canvas";-import { Button } from "@/components/ui/button";-import { currentWhere, mostUsedAgent, orderTasks, startErrorView, SUGGESTIONS, taskState, TASK_STATE_TEXT, taskTitle, useAskTasks, type AskTask, type TaskState } from "@/lib/ask-first";+import { currentWhere, mostUsedAgent, SUGGESTIONS, useAskTasks, type AskTask, type TaskState } from "@/lib/ask-first";import { useListedSpaces } from "@/components/spaces/listed";-import { orderSpaces, realSpaces, spaceState } from "@/lib/spaces";import { cn } from "@/lib/utils";-import { agentName, AppMark, AskBox, TASK_AGENTS, type TaskWhere } from "./ask-box";+import { agentName, AskBox, TASK_AGENTS, type TaskWhere } from "./ask-box";import { YourAgents, YourSpaces as YourSpacesRow } from "./home-sections";import { useWherePick } from "./this-mac-confirm";import { useStartTask } from "./use-start-task";@@ -46,7 +41,7 @@ export function AskFirstHome() {const tasks = useAskTasks();const { data: spaces } = useSpaces();const listed = useListedSpaces(spaces);- const { data: agents, agentSetup } = useAgents();+ const { agentSetup } = useAgents();const { kinds, spaces: pickable } = useWhereOptions();const { start } = useStartTask();const [installed, setInstalled] = useState<ReadonlySet<string>>(new Set());@@ -79,18 +74,11 @@ export function AskFirstHome() {setText("");};- const rows = orderTasks(- tasks.map((task) => {- const run = taskRun(agents?.runs, task);- return { task, run, state: taskState(task, run ? { status: run.status, needsYou: Boolean(run.needsYou), lastEventMs: null } : null) };- }),- );- const redesign = useFlag("spaces_redesign");- // The redesign lists agents and Spaces, not tasks: with neither (a first run,+ // Home lists agents and Spaces, not tasks: with neither (a first run,// or tasks whose Spaces are gone), Home is the welcome again.const attempts = useAgentAttempts();const { chats } = useAgentChats(attempts);- const first = redesign ? !chats?.length && listed.counted.length === 0 : tasks.length === 0;+ const first = !chats?.length && listed.counted.length === 0;return (<div className="h-full overflow-y-auto [scrollbar-gutter:stable]" data-ask-first-home="">@@ -137,119 +125,12 @@ export function AskFirstHome() {<CuaKey size={24} />A fresh computer does the work, so yours stays untouched. Watch it live, step in any time, and throw it away when you're done.</p></>- ) : redesign ? null : (- <TaskList rows={rows} spaces={spaces ?? []} />- )}- {redesign ? (- // The redesign: the Agents page's own list, then the Spaces page's tiles.- <>- <YourAgents chats={chats} />- <YourSpacesRow />- </>- ) : !first && realSpaces(spaces ?? []).length > 0 ? (- <YourSpaces spaces={orderSpaces(realSpaces(spaces ?? []))} />) : null}+ {/* The Agents page's own list, then the Spaces page's tiles. */}+ <YourAgents chats={chats} />+ <YourSpacesRow /></div>{pick.dialog}</div>);}--function TaskList({ rows, spaces }: { rows: { task: AskTask; run: AgentRunSummary | undefined; state: TaskState }[]; spaces: Space[] }) {- const live = rows.filter((r) => r.state === "working" || r.state === "starting").length;- return (- <section>- <h2 className="mb-3 flex items-baseline gap-2 text-[17px] font-semibold">- Tasks {live ? <span className="text-[14px] font-normal text-muted-foreground">{live} running</span> : null}- </h2>- <div className="divide-y overflow-hidden rounded-xl border bg-card shadow-xs">- {rows.map((r) => (- <TaskRow key={r.task.id} {...r} space={spaces.find((s) => s.id === r.task.spaceId)} />- ))}- </div>- </section>- );-}--function ago(ms: number, now = Date.now()): string {- const m = Math.round((now - ms) / 60_000);- if (m < 2) return "Now";- if (m < 60) return `${m} min ago`;- const h = Math.round(m / 60);- if (h < 24) return `${h} h ago`;- return h < 48 ? "Yesterday" : `${Math.round(h / 24)} days ago`;-}--function TaskRow({ task, run, state, space }: { task: AskTask; run: AgentRunSummary | undefined; state: TaskState; space: Space | undefined }) {- const thumb = useSpaceThumbnail(task.spaceId ?? "", Boolean(space) && task.ending !== "thrown");- const line =- state === "needs-you" && run?.needsYou- ? run.needsYou.title- : state === "didnt-start" && task.error- ? `Didn't start: ${startErrorView(task.error, agentName(task.agent)).title}`- : TASK_STATE_TEXT[state];- const where = task.ending === "thrown" ? "Thrown away" : task.onHost ? "This Mac" : (space?.name ?? "");- return (- <Link- to="/home/$taskId"- params={{ taskId: task.id }}- data-task-row={task.id}- className="flex min-h-[72px] items-center gap-4 px-5 py-3 hover:bg-accent/60"- >- <AppMark agent={task.agent} size={36} />- <div className="min-w-0 flex-1">- <div className="truncate text-[14px] font-medium">{taskTitle(task.prompt)}</div>- <div className="flex items-center gap-2 text-[13px] text-muted-foreground">- <StateDot state={state} />- <span className="truncate">{line}</span>- </div>- </div>- <span className="hidden w-40 truncate text-right text-[13px] text-muted-foreground md:block">{where}</span>- <span className="w-24 text-right text-[13px] text-muted-foreground">{ago(task.createdMs)}</span>- <span className="hidden w-24 lg:block">- {thumb ? <img src={thumb} alt="" className="aspect-[16/10] w-24 rounded-md border object-cover" /> : null}- </span>- {state === "needs-you" ? (- <Button variant="secondary" className="h-10 px-4" render={<span />}>- Answer- </Button>- ) : null}- </Link>- );-}--function YourSpaces({ spaces }: { spaces: Space[] }) {- const on = spaces.filter((s) => spaceState(s) === "running").length;- return (- <section>- <div className="mb-3 flex items-center justify-between">- <h2 className="flex items-baseline gap-2 text-[17px] font-semibold">- Your Spaces <span className="text-[14px] font-normal text-muted-foreground">{on} on</span>- </h2>- <Link to="/spaces" className="flex items-center gap-1 text-[13px] text-muted-foreground hover:text-foreground">- See all {spaces.length} <ChevronRightIcon className="size-4" />- </Link>- </div>- <div className="grid grid-cols-2 gap-4 md:grid-cols-4">- {spaces.slice(0, 4).map((s) => (- <SpaceCard key={s.id} space={s} />- ))}- </div>- </section>- );-}--function SpaceCard({ space }: { space: Space }) {- const thumb = useSpaceThumbnail(space.id, spaceState(space) === "running");- return (- <Link to="/spaces/$spaceId" params={{ spaceId: space.id }} className="overflow-hidden rounded-xl border bg-card shadow-xs hover:bg-accent/60">- <SpaceCanvas className="rounded-none">- {thumb ? <img src={thumb} alt="" className="absolute inset-0 size-full object-cover" /> : <OsIcon os={space.os} className="size-6 text-muted-foreground" />}- </SpaceCanvas>- <div className="px-4 py-3">- <div className="truncate text-[14px] font-medium">{space.name}</div>- <div className="text-[12px] text-muted-foreground">{spaceState(space) === "running" ? "On" : "Off"}</div>- </div>- </Link>- );-}diff --git a/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts b/apps/cua-spaces-web/src/components/ask-first/use-start-task.tsindex 79583b9647..1e35ffdf63 100644--- a/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts+++ b/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts@@ -3,7 +3,7 @@import { useNavigate, useRouter } from "@tanstack/react-router";-import { firstMessage, newPendingId, threadOpAvailable, useAgents, useBridge, useFeatureRecorder, useFirstSpaceOffers, useFlag, useSpaces, type AgentMember, type HostStatus } from "@/bridge";+import { firstMessage, newPendingId, threadOpAvailable, useAgents, useBridge, useFeatureRecorder, useFirstSpaceOffers, useSpaces, type AgentMember, type HostStatus } from "@/bridge";import { enqueue, flushQueue, resolveQueue } from "@/components/space-thread/queued";import { sendWithSummon } from "@/components/space-thread/summon";import { useConnectors } from "@/hooks/use-connectors";@@ -32,9 +32,8 @@ export function useStartTask(): {const { offers } = useFirstSpaceOffers();const record = useFeatureRecorder();const { core } = useBridge();- // With the redesign, the job goes straight to its Space: the page is the Space's, and+ // The job goes straight to its Space: the page is the Space's, and// the job is its first message, @mentioning the agent (the same summon as the composer's).- const inSpace = useFlag("spaces_redesign");const { input: connectors } = useConnectors();/** What summoning reads for `spaceId`: its agents now and this device's connectors. */@@ -109,11 +108,6 @@ export function useStartTask(): {const target = taskTarget(where);const task = addAskTask({ prompt: prompt.trim(), agent, os: whereOs(where), spaceId: target.kind === "space" ? target.spaceId : null, onHost: target.kind === "host" });record("ask_first_task_started");- if (!inSpace) {- void navigate({ to: "/home/$taskId", params: { taskId: task.id } });- run(task.id, target);- return;- }// Straight to the Space: the one picked, the one being made (its page follows the create), or this Mac's.const go = (spaceId: string) => void navigate({ to: "/spaces/$spaceId", params: { spaceId } });if (target.kind === "space") {diff --git a/apps/cua-spaces-web/src/components/machines/account-parts.tsx b/apps/cua-spaces-web/src/components/machines/account-parts.tsxnew file mode 100644index 0000000000..f7fb64a04a--- /dev/null+++ b/apps/cua-spaces-web/src/components/machines/account-parts.tsx@@ -0,0 +1,271 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { HashIcon, UserRoundIcon, UsersIcon } from "lucide-react";+import { useMemo, useState } from "react";++import { useDevices, useSession, type AccessLine, type MachinesAccountView, type PendingMachine, type ThisMachineTrust } from "@/bridge";+import { OsIcon } from "@/components/os-icon";+import { ConfirmDialog } from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";+import { toast } from "@/components/ui/toast";+import { dateText, relativeText } from "@/lib/devices";+import type { SpaceOs } from "@/bridge";++const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));++/** The account's part of the Machines page: what waits, this machine's trust, who reached each machine. */+export function useMachinesAccount(): {+ account: MachinesAccountView | null;+ /** Machines waiting to be added (the ones put off are left out). */+ pending: PendingMachine[];+ now: number;+ devices: ReturnType<typeof useDevices>;+} {+ const { data: session } = useSession();+ const devices = useDevices();+ const account = session?.signedIn === false ? null : (devices.data?.account ?? null);+ const dismissed = devices.data?.dismissed;+ const pending = useMemo(() => (account?.pending ?? []).filter((p) => p.kind !== "sign-in" || !dismissed?.includes(p.device ?? "")), [account, dismissed]);+ return { account, pending, now: devices.data?.now ?? Math.floor(Date.now() / 1000), devices };+}++/** `macOS` as the three systems the app draws. */+export function pendingOs(p: Pick<PendingMachine, "os">): SpaceOs | null {+ const os = p.os.toLowerCase();+ return os === "macos" ? "macos" : os === "windows" ? "windows" : os === "linux" ? "linux" : null;+}++/** [Add machine] [Not me] for one waiting machine: the one place that does either. */+export function usePendingActions() {+ const { devices } = useMachinesAccount();+ const [notMe, setNotMe] = useState<PendingMachine | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ const run = (p: PendingMachine, what: () => Promise<unknown>, done: string, failed: string) => {+ setBusy(p.id);+ void what().then(+ () => toast(done, { type: "success" }),+ (e: unknown) => toast(failed, { description: errorText(e), type: "error" }),+ ).finally(() => setBusy(null));+ };+ return {+ busy,+ add: (p: PendingMachine) =>+ run(p, () => (p.kind === "machine" ? devices.confirmMachine(p.machine!) : devices.addMachine(p.device!)), `Added ${p.name}`, `Couldn't add ${p.name}`),+ /** Not me: a machine that signed in is denied at once; one that registered is removed after a question. */+ notMe: (p: PendingMachine) => (p.kind === "machine" ? setNotMe(p) : run(p, () => devices.denyDevice(p.device!), `${p.name} was not added`, `Couldn't refuse ${p.name}`)),+ notMeDialog: (remove: (machine: string) => Promise<unknown>) => (+ <ConfirmDialog+ open={notMe !== null}+ onOpenChange={(o) => !o && setNotMe(null)}+ title={`Not you? Remove “${notMe?.name ?? ""}”`}+ description="It leaves your account. Setting it up again adds it back."+ confirmLabel="Remove"+ destructive+ onConfirm={() => notMe && run(notMe, () => remove(notMe.machine!), `${notMe.name} was removed`, `Couldn't remove ${notMe.name}`)}+ />+ ),+ };+}++/** One waiting machine in the list's top group: name, system, its line, and the two choices. */+export function PendingRow({+ machine: p,+ selected,+ busy,+ onSelect,+ onAdd,+ onNotMe,+}: {+ machine: PendingMachine;+ selected: boolean;+ busy: boolean;+ onSelect: () => void;+ onAdd: () => void;+ onNotMe: () => void;+}) {+ const os = pendingOs(p);+ return (+ <div+ data-pending-machine={p.id}+ data-pending-kind={p.kind}+ aria-selected={selected}+ className={`rounded-lg px-2 py-[7px] ${selected ? "bg-brand/15" : "hover:bg-accent/60"}`}+ >+ <button type="button" onClick={onSelect} className="flex w-full cursor-default items-center gap-2.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/60 rounded-lg">+ <span aria-hidden className="size-2 shrink-0 rounded-full bg-warning" />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[13px] font-medium">{p.name}</span>+ <span className="block truncate text-xs text-muted-foreground" data-pending-line="">+ {p.line}+ </span>+ </span>+ {os ? <OsIcon os={os} className="size-3.5 shrink-0 text-muted-foreground/70" /> : null}+ </button>+ <div className="mt-1.5 flex gap-1.5 pl-[18px]">+ <Button size="sm" className="h-6 px-2 text-xs" disabled={busy} onClick={onAdd} data-pending-add="">+ {p.addLabel}+ </Button>+ <Button size="sm" variant="ghost" className="h-6 px-2 text-xs" disabled={busy} onClick={onNotMe} data-pending-not-me="">+ {p.notMeLabel}+ </Button>+ </div>+ </div>+ );+}++/** "Add this machine?": the waiting machine's page, with its name, system and when it asked, and two buttons. */+export function PendingDetail({ machine: p, now, busy, onAdd, onNotMe }: { machine: PendingMachine; now: number; busy: boolean; onAdd: () => void; onNotMe: () => void }) {+ return (+ <section aria-label={`${p.name} is waiting`} className="min-w-0 max-w-[620px]" data-pending-detail={p.id}>+ <h2 className="text-[22px] font-semibold tracking-[-0.015em]">Add this machine?</h2>+ <p className="mt-1.5 text-[13px] text-muted-foreground">{p.text}</p>+ <dl className="mt-5 border-y">+ <Fact label="Name" value={p.name} />+ {p.os ? <Fact label="System" value={p.os} /> : null}+ {p.since ? <Fact label="Last seen" value={relativeText(p.since, now)} /> : null}+ </dl>+ <div className="mt-5 flex gap-2">+ <Button disabled={busy} onClick={onAdd} data-pending-add="">+ {p.addLabel}+ </Button>+ <Button variant="outline" disabled={busy} onClick={onNotMe} data-pending-not-me="">+ {p.notMeLabel}+ </Button>+ </div>+ </section>+ );+}++function Fact({ label, value }: { label: string; value: string }) {+ return (+ <div className="grid grid-cols-[140px_1fr] border-t py-2.5 text-[13px] first:border-t-0">+ <dt className="text-muted-foreground">{label}</dt>+ <dd className="select-text">{value}</dd>+ </div>+ );+}++/** This machine's own trust, in plain words, with the one action that fixes it. */+export function TrustSection({ trust, onTrust }: { trust: ThisMachineTrust; onTrust: () => void }) {+ const status = trust.at === null ? trust.status : `${trust.status} ${dateText(trust.at)}`;+ return (+ <>+ <h3 className="mt-5 mb-2 text-xs font-semibold text-muted-foreground">Access to your machines</h3>+ <div className="border-y" data-machine-trust={trust.kind}>+ <div className="flex min-h-11 items-center justify-between gap-4 py-2.5">+ <span className={`text-[13px] ${trust.kind === "enrolled" ? "text-muted-foreground" : "text-warning"}`} data-machine-trust-status="">+ {status}+ </span>+ {trust.actionLabel ? (+ <Button size="sm" variant="outline" onClick={onTrust} data-machine-trust-action="">+ {trust.actionLabel}+ </Button>+ ) : null}+ </div>+ {trust.text ? (+ <p className="border-t py-2.5 text-xs text-muted-foreground" data-machine-trust-text={trust.tone ?? ""}>+ {trust.text}+ </p>+ ) : null}+ </div>+ </>+ );+}++/** Who reached this machine lately: a few lines, newest first. */+export function RecentAccess({ lines, title, empty, now, error }: { lines: AccessLine[]; title: string; empty: string; now: number; error?: string | null }) {+ return (+ <>+ <h3 className="mt-7 mb-2 text-xs font-semibold text-muted-foreground">{title}</h3>+ <div className="border-y" data-machine-recent="">+ {lines.length === 0 ? <p className="py-3 text-[13px] text-muted-foreground">{empty}</p> : null}+ {lines.map((a, i) => (+ <div key={`${a.ts}-${i}`} data-recent-row="" className={`flex min-h-10 items-center justify-between gap-4 py-2 ${i > 0 ? "border-t" : ""}`}>+ <span className="flex min-w-0 items-center gap-2 text-[13px]">+ {a.notable ? <UsersIcon className="size-3.5 shrink-0 text-warning" aria-label="Another account or an untrusted machine" /> : null}+ <span className="select-text" data-recent-text="">+ {a.text}+ </span>+ </span>+ <span className="shrink-0 text-xs text-muted-foreground">{relativeText(a.ts, now)}</span>+ </div>+ ))}+ {error ? (+ <p data-devices-read-error="" className="border-t py-2.5 text-xs break-words text-destructive">+ {error}+ </p>+ ) : null}+ </div>+ </>+ );+}++/** "Trust this machine": sign in again, or add it from a machine you already trust with a one-time code. */+export function EnrollSheet() {+ const { data, chooseEnroll, backEnroll, closeEnroll } = useDevices();+ const v = data?.enroll?.view;+ return (+ <Dialog open={Boolean(v)} onOpenChange={(o) => !o && closeEnroll()}>+ <DialogPopup className="w-[min(440px,calc(100vw-2rem))]" data-enroll>+ {v ? (+ <>+ <div className="px-5 pt-5 pb-4">+ <DialogTitle className="text-[15px] font-semibold" data-enroll-title>+ {v.title}+ </DialogTitle>+ <p className="mt-1.5 text-[13px] text-muted-foreground">{v.lede}</p>+ {v.options.length > 0 ? (+ <div className="mt-4 flex flex-col gap-2">+ {v.options.map((o) => (+ <button+ key={o.method}+ type="button"+ data-enroll-option={o.method}+ onClick={() => void chooseEnroll(o.method)}+ className="flex items-center gap-3 rounded-lg border bg-card px-3 py-2.5 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ {o.method === "sign-in" ? <UserRoundIcon className="size-5 text-muted-foreground" /> : <HashIcon className="size-5 text-muted-foreground" />}+ <span className="min-w-0">+ <span className="block text-[13px] font-medium">{o.title}</span>+ <span className="block text-xs text-muted-foreground">{o.detail}</span>+ </span>+ </button>+ ))}+ </div>+ ) : null}+ {v.code ? (+ <p className="mt-5 text-center font-mono text-[28px] font-semibold tracking-wider select-text" data-enroll-code>+ {v.code}+ </p>+ ) : null}+ {v.codeHelp ? <p className="mt-3 text-xs text-muted-foreground">{v.codeHelp.replace(/`/g, "")}</p> : null}+ {v.status ? (+ <p className="mt-4 flex items-center gap-2 text-[13px] text-muted-foreground" data-enroll-status>+ {v.busy ? <span className="size-3 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-muted-foreground" /> : null}+ {v.status}+ </p>+ ) : null}+ {v.error ? (+ <p className="mt-3 text-[13px] text-destructive select-text" data-enroll-error>+ {v.error}+ </p>+ ) : null}+ </div>+ <div className="flex justify-end gap-2 border-t bg-muted/60 px-5 py-3">+ {v.backLabel ? (+ <Button variant="outline" onClick={backEnroll} data-enroll-back>+ {v.backLabel}+ </Button>+ ) : null}+ <Button variant={v.done ? "default" : "outline"} onClick={closeEnroll} data-enroll-close>+ {v.closeLabel}+ </Button>+ </div>+ </>+ ) : null}+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/cua-spaces-web/src/components/settings/account-keys.tsx b/apps/cua-spaces-web/src/components/settings/account-keys.tsxdeleted file mode 100644index d79ff64a3f..0000000000--- a/apps/cua-spaces-web/src/components/settings/account-keys.tsx+++ /dev/null@@ -1,119 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { TriangleAlertIcon } from "lucide-react";--import { useAgentKeys, type AgentKeyRowView } from "@/bridge";-import { KeySheet } from "@/components/agents/key-sheet";-import { ConfirmDialog } from "@/components/ui/alert-dialog";-import { SettingsGroup } from "@/components/settings-group";-import { Button } from "@/components/ui/button";-import { GroupedRow, SettingRow } from "@/components/ui/grouped";-import { toastError } from "@/components/ui/toast";-import { addedText } from "@/lib/agent-keys";-import { KEYS_ADD_OTHER_BUTTON, KEYS_ADD_OTHER_LABEL, KEYS_OTHER_HELP, KEYS_TITLE, plainKeysIntro } from "@/lib/settings-copy";--/**- * Settings, Connectors, Account keys: the provider keys agents in your Spaces get. Anthropic- * and OpenAI always have a row, other keys follow by variable name; Add or- * Replace opens a sheet with a secure field (the key is never shown again),- * Remove asks first. Every word is the app core's `agent_keys` view.- */-export function AccountKeysSection() {- // The keys also change outside the app (`cua agent keys`): read them again when this page shows- // and whenever the window gets focus.- const keys = useAgentKeys({ watch: true });- const { view } = keys;- if (keys.unsupported) return <p className="px-1 text-[13px] text-muted-foreground">Agent keys are not available in this app yet.</p>;- if (keys.isLoading) return <p className="px-1 text-[13px] text-muted-foreground" data-agent-keys-loading>Loading agent keys…</p>;- if (!view) return <p className="px-1 text-[13px] text-muted-foreground">Agent keys need the app core, which isn't loaded.</p>;- const confirm = keys.removing ? keys.removeConfirmOf(keys.removing) : null;-- return (- <div data-agent-keys>- {view.notice ? (- <div data-agent-keys-notice className="mb-4 flex items-start gap-2.5 rounded-lg bg-warning/10 px-4 py-2.5 text-[13px]">- <TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-warning" />- <span className="min-w-0 flex-1">{view.notice}</span>- {keys.error ? (- <Button size="sm" variant="outline" onClick={() => void keys.refresh()}>- Try again- </Button>- ) : null}- </div>- ) : null}-- <SettingsGroup title={<span data-agent-keys-title>{KEYS_TITLE}</span>} footer={<span data-agent-keys-intro>{plainKeysIntro(view.intro)}</span>}>- {view.rows.map((r) => (- <KeyRow key={`${r.provider}:${r.env}`} row={r} addedLabel={view.addedLabel} canEdit={view.canEdit} onEdit={() => keys.openSheet(r.provider, r.provider === "other" ? r.env : null)} onRemove={() => keys.askRemove(r.env)} />- ))}- <SettingRow- label={KEYS_ADD_OTHER_LABEL}- help={<span data-agent-key-other-help>{KEYS_OTHER_HELP}</span>}- control={- <Button size="sm" variant="outline" disabled={!view.canEdit} onClick={() => keys.openSheet("other")} data-agent-key-add-other>- {KEYS_ADD_OTHER_BUTTON}- </Button>- }- />- </SettingsGroup>-- {keys.sheet ? <KeySheet key={`${keys.sheet.provider}:${keys.sheet.env ?? ""}`} keys={keys} provider={keys.sheet.provider} env={keys.sheet.env} /> : null}- <ConfirmDialog- open={confirm !== null}- onOpenChange={(o) => !o && keys.askRemove(null)}- title={confirm?.title ?? ""}- description={confirm?.message ?? ""}- confirmLabel={confirm?.confirmLabel ?? "Remove"}- cancelLabel={confirm?.cancelLabel}- destructive- onConfirm={() => {- const env = keys.removing;- if (env) void keys.remove(env).catch(toastError("Couldn't remove the key"));- }}- />- </div>- );-}--function KeyRow({ row: r, addedLabel, canEdit, onEdit, onRemove }: { row: AgentKeyRowView; addedLabel: string; canEdit: boolean; onEdit: () => void; onRemove: () => void }) {- return (- <GroupedRow data-agent-key-row={r.env} data-agent-key-provider={r.provider} data-set={String(r.set)}>- <div className="min-w-0 flex-1">- <div className="flex items-baseline gap-2">- <span className="truncate text-[13px]" data-agent-key-title>- {r.title}- </span>- {r.title !== r.env ? (- <span className="truncate font-mono text-[11px] text-muted-foreground" data-agent-key-env>- {r.env}- </span>- ) : null}- </div>- <div className="truncate text-xs text-muted-foreground" data-agent-key-detail>- {r.detail}- </div>- </div>- <div className="flex shrink-0 flex-col items-end">- <span className={r.set ? "font-mono text-[12px]" : "text-[13px] text-muted-foreground"} data-agent-key-status>- {r.status}- </span>- {r.addedMs !== null ? (- <span className="text-[11px] text-muted-foreground" data-agent-key-added>- {addedText(addedLabel, r.addedMs)}- </span>- ) : null}- </div>- <div className="flex shrink-0 items-center gap-1.5">- <Button size="sm" variant="outline" disabled={!canEdit} onClick={onEdit} data-agent-key-action>- {r.actionLabel}- </Button>- {r.removeLabel ? (- <Button size="sm" variant="ghost" disabled={!canEdit} onClick={onRemove} data-agent-key-remove>- {r.removeLabel}- </Button>- ) : null}- </div>- </GroupedRow>- );-}diff --git a/apps/cua-spaces-web/src/components/settings/account-tab.tsx b/apps/cua-spaces-web/src/components/settings/account-tab.tsxindex 4e9042bcc7..f1735727a1 100644--- a/apps/cua-spaces-web/src/components/settings/account-tab.tsx+++ b/apps/cua-spaces-web/src/components/settings/account-tab.tsx@@ -127,7 +127,7 @@ export function AccountTab() {<div data-relay-usage=""><UsageBarid="Remote hours"- label="Time away from this computer"+ label="Time away from this machine"text={`${hours(usage.hoursUsed)} of ${usage.hoursLimit ?? 0} hours`}used={usage.hoursUsed}limit={usage.hoursLimit}diff --git a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsxindex 49ae02d0ae..719d65acb0 100644--- a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx+++ b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx@@ -45,7 +45,7 @@ export function AdvancedTab() {<EarlyReleases /><Labs />{runtimes || autoConnect || overflow ? (- <SettingsGroup title="Which software runs Spaces on this computer">+ <SettingsGroup title="Which software runs Spaces on this machine">{/* One row per kind of Space, as the core lays them out (always there, "Checking…" until the host read them). */}{runtimes ? <RuntimeKindRows section={runtimes} onChoose={choose} /> : null}{autoConnect ? <CoreSettingsRow row={{ ...autoConnect, label: "Open a Space’s screen right away" }} onChoose={choose} /> : null}@@ -133,7 +133,6 @@ function thisMacAskRow(asks: boolean): CoreRow {function Labs() {const { data, chooseExperiment } = useExperiments();const askFirst = useFlag("spaces_ask_first_home");- const redesign = useFlag("spaces_redesign");const thisMacOk = useThisMacConfirmed();const rows = (data?.page?.sections.flatMap((s) => s.rows) ?? []).filter((r) => LABS.has(r.id));const note: Record<string, string> = {@@ -141,11 +140,6 @@ function Labs() {};return (<SettingsGroup title="Labs">- <CoreSettingsRow- row={flagRow("spaces_redesign", "New design", redesign)}- description="The new Spaces page, Space page and Agents tab. Turn off to use the classic design. On this device only."- onChoose={(_, option) => setFlagOverride("spaces_redesign", option === "on")}- /><CoreSettingsRowrow={flagRow("spaces_ask_first_home", "Try the new Home", askFirst)}description="Home asks what you want done, then does it on a fresh computer you can watch. On this device only."diff --git a/apps/cua-spaces-web/src/components/settings/coding-apps-section.tsx b/apps/cua-spaces-web/src/components/settings/coding-apps-section.tsxdeleted file mode 100644index 79804f80b4..0000000000--- a/apps/cua-spaces-web/src/components/settings/coding-apps-section.tsx+++ /dev/null@@ -1,206 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { ChevronDownIcon, ChevronRightIcon, ChevronUpIcon } from "lucide-react";-import { lazy, Suspense, useEffect, useState } from "react";--import type { AgentSetupRow } from "@/bridge";-import { HarnessMark } from "@/components/agents/harness-mark";-import { SettingsGroup, SettingsRow } from "@/components/settings-group";-import { Snippet } from "@/components/settings/snippet";-import { Button } from "@/components/ui/button";-import { GroupedAction, GroupedRow } from "@/components/ui/grouped";-import { Segmented } from "@/components/ui/segmented";-import { Switch } from "@/components/ui/switch";-import { useBridge } from "@/bridge";-import type { ConnectedApps } from "@/hooks/use-connected-apps";-import { BY_HAND, getItUrl, missingApps, shownApps } from "@/lib/connected-apps";-import { cn } from "@/lib/utils";--// Its miniature and setup load with the card.-const DriverSettingsCard = lazy(() => import("@/components/volume/driver-card").then((m) => ({ default: m.DriverSettingsCard })));--/**- * Settings, Connectors, "Coding apps": the coding apps on this computer,- * one switch each for Cua being set up in it (with Background computer use),- * and "Set up new apps automatically". Rows show only the app and its switch.- * "Show all" opens the apps that aren't installed, Background computer use,- * and a collapsed "Advanced" with each app's settings file and adding Cua by hand.- */-export function CodingAppsSection({ apps, focusApp }: { apps: ConnectedApps; focusApp?: string }) {- const { openExternal } = useExternal();- const shown = shownApps(apps.rows ?? []);- const missing = missingApps(apps.rows ?? []);- const [all, setAll] = useState(() => Boolean(focusApp) && !shown.some((r) => r.agent === focusApp) && missing.some((r) => r.agent === focusApp));- const [lit, setLit] = useState<string | null>(null);- const ready = apps.rows !== null;-- // Coming from the Agents page's Connect: bring that app's row into view and mark it for a moment.- useEffect(() => {- if (!ready || !focusApp) return;- const row = document.querySelector<HTMLElement>(`[data-connected-app="${focusApp}"], [data-connected-missing="${focusApp}"]`);- if (!row) return;- row.scrollIntoView?.({ block: "center" });- setLit(focusApp);- const t = setTimeout(() => setLit(null), 2000);- return () => clearTimeout(t);- }, [ready, focusApp, all]);-- if (!ready) return <div className="mb-8 h-48" aria-busy="true" />;-- return (- <div data-connected-apps="">- <SettingsGroup title="Coding apps">- {shown.length === 0 ? (- <GroupedRow className="text-muted-foreground" data-connected-none="">- We didn't find a coding app yet. Install one and Cua will notice.- </GroupedRow>- ) : (- shown.map((row) => <AppRow key={row.agent} row={row} apps={apps} lit={lit === row.agent} />)- )}- <SettingsRow- label="Set up new apps automatically"- description="When you install another coding app, Cua adds itself and tells you."- htmlFor="connected-auto"- control={<Switch id="connected-auto" data-connected-auto="" checked={apps.state.auto === true} onCheckedChange={apps.setAuto} />}- />- {all && missing.length > 0 ? (- <>- <GroupedRow className="min-h-9 bg-muted/40 py-2 text-xs text-muted-foreground">Not installed</GroupedRow>- {missing.map((row) => {- const url = getItUrl(row.agent);- return (- <GroupedRow key={row.agent} data-connected-missing={row.agent} className={cn("text-muted-foreground transition-colors", lit === row.agent && "bg-accent")}>- <HarnessMark agent={row.agent} name={row.name} />- <span className="min-w-0 flex-1 text-[13px]">{row.name}</span>- {url ? (- <button type="button" className="text-xs hover:text-foreground hover:underline" onClick={() => void openExternal(url)}>- Get it- </button>- ) : null}- </GroupedRow>- );- })}- </>- ) : null}- <GroupedAction data-connected-show-all="" aria-expanded={all} onClick={() => setAll(!all)}>- {all ? "Show fewer" : "Show all"} {all ? <ChevronUpIcon className="size-3.5" /> : <ChevronDownIcon className="size-3.5" />}- </GroupedAction>- </SettingsGroup>- {all ? (- <>- <SettingsGroup title="Background computer use">- <Suspense fallback={<div className="h-48" />}>- <DriverSettingsCard />- </Suspense>- </SettingsGroup>- <Advanced rows={shown} />- </>- ) : null}- </div>- );-}--function useExternal() {- const { data } = useBridge();- return { openExternal: async (url: string) => void (await data?.call("session.openExternal", { url }).catch(() => {})) };-}--function AppRow({ row, apps, lit }: { row: AgentSetupRow; apps: ConnectedApps; lit?: boolean }) {- const busy = apps.pending.includes(row.agent);- const failure = apps.failures[row.agent];- const on = row.configured && !failure;- const justOff = !row.configured && apps.state.off.includes(row.agent);- const note = failure ? null : justOff ? "Off." : null;- return (- <div data-connected-app={row.agent} data-on={String(on)} data-failed={failure ? "" : undefined} className={cn("transition-colors", failure && "bg-destructive/5", lit && "bg-accent")}>- <GroupedRow>- <HarnessMark agent={row.agent} name={row.name} />- <div className="min-w-0 flex-1">- <label htmlFor={`app-${row.agent}`} className="block truncate text-[13px]">- {row.name}- </label>- {note ? <p className="mt-0.5 truncate text-xs text-muted-foreground">{note}</p> : null}- </div>- <Switch id={`app-${row.agent}`} checked={on} disabled={busy} onCheckedChange={(next) => void apps.toggle(row, next)} />- </GroupedRow>- {failure ? <Failure row={row} text={failure} busy={busy} onRetry={() => void apps.toggle(row, true)} /> : null}- </div>- );-}--/** A setup that didn't work: why, Try again, and the by-hand snippet for this app. */-function Failure({ row, text, busy, onRetry }: { row: AgentSetupRow; text: string; busy: boolean; onRetry: () => void }) {- const [hand, setHand] = useState(false);- const snippet = BY_HAND[row.agent];- return (- <div className="px-4 pb-4 pl-14" data-connected-failure={row.agent}>- <p className="text-[13px] text-destructive">{text}</p>- <div className="mt-3 flex gap-2">- <Button size="sm" variant="outline" disabled={busy} onClick={onRetry}>- Try again- </Button>- {snippet ? (- <Button size="sm" variant="outline" aria-expanded={hand} onClick={() => setHand(!hand)}>- Add it by hand- </Button>- ) : null}- </div>- {hand && snippet ? (- <>- <Snippet file={snippet.file} text={snippet.snippet} />- <p className="mt-2 text-xs text-muted-foreground">Paste this into the file, then restart {row.name}.</p>- </>- ) : null}- </div>- );-}--/**- * "Advanced", closed by default: the file each app keeps its settings in, and- * adding Cua by hand. Most people never need either.- */-function Advanced({ rows }: { rows: AgentSetupRow[] }) {- const files = rows.filter((r) => r.mcpConfig);- return (- <details className="group mb-8" data-connected-advanced="">- <summary className="-ml-1 flex w-fit cursor-default list-none items-center gap-1 rounded-lg px-1 py-0.5 text-[11px] font-semibold tracking-wide text-muted-foreground uppercase outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 [&::-webkit-details-marker]:hidden">- <ChevronRightIcon className="size-3 transition-transform group-open:rotate-90" aria-hidden /> Advanced- </summary>- <div className="mt-8">- {files.length > 0 ? (- <SettingsGroup title="Settings files">- {files.map((r) => (- <GroupedRow key={r.agent} data-connected-file={r.agent}>- <span className="w-40 shrink-0 truncate text-[13px]">{r.name}</span>- <code className="min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground select-text" title={r.mcpConfig ?? undefined}>- {r.mcpConfig}- </code>- </GroupedRow>- ))}- </SettingsGroup>- ) : null}- <ByHand />- </div>- </details>- );-}--/** "Add it by hand": for an app in an unusual place, another computer, or a work laptop where Cua may not edit settings. */-function ByHand() {- const ids = Object.keys(BY_HAND);- const [id, setId] = useState(ids[0]!);- const entry = BY_HAND[id]!;- const label: Record<string, string> = { "claude-code": "Claude Code", codex: "Codex", hermes: "Hermes", openclaw: "OpenClaw", cursor: "Cursor" };- return (- <SettingsGroup title="Add it by hand" className="mb-0" data-connected-by-hand="">- <div className="px-4 py-4">- <Segmented aria-label="App" value={id} options={ids.map((value) => ({ value, label: label[value] ?? value }))} onValueChange={setId} />- <Snippet file={entry.file} text={entry.snippet} />- <p className="mt-2 text-xs text-muted-foreground">- Use the full path to <code className="font-mono">cua</code> if the app runs without your shell's PATH, as apps opened from the Dock do.- </p>- </div>- </SettingsGroup>- );-}diff --git a/apps/cua-spaces-web/src/components/settings/connectors/app-detail.tsx b/apps/cua-spaces-web/src/components/settings/connectors/app-detail.tsxindex 9fd5d33806..8a00ed34f7 100644--- a/apps/cua-spaces-web/src/components/settings/connectors/app-detail.tsx+++ b/apps/cua-spaces-web/src/components/settings/connectors/app-detail.tsx@@ -5,6 +5,7 @@ import { Link } from "@tanstack/react-router";import { CheckIcon, ChevronLeftIcon, Loader2Icon } from "lucide-react";import { HarnessMark } from "@/components/agents/harness-mark";+import { useThisAndOthers } from "@/components/agents/other-machine-block";import { SettingsGroup, SettingsRow } from "@/components/settings-group";import { Snippet } from "@/components/settings/snippet";import { Button } from "@/components/ui/button";@@ -23,6 +24,7 @@ import { cn } from "@/lib/utils";*/export function ConnectorAppPage({ agent }: { agent: string }) {const c = useConnectors();+ const { hereName } = useThisAndOthers();const d = c.detail(agent);const back = (<Link to="/settings/connectors" className="-ml-1 mb-4 inline-flex items-center gap-0.5 rounded-lg px-1 py-0.5 text-[13px] text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60" data-connector-back="">@@ -53,6 +55,10 @@ export function ConnectorAppPage({ agent }: { agent: string }) {{busy ? <Loader2Icon className="size-3.5 animate-spin" /> : d.connected ? <CheckIcon className="size-3.5 text-success" /> : null}{d.status}</p>+ {/* Connect edits the apps of this machine only: the page says which. */}+ <p className="text-xs text-muted-foreground" data-connector-on="">+ On {hereName}+ </p>{failure ? <p className="text-[13px] text-destructive">{failure}</p> : null}</div>{d.connect ? (diff --git a/apps/cua-spaces-web/src/components/settings/connectors/connectors-page.tsx b/apps/cua-spaces-web/src/components/settings/connectors/connectors-page.tsxindex 48c01b0bad..f7664debec 100644--- a/apps/cua-spaces-web/src/components/settings/connectors/connectors-page.tsx+++ b/apps/cua-spaces-web/src/components/settings/connectors/connectors-page.tsx@@ -5,7 +5,8 @@ import { useNavigate } from "@tanstack/react-router";import { CheckIcon, ChevronDownIcon, ChevronRightIcon, ChevronUpIcon, Loader2Icon, TriangleAlertIcon } from "lucide-react";import { lazy, Suspense, useEffect, useState, type KeyboardEvent, type MouseEvent } from "react";-import { useAgentKeys, useBridge, type ConnectorAppRow, type ConnectorProviderRow } from "@/bridge";+import { useAgentKeys, useBridge, useKeysRecheck, type ConnectorAppRow, type ConnectorProviderRow } from "@/bridge";+import { OtherMachineBlock, useThisAndOthers } from "@/components/agents/other-machine-block";import { HarnessMark } from "@/components/agents/harness-mark";import { KeySheet } from "@/components/agents/key-sheet";import { SettingsGroup, SettingsRow } from "@/components/settings-group";@@ -22,7 +23,7 @@ import { cn } from "@/lib/utils";const DriverSettingsCard = lazy(() => import("@/components/volume/driver-card").then((m) => ({ default: m.DriverSettingsCard })));/**- * Settings, Connectors (redesign): Coding apps, each with Connect (Cua's+ * Settings, Connectors: Coding apps, each with Connect (Cua's* tools and the app's sign-in, once) and a chevron to its own page; then* Providers, each with Connect (the provider's sign-in where there is one* for this, else a key) or Sign out. Every word and state is the core's@@ -34,7 +35,11 @@ export function ConnectorsRedesign({ focusApp }: { focusApp?: string }) {const navigate = useNavigate();const { data } = useBridge();const keys = useAgentKeys();+ // Opening this page asks the providers whether the saved sign-ins and keys still work.+ useKeysRecheck();const [all, setAll] = useState(false);+ const [otherOpen, setOtherOpen] = useState(false);+ const { hereName, others } = useThisAndOthers();const [lit, setLit] = useState<string | null>(null);useEffect(() => {@@ -58,7 +63,16 @@ export function ConnectorsRedesign({ focusApp }: { focusApp?: string }) {</div>) : null}- <SettingsGroup title={view.appsTitle} data-connectors-apps="">+ <SettingsGroup+ title={view.appsTitle}+ data-connectors-apps=""+ footer={+ // Connect edits the coding apps of this machine only: it says which, and what it leaves alone.+ <span data-connectors-machine="">+ On {hereName}.{others.length > 0 ? ` Not touched: ${others.join(", ")}. An agent on one of those machines needs its own setup (see On another machine).` : ""}+ </span>+ }+ >{view.appsEmpty ? <GroupedRow className="text-muted-foreground">{view.appsEmpty}</GroupedRow> : null}{view.apps.map((row) => (<AppRow key={row.agent} row={row} lit={lit === row.agent} onOpen={() => open(row.agent)} onConnect={() => void c.connectApp(row.agent)} />@@ -100,6 +114,19 @@ export function ConnectorsRedesign({ focusApp }: { focusApp?: string }) {</SettingsGroup>) : null}+ <SettingsGroup title="On another machine" data-connectors-other-machine-group="">+ <GroupedRow>+ <div className="min-w-0 flex-1">+ <div className="text-[13px]">An agent on another machine</div>+ <div className="text-xs text-muted-foreground">Use {hereName} from an agent that runs somewhere else.</div>+ </div>+ <Button size="sm" variant="outline" aria-expanded={otherOpen} onClick={() => setOtherOpen(!otherOpen)} data-connectors-other-toggle="">+ {otherOpen ? "Hide" : "Show how"}+ </Button>+ </GroupedRow>+ {otherOpen ? <OtherMachineBlock /> : null}+ </SettingsGroup>+<SettingsGroup title={view.providersTitle} footer={view.providersFooter} data-connectors-providers="">{view.providers.map((p) => (<ProviderRow key={p.id} row={p} addedLabel={view.addedLabel} c={c} />diff --git a/apps/cua-spaces-web/src/components/settings/general-tab.tsx b/apps/cua-spaces-web/src/components/settings/general-tab.tsxindex 5e7739e2b1..7d09ea4f15 100644--- a/apps/cua-spaces-web/src/components/settings/general-tab.tsx+++ b/apps/cua-spaces-web/src/components/settings/general-tab.tsx@@ -36,7 +36,7 @@ export const showCuaIn = (row: CoreRow): CoreRow => ({/*** Settings, General: the few things a person sets every day. Start at login,* where Cua lives (Mac), appearance, the shortcut (Mac) and usage data.- * Everything else moved: Advanced, Connectors, Trusted machines, the Volume+ * Everything else moved: Advanced, Connectors, the Volume* and Keyvault pages.*/export function GeneralTab() {diff --git a/apps/cua-spaces-web/src/components/settings/screen-permissions-section.tsx b/apps/cua-spaces-web/src/components/settings/screen-permissions-section.tsxdeleted file mode 100644index d5a804d867..0000000000--- a/apps/cua-spaces-web/src/components/settings/screen-permissions-section.tsx+++ /dev/null@@ -1,50 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { CheckIcon } from "lucide-react";--import { useScreenPermissions } from "@/bridge";-import { SettingsGroup, SettingsRow } from "@/components/settings-group";-import { Button } from "@/components/ui/button";-import { toastError } from "@/components/ui/toast";--/**- * Settings, Trusted machines, "Let others use this machine": the first run's "Share this Mac's screen" rows- * (Screen Recording, Accessibility), for whoever chose "Not now" there.- * Only on a Mac that is set up and shares its screen. Allow opens the app's- * guide to the System Settings pane; a check shows once it is granted.- */-export function ScreenPermissionsSection() {- const perms = useScreenPermissions();- if (!perms) return null;- const { view } = perms;- const place = view.rows.map((r) => /^See (.+)\u2019?'?s screen$/.exec(r.title)?.[1]).find(Boolean) ?? "this machine";- return (- <SettingsGroup title="Let others use this machine">- {view.rows.map((r) => (- <SettingsRow- key={r.id}- label={r.id === "accessibility" ? `Let others click and type on ${place}` : r.title.replace(/^See /, "Let others see ")}- description={r.note}- control={- r.state === "ok" ? (- <span className="flex size-5 items-center justify-center rounded-full bg-[#1f9d55] text-white" aria-label="Allowed" data-settings-permission={r.id} data-state="ok">- <CheckIcon className="size-3" strokeWidth={3} />- </span>- ) : r.action && r.settingsUrl ? (- <Button- size="sm"- variant="outline"- data-settings-permission={r.id}- data-state={r.state}- onClick={() => void perms.allow(r.settingsUrl!).catch(toastError("Couldn't open System Settings"))}- >- {r.action.label}- </Button>- ) : null- }- />- ))}- </SettingsGroup>- );-}diff --git a/apps/cua-spaces-web/src/components/shell/command-palette.tsx b/apps/cua-spaces-web/src/components/shell/command-palette.tsxindex 43974f7fcd..5bb4236eaa 100644--- a/apps/cua-spaces-web/src/components/shell/command-palette.tsx+++ b/apps/cua-spaces-web/src/components/shell/command-palette.tsx@@ -134,7 +134,7 @@ function PaletteBody({ onClose }: { onClose: () => void }) {icon: icon(n.icon),run: () => void navigate({ to: n.to }),})),- // Each Settings tab, so Cmd+K finds "Connectors" or "Trusted machines" by name.+ // Each Settings tab, so Cmd+K finds "Connectors" or "Advanced" by name....SETTINGS_TABS.filter((t) => t.to !== "/settings").map((t) => ({id: `settings:${t.to}`,group: "Go to",diff --git a/apps/cua-spaces-web/src/components/shell/devices-banner.tsx b/apps/cua-spaces-web/src/components/shell/devices-banner.tsxindex 3acbebec2a..5d048d924f 100644--- a/apps/cua-spaces-web/src/components/shell/devices-banner.tsx+++ b/apps/cua-spaces-web/src/components/shell/devices-banner.tsx@@ -12,8 +12,8 @@ import { cn } from "@/lib/utils";/*** This device needs enrolling or re-verifying: one bar above every page,* the core's words and its Enroll… (the SwiftUI app's `DevicesBanner`).- * Settings, Devices says the same under its own row, so the bar stays off- * that page.+ * This machine's page says the same under its own name, so the bar stays off+ * the Machines page.*/export function DevicesBanner() {const { data: session } = useSession();@@ -21,14 +21,14 @@ export function DevicesBanner() {const { pathname } = useLocation();const navigate = useNavigate();const banner = shellDevicesBanner(devices.data, session?.signedIn);- if (!banner || pathname.startsWith("/settings/devices")) return null;+ if (!banner || pathname.startsWith("/machines")) return null;const critical = banner.tone === "critical";const Icon = critical ? TriangleAlertIcon : CircleAlertIcon;- // The enroll sheet is the Devices page's.+ // The sheet is the Machines page's.const enroll = () => {devices.startEnroll();- void navigate({ to: "/settings/devices" });+ void navigate({ to: "/machines" });};return (<div role="status" data-shell-devices-banner={banner.tone} className="flex shrink-0 items-center gap-2 bg-muted/60 px-4 py-1.5 text-xs">diff --git a/apps/cua-spaces-web/src/components/shell/sidebar.tsx b/apps/cua-spaces-web/src/components/shell/sidebar.tsxindex 1566a9bb5f..1aaaad1c92 100644--- a/apps/cua-spaces-web/src/components/shell/sidebar.tsx+++ b/apps/cua-spaces-web/src/components/shell/sidebar.tsx@@ -23,6 +23,7 @@ import { SignInLink } from "@/components/sign-in-link";import { useNavItems } from "./nav";import { SidebarUpdateButton } from "./update-indicator";import { SidebarTip } from "@/components/tips";+import { useMachinesAccount } from "@/components/machines/account-parts";import { AccountLine, ProBanner } from "./account-area";export function Sidebar() {@@ -34,6 +35,8 @@ export function Sidebar() {// Spaces known so far.const { counted } = useListedSpaces(spaces);const spacesCount = spaces && listStatus.loaded ? counted.length : undefined;+ // Machines waiting to be added show beside the item, so they are seen from every page.+ const { pending } = useMachinesAccount();const counts: Partial<Record<string, number>> = { "/spaces": spacesCount, "/machines": machines?.length };const navItems = useNavItems();const unread = notifications.data?.unread ?? 0;@@ -68,6 +71,11 @@ export function Sidebar() {<span className="text-2xs font-medium tabular-nums text-foreground">{unread}</span></span>) : null}+ {item.to === "/machines" && pending.length > 0 ? (+ <span data-pending-badge className="rounded-full bg-warning/20 px-1.5 text-2xs font-medium tabular-nums text-foreground" aria-label={`${pending.length} waiting to be added`}>+ {pending.length}+ </span>+ ) : null}{counts[item.to] !== undefined ? (<span className="text-2xs tabular-nums text-muted-foreground group-hover:hidden">{counts[item.to]}</span>) : null}diff --git a/apps/cua-spaces-web/src/components/space-canvas.tsx b/apps/cua-spaces-web/src/components/space-canvas.tsxdeleted file mode 100644index 056e43055e..0000000000--- a/apps/cua-spaces-web/src/components/space-canvas.tsx+++ /dev/null@@ -1,38 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import type { ReactNode, Ref } from "react";--import { cn } from "@/lib/utils";--/** The gridded surface Space tiles draw on: under the Space's latest- * thumbnail (`spaces.thumbnail`) when the host has one, and its live video. */-export function SpaceCanvas({- dim,- className,- children,- ref,- streamState,-}: {- dim?: boolean;- className?: string;- children?: ReactNode;- ref?: Ref<HTMLDivElement>;- /** Live video over it (`data-stream-state`), when the host draws it. */- streamState?: string;-}) {- return (- <div- ref={ref}- data-stream-state={streamState}- className={cn(- "relative flex aspect-[16/10] items-center justify-center overflow-hidden rounded-lg bg-thumb",- "bg-[linear-gradient(var(--thumb-line)_1px,transparent_1px),linear-gradient(90deg,var(--thumb-line)_1px,transparent_1px)] bg-[size:24px_24px] bg-center",- dim && "opacity-70",- className,- )}- >- {children}- </div>- );-}diff --git a/apps/cua-spaces-web/src/components/space-thread/failure-note.tsx b/apps/cua-spaces-web/src/components/space-thread/failure-note.tsxindex 1546c31b03..6d7e7ddeae 100644--- a/apps/cua-spaces-web/src/components/space-thread/failure-note.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/failure-note.tsx@@ -2,10 +2,10 @@// Copyright (c) 2026 Cua AI, Inc.import { CheckIcon, ChevronRightIcon, CopyIcon, Loader2Icon, PlugIcon, RotateCcwIcon } from "lucide-react";-import { useState } from "react";+import { useEffect, useState } from "react";import { Link } from "@tanstack/react-router";-import type { ThreadFailure } from "@/bridge";+import { useAgentKeys, type ThreadFailure } from "@/bridge";import { Button } from "@/components/ui/button";import { useConnectors } from "@/hooks/use-connectors";import { cn } from "@/lib/utils";@@ -43,7 +43,7 @@ export function FailureNote({<div data-failure={failure.class} className="mt-1.5"><div className="flex flex-wrap items-center gap-2">{needsConnect ? <ConnectActions harness={harness} provider={failure.provider} taskText={taskText} onRetry={onRetry} /> : <RetryButton taskText={taskText} onRetry={failure.retryable ? onRetry : undefined} enabled />}- <Details message={failure.message} />+ <FailureDetails message={failure.message} /></div></div>);@@ -51,6 +51,12 @@ export function FailureNote({function ConnectActions({ harness, provider, taskText, onRetry }: { harness: string; provider: string | null; taskText: string | null; onRetry?: (text: string) => Promise<void> }) {const c = useConnectors();+ // The agent was refused its credential: Settings reads the saved list again, which says it needs a reconnect.+ const keys = useAgentKeys();+ useEffect(() => {+ void keys.refresh();+ // Once, when the failure appears.+ }, []); // eslint-disable-line react-hooks/exhaustive-depsconst app = failureApp(harness, provider);const connected = app ? c.view?.apps.find((a) => a.agent === app)?.state === "connected" : false;return (@@ -101,7 +107,7 @@ function RetryButton({ taskText, onRetry, enabled }: { taskText: string | null;}/** "Show details": the complete error, selectable, with Copy. */-function Details({ message }: { message: string }) {+export function FailureDetails({ message }: { message: string }) {const [open, setOpen] = useState(false);const [copied, setCopied] = useState(false);if (!message) return null;diff --git a/apps/cua-spaces-web/src/components/space-thread/live-row.tsx b/apps/cua-spaces-web/src/components/space-thread/live-row.tsxindex 6f1810d8e8..91d72be476 100644--- a/apps/cua-spaces-web/src/components/space-thread/live-row.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/live-row.tsx@@ -2,21 +2,37 @@// Copyright (c) 2026 Cua AI, Inc./**- * The live row at the bottom of the thread for each agent that is at work+ * What an agent that is at work shows at the bottom of the thread* (CUA-2640): "hermes-test is starting...", then the stage the run reports- * (installing, starting, thinking, using Bash). The daemon sends the stages- * with the thread's own follow, so a row shows as the stage changes; it is- * gone when the agent replies or fails (the failure is its own message).+ * (installing, starting, thinking, using Bash), and, once it has begun to+ * answer, what it has said so far as one live entry that the next snapshot+ * replaces whole (never appended to). Under it, "Working for 1m 05s": the+ * clock ticks by writing its own text node, so a second passing re-renders+ * nothing. The daemon sends all of it with the thread's own follow. The row+ * is gone when the agent replies or fails (the reply, or the failure, is+ * then its own message).*/+import { useEffect, useRef } from "react";+import type { LiveAgent } from "@/bridge";import { MemberAvatar } from "./avatar";import type { Roster } from "./roster";+import { ThreadText } from "./thread-view";/** `thinking` as "is thinking"; `using Bash` as "is using Bash". */export const stageSentence = (stage: string) => `is ${stage}`;+/** "12s", "1m 05s", "1h 02m": how long the agent has been at work. */+export function elapsedText(ms: number): string {+ const s = Math.max(0, Math.floor(ms / 1000));+ if (s < 60) return `${s}s`;+ const m = Math.floor(s / 60);+ if (m < 60) return `${m}m ${String(s % 60).padStart(2, "0")}s`;+ return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;+}+/** Three dots that pulse in turn (still, when the person asked for less motion). */function Dots() {return (@@ -28,6 +44,23 @@ function Dots() {);}+/** "Working for 1m 05s", ticking once a second by writing its text directly (no render per tick). */+export function WorkingFor({ sinceMs, now = Date.now }: { sinceMs: number | undefined; now?: () => number }) {+ const ref = useRef<HTMLSpanElement | null>(null);+ // Without the daemon's clock, from when this row first showed.+ const from = useRef(sinceMs ?? now());+ useEffect(() => {+ const start = sinceMs ?? from.current;+ const write = () => {+ if (ref.current) ref.current.textContent = `Working for ${elapsedText(now() - start)}`;+ };+ write();+ const t = setInterval(write, 1000);+ return () => clearInterval(t);+ }, [sinceMs, now]);+ return <span ref={ref} data-live-elapsed="" className="tabular-nums" />;+}+export function LiveRows({ live, roster }: { live: readonly LiveAgent[]; roster: Roster }) {if (!live.length) return null;return (@@ -35,13 +68,28 @@ export function LiveRows({ live, roster }: { live: readonly LiveAgent[]; roster:{live.map((a) => {const member = roster.agents.find((m) => m.handle === a.agent || m.name === a.agent);const label = member?.label ?? a.agent;+ const avatar = <MemberAvatar kind="agent" name={member?.handle ?? a.agent} harness={member?.harness ?? ""} identity={member?.identity} size={28} />;return (- <div key={a.agent} data-live-row={a.agent} data-live-stage={a.stage} role="status" className="flex items-center gap-3 py-2">- <MemberAvatar kind="agent" name={member?.handle ?? a.agent} harness={member?.harness ?? ""} identity={member?.identity} size={28} />- <p className="min-w-0 truncate text-[13px] text-muted-foreground">- <span className="font-medium text-foreground">{label}</span> {stageSentence(a.stage)}- <Dots />- </p>+ <div key={a.agent} data-live-row={a.agent} data-live-stage={a.stage} role="status" className="py-2">+ {a.text ? (+ // What it has said so far: one entry, replaced whole by each snapshot.+ <div data-live-entry={a.agent} className="mb-1 flex gap-3">+ <span className="mt-0.5 shrink-0">{avatar}</span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="truncate text-[13px] font-semibold">{label}</span>+ </div>+ <ThreadText text={a.text} handles={roster.handles} />+ </div>+ </div>+ ) : null}+ <div className="flex items-center gap-3">+ {a.text ? <span className="size-7 shrink-0" aria-hidden /> : <span className="shrink-0">{avatar}</span>}+ <p className="min-w-0 truncate text-[13px] text-muted-foreground">+ <span className="font-medium text-foreground">{label}</span> {stageSentence(a.stage)}+ <Dots /> <WorkingFor sinceMs={a.sinceMs} />+ </p>+ </div></div>);})}diff --git a/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx b/apps/cua-spaces-web/src/components/space-thread/members-panel.tsxindex dac49de0ac..3adab72055 100644--- a/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx@@ -12,6 +12,7 @@ import { Tooltip } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";import { MemberAvatar } from "./avatar";+import { FailureDetails } from "./failure-note";import { AiTag, OwnerSuffix } from "./identity";import { ProfileTrigger } from "./profile-card";import { RAIL_WINDOWS, railStreams } from "./rail";@@ -116,7 +117,7 @@ export function MembersPanel({</ProfileRow>))}{roster.agents.map((a) => (- <ProfileRow key={a.id} agent={a}>+ <ProfileRow key={a.id} agent={a} below={a.failure ? <FailureDetails message={a.failure.message} /> : undefined}><Rowmember={a.id}mark={<MemberAvatar kind="agent" name={a.name} harness={a.harness} identity={a.identity} surface="chrome" size={24} dim={a.dim} presence={presence?.[a.id] ?? null} />}@@ -268,9 +269,9 @@ function Row({{mark}<span className="min-w-0 flex-1"><span className={dim ? "block truncate text-[13px] text-muted-foreground" : "block truncate text-[13px]"}>{label}</span>- {/* A failed agent's reason is shown whole (wrapped, selectable), never cut with an ellipsis. */}+ {/* A failed agent says one word here ("Stopped", "Not connected"); its error is under Show details. */}{caption ? (- <span data-member-caption="" className={cn("block text-[11px] text-muted-foreground", status === "failed" ? "break-words select-text" : "truncate")}>+ <span data-member-caption="" className="block truncate text-[11px] text-muted-foreground">{caption}</span>) : null}@@ -303,12 +304,17 @@ function Row({}/** A row in "In this space" that opens its person's or agent's card. */-function ProfileRow({ person, agent, children }: { person?: RosterPerson; agent?: RosterAgent; children: ReactNode }) {+function ProfileRow({ person, agent, children, below }: { person?: RosterPerson; agent?: RosterAgent; children: ReactNode; /** Under the row, outside its card trigger (a failed agent's Show details). */ below?: ReactNode }) {return (<li><ProfileTrigger person={person} agent={agent} side="left" className="block w-full rounded-lg data-[selected]:bg-accent" rowKey={person?.id}>{children}</ProfileTrigger>+ {below ? (+ <div data-member-details="" className="flex flex-wrap items-center gap-1 pb-1 pl-[44px]">+ {below}+ </div>+ ) : null}</li>);}diff --git a/apps/cua-spaces-web/src/components/space-thread/profile-card.tsx b/apps/cua-spaces-web/src/components/space-thread/profile-card.tsxindex c050b19483..2320f0b18d 100644--- a/apps/cua-spaces-web/src/components/space-thread/profile-card.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/profile-card.tsx@@ -2,7 +2,7 @@// Copyright (c) 2026 Cua AI, Inc./**- * The card a person or an agent opens to in a Space (redesign): their name+ * The card a person or an agent opens to in a Space: their name* or avatar in the thread, an @mention, a row in "In this space". One calm* shape for both, like a chat app's profile card: who, their access or what* runs them, their status, the few actions that apply, and for an agent the@@ -409,7 +409,7 @@ function IdCopy({ value }: { value: string }) {/*** Opens the card of `person` or `agent` on click. Without a Space's scope- * (outside the redesigned Space page) a person has no card: the children+ * (outside the Space page) a person has no card: the children* draw as they are.*/export function ProfileTrigger({diff --git a/apps/cua-spaces-web/src/components/space-thread/queued.ts b/apps/cua-spaces-web/src/components/space-thread/queued.tsindex 632b02273f..5c81b46d5a 100644--- a/apps/cua-spaces-web/src/components/space-thread/queued.ts+++ b/apps/cua-spaces-web/src/components/space-thread/queued.ts@@ -82,7 +82,7 @@ export function useQueued(spaceId: string): Queued[] {/** Queued messages as thread items. */export const queuedItems = (qs: readonly Queued[], me: string, name: string): ThreadItem[] =>- qs.map((q, i) => ({ type: "message" as const, key: `queued:${q.id}`, entry: entryOf(q, i, me, name) }));+ qs.map((q, i) => ({ type: "message" as const, key: `queued:${q.id}`, entry: entryOf(q, i, me, name), quote: null, taskText: null }));/*** The thread of a Space still being made: empty (its queued messages arediff --git a/apps/cua-spaces-web/src/components/space-thread/roster.ts b/apps/cua-spaces-web/src/components/space-thread/roster.tsindex 8540491522..9519b71a6e 100644--- a/apps/cua-spaces-web/src/components/space-thread/roster.ts+++ b/apps/cua-spaces-web/src/components/space-thread/roster.ts@@ -8,7 +8,7 @@* names the composer's `@` picker offers.*/-import { DEFAULT_AGENT_RIGHTS, type AgentMember, type AgentRight, type AgentRights, type MemberIdentity, type ShareEntry, type ThreadAuthor, type ThreadEntry, type ThreadRole } from "@/bridge";+import { DEFAULT_AGENT_RIGHTS, type ThreadFailure, type AgentMember, type AgentRight, type AgentRights, type MemberIdentity, type ShareEntry, type ThreadAuthor, type ThreadEntry, type ThreadRole } from "@/bridge";import type { MentionCandidate } from "@/lib/mentions";export interface RosterAgent {@@ -34,6 +34,8 @@ export interface RosterAgent {collides: boolean;/** What the Space calls it (`@claude`); `name` is its key on this machine (`claude-2` in a second Space). */handle: string;+ /** Why it failed, typed, with the complete text (the member list says one word; Show details has the rest). */+ failure: ThreadFailure | null;}/** How an author shows in the thread. */@@ -145,6 +147,7 @@ export function buildRoster(input: {rights: m.rights ?? DEFAULT_AGENT_RIGHTS,youCan: m.youCan ?? { task: true, control: true, approve: true },identity: m.identity,+ failure: m.status === "failed" ? (m.failure ?? null) : null,collides: false,}));const colliding = collidingNames(agents);diff --git a/apps/cua-spaces-web/src/components/space-thread/summon.tsx b/apps/cua-spaces-web/src/components/space-thread/summon.tsxindex e2bdc8fe0b..fb2bcef3af 100644--- a/apps/cua-spaces-web/src/components/space-thread/summon.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/summon.tsx@@ -2,7 +2,7 @@// Copyright (c) 2026 Cua AI, Inc./**- * @mentioning agents in a Space (redesign): the composer's picker offers the+ * @mentioning agents in a Space: the composer's picker offers the* agents in the Space and those that can start in it; sending posts the* message, adds an @mentioned agent that isn't in the Space yet (asleep, so* the message wakes it), and, when one can't be woken, shows why under thediff --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 83bbc37ed7..6437c11a87 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@@ -4,7 +4,7 @@import { CheckIcon, FileTextIcon, ImageIcon, XIcon } from "lucide-react";import { Fragment, memo, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";-import { useBridge, type ThreadAttachment, type ThreadEntry, type ThreadItem, type ThreadView } from "@/bridge";+import { useBridge, type ThreadAttachment, type ThreadEntry, type ThreadItem, type ThreadQuote, type ThreadView } from "@/bridge";import { Inlines } from "@/components/markdown";import { Button } from "@/components/ui/button";import { parseInline } from "@/lib/markdown";@@ -144,9 +144,9 @@ export function ThreadView({<div className="flex h-full items-end px-8 pb-4">{empty}</div>) : (<div ref={body} 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) => (+ {items.map((item, i) => (<Fragment key={item.key}>- <ThreadItemView item={item} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRemoveAgent={onRemoveAgent} onRetry={onRetry} />+ <ThreadItemView item={item} above={aboveSeq(items, i)} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRemoveAgent={onRemoveAgent} onRetry={onRetry} />{after && "entry" in item ? after(item.entry.seq) : null}</Fragment>))}@@ -157,6 +157,16 @@ export function ThreadView({);}+/** The seq of the message drawn right above `items[i]` (notes and the unread divider are not messages). */+export function aboveSeq(items: readonly ThreadItem[], i: number): number | null {+ for (let j = i - 1; j >= 0; j--) {+ const it = items[j]!;+ if (it.type === "system" || it.type === "unread") continue;+ return it.entry.seq;+ }+ return null;+}+/** One folded thread item as the thread draws it; the Agents tab's DM draws the same, labelled with its Space. */export const ThreadItemView = memo(function Item({item,@@ -166,9 +176,12 @@ export const ThreadItemView = memo(function Item({onRemoveAgent,onRetry,label,+ above = null,}: {item: ThreadItem;roster: Roster;+ /** The seq of the entry drawn right above this one. */+ above?: number | null;onAnswer: (approval: number, approve: boolean) => Promise<void>;onOpenAttachment: (a: ThreadAttachment) => void;onRemoveAgent?: (handle: string) => Promise<void>;@@ -189,32 +202,18 @@ export const ThreadItemView = memo(function Item({// A join or a removal with who it was: drawn with its mark; anything else is its line of text.if (item.entry.event?.member) return <MemberEventNote event={item.entry.event} text={item.text} tsMs={item.entry.tsMs} />;return (- <p data-thread-note={item.entry.seq} className="my-1 truncate text-center text-xs text-muted-foreground">+ <p data-thread-note={item.entry.seq} className="my-1 text-center text-xs break-words text-muted-foreground">{item.text}</p>);case "message":- return <Message entry={item.entry} {...m} />;+ // One row, in order. A reply quotes the message it answers only when that is not the one right above it.+ return <Message entry={item.entry} {...m} quote={item.quote && item.quote.seq !== above ? item.quote : null} task={item.taskText !== null ? { text: item.taskText, onRetry } : undefined} />;case "task":+ // How the task is going is told by the chat: the live row, the agent's reply or its failure message. No chip here.return (<div data-task={item.entry.seq} data-task-state={item.state}>- {/* How the task is going is told by the chat: the live row, the agent's reply or its failure message. No chip here. */}<Message entry={item.entry} {...m} footnote={keysLine(item.entry, roster)} />- {item.replies.length || item.notes.length ? (- <div data-task-replies="" className="pl-10">- {[...item.notes.map((n) => ({ seq: n.entry.seq, note: n.text, entry: n.entry })), ...item.replies.map((r) => ({ seq: r.seq, note: null, entry: r }))]- .sort((a, b) => a.seq - b.seq)- .map((x) =>- x.note !== null ? (- <p key={x.seq} data-thread-note={x.seq} className="py-1 pl-10 text-xs text-muted-foreground">- {x.note}- </p>- ) : (- <Message key={x.seq} entry={x.entry} {...m} nested task={{ text: item.entry.text, onRetry }} />- ),- )}- </div>- ) : null}</div>);case "join_request":@@ -239,7 +238,7 @@ function Message({label,status,footnote,- nested,+ quote,task,surface = "background",}: {@@ -254,7 +253,8 @@ function Message({status?: ReactNode;/** A muted line under the text ("Runs on Ada's keys"). */footnote?: string | null;- nested?: boolean;+ /** The message this one replies to, when it is not the one right above. */+ quote?: ThreadQuote | null;/** The task this message replies to (its text, for a failed reply's Retry). */task?: { text: string; onRetry?: (text: string) => Promise<void> };}) {@@ -268,12 +268,12 @@ function Message({harness={who.harness}identity={who.identity}surface={surface}- size={nested ? 24 : 28}+ size={28}className="mt-0.5"/>);return (- <div data-entry={entry.seq} className={cn("flex gap-3", nested ? "py-1.5" : "py-2")}>+ <div data-entry={entry.seq} className="flex gap-3 py-2">{who.kind === "agent" && who.identity ? (<ProfileTrigger identity={who.identity} agent={who.agent} roster={roster} onRemove={onRemoveAgent} className="self-start rounded-full">{avatar}@@ -300,6 +300,7 @@ function Message({{label ? <span className="shrink-0">{label}</span> : null}{status ? <span className="shrink-0">{status}</span> : null}</div>+ {quote ? <ReplyQuote quote={quote} roster={roster} /> : null}{entry.text ? <ThreadText text={entry.text} handles={roster.handles} /> : null}{entry.failure ? <FailureNote failure={entry.failure} harness={who.harness ?? ""} taskText={task?.text ?? null} onRetry={task?.onRetry} /> : null}{entry.view ? <ViewLine view={entry.view} /> : null}@@ -320,6 +321,17 @@ function Message({);}+/** "Replying to Ada: ...": the message a reply answers, one quiet line (a preview of another message, not an error). */+function ReplyQuote({ quote, roster }: { quote: ThreadQuote; roster: Roster }) {+ const who = roster.author(quote.author);+ const text = quote.text.replace(/\s+/g, " ").trim();+ return (+ <p data-reply-quote={quote.seq} className="mb-0.5 truncate border-l-2 pl-2 text-[11.5px] text-muted-foreground">+ <span className="font-medium">{who.label}</span> {text}+ </p>+ );+}+/** What the person was looking at as they posted, one quiet line ("Sent from Firefox"); the core's words (`stream.viewLine`). */function ViewLine({ view }: { view: ThreadView }) {const { core } = useBridge();diff --git a/apps/cua-spaces-web/src/components/ui/toast.tsx b/apps/cua-spaces-web/src/components/ui/toast.tsxindex 9bea42f1bc..8d8000c10c 100644--- a/apps/cua-spaces-web/src/components/ui/toast.tsx+++ b/apps/cua-spaces-web/src/components/ui/toast.tsx@@ -2,8 +2,8 @@// Copyright (c) 2026 Cua AI, Inc.import { Toast } from "@base-ui/react/toast";-import { CircleAlertIcon, CircleCheckIcon, InfoIcon, XIcon } from "lucide-react";-import type { ReactNode } from "react";+import { CheckIcon, CircleAlertIcon, CircleCheckIcon, CopyIcon, InfoIcon, XIcon } from "lucide-react";+import { useState, type ReactNode } from "react";import { CuaKey } from "@/components/cua-key";@@ -83,6 +83,25 @@ export function ToastProvider({ children }: { children: ReactNode }) {);}+/** Copies an error toast's complete text. */+function CopyError({ text }: { text: string }) {+ const [copied, setCopied] = useState(false);+ return (+ <button+ type="button"+ data-toast-copy=""+ className="mt-1.5 -ml-1 flex items-center gap-1 rounded-lg px-1 py-0.5 text-xs text-muted-foreground hover:text-foreground"+ onClick={() => {+ void navigator.clipboard?.writeText(text).catch(() => undefined);+ setCopied(true);+ setTimeout(() => setCopied(false), 1200);+ }}+ >+ {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />} {copied ? "Copied" : "Copy"}+ </button>+ );+}+function ToastList() {const { toasts } = Toast.useToastManager();return toasts.map((t) => {@@ -101,7 +120,9 @@ function ToastList() {)}<Toast.Content className="min-w-0 flex-1"><Toast.Title className="text-[13px] font-medium" />- <Toast.Description className="text-xs text-muted-foreground" />+ {/* An error is never cut: the whole text wraps (scrolls when very long), selects and copies. */}+ <Toast.Description className="max-h-40 overflow-y-auto text-xs break-words whitespace-pre-wrap text-muted-foreground select-text" />+ {t.type === "error" && typeof t.description === "string" && t.description ? <CopyError text={t.description} /> : null}{(t.data as { action?: ToastAction } | undefined)?.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 53bbb407bd..a3344afb02 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@@ -125,7 +125,7 @@ describe("WebCodecsSlots", () => {});it("says there is no video here when the shell can't stream, and opens no session", async () => {- const { desktop } = fakeDesktop(() => ({ ok: false, error: { message: "Live video needs cua on this computer.", code: "unsupported" } }));+ const { desktop } = fakeDesktop(() => ({ ok: false, error: { message: "Live video needs cua on this machine.", code: "unsupported" } }));const { last } = slotIn(desktop);await flush();expect(last()).toEqual({ phase: "failed", reason: NO_VIDEO_HERE, opening: true, focused: false });@@ -482,7 +482,7 @@ describe("<StreamSurface> in the Electron shell", () => {});it("keeps the plain placeholder when the shell has no video (no cua, sample data)", async () => {- electron(fakeDesktop(() => ({ ok: false, error: { message: "Live video needs cua on this computer.", code: "unsupported" } })).desktop);+ electron(fakeDesktop(() => ({ ok: false, error: { message: "Live video needs cua on this machine.", code: "unsupported" } })).desktop);const { container, findByText, queryByText } = mount();expect(await findByText("The desktop opens in its own window.")).toBeTruthy();expect(container.querySelector('[data-stream-state="placeholder"]')).toBeTruthy();diff --git a/apps/cua-spaces-web/src/components/volume/driver-card.tsx b/apps/cua-spaces-web/src/components/volume/driver-card.tsxindex 54abb04f74..a0c25ecca3 100644--- a/apps/cua-spaces-web/src/components/volume/driver-card.tsx+++ b/apps/cua-spaces-web/src/components/volume/driver-card.tsx@@ -101,7 +101,7 @@ export function DriverSettingsCard() {try {setSummaries(await setup.setUp(agents.map((a) => ({ id: a.agent, name: a.name }))));} catch (e) {- setError(isUnsupported(e) ? "Setting up cua-driver needs the Cua Spaces app on this computer." : e instanceof Error ? e.message : String(e));+ setError(isUnsupported(e) ? "Setting up cua-driver needs the Cua Spaces app on this machine." : e instanceof Error ? e.message : String(e));} finally {setBusy(false);}diff --git a/apps/cua-spaces-web/src/components/volume/use-agents-step.ts b/apps/cua-spaces-web/src/components/volume/use-agents-step.tsindex 44a57b4393..10e50c06bb 100644--- a/apps/cua-spaces-web/src/components/volume/use-agents-step.ts+++ b/apps/cua-spaces-web/src/components/volume/use-agents-step.ts@@ -96,7 +96,7 @@ export function useAgentsStep(active: boolean): AgentsStep {return { ...s, text: [detail, s.text].filter((t) => t && t !== "nothing to change").join(" · ") || s.text };}),);- if (driverMissing) setError("cua-driver needs the Cua Spaces app on this computer. Set it up later in Settings.");+ if (driverMissing) setError("cua-driver needs the Cua Spaces app on this machine. Set it up later in Settings.");} catch (e) {setError(e instanceof Error ? e.message : String(e));} finally {diff --git a/apps/cua-spaces-web/src/hooks/use-connectors.ts b/apps/cua-spaces-web/src/hooks/use-connectors.tsindex 0ead387b4a..a5357062c4 100644--- a/apps/cua-spaces-web/src/hooks/use-connectors.ts+++ b/apps/cua-spaces-web/src/hooks/use-connectors.ts@@ -2,7 +2,7 @@// Copyright (c) 2026 Cua AI, Inc./**- * Connect, as Settings → Connectors (redesign), an app's page, a Space's+ * Connect, as Settings → Connectors, an app's page, a Space's* "isn't connected yet" note and Ask first share it: one place that knows* which connects are running, what failed, and which provider sheet is* open. The steps and words are the core's (`connectors.*`); the hostdiff --git a/apps/cua-spaces-web/src/legacy/__tests__/add-machine-dialog.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/add-machine-dialog.test.tsxdeleted file mode 100644index 443ca11151..0000000000--- a/apps/cua-spaces-web/src/legacy/__tests__/add-machine-dialog.test.tsx+++ /dev/null@@ -1,309 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.-// Before the redesign: public's test for this page, run with `spaces_redesign` off-// (the drift guard that keeps the default UI working).--import { vi as __vi } from "vitest";-__vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");-import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it } from "vitest";--import { BridgeProvider, expiresInText, setFlagOverride, useMachines } from "@/bridge";-import { HostError, type DataAdapter } from "@/bridge/adapter";-import { createDemoAdapter, type DemoOptions } from "@/bridge/adapters/demo";-import { unavailableCore } from "@/bridge/core";-import { AddMachineDialog } from "@/legacy/components/add-machine-dialog";--afterEach(() => {- cleanup();- localStorage.clear();-});--/** The demo host, with some operations answered differently, recording the pairing calls. */-function host(options: DemoOptions = {}, override: Record<string, (args: Record<string, unknown>) => Promise<unknown>> = {}) {- const base = createDemoAdapter({ latencyMs: 0, stepMs: 0, signedIn: true, onboarded: true, ...options });- const calls: string[] = [];- const adapter = Object.assign(Object.create(base) as DataAdapter, {- call: ((op: string, args: Record<string, unknown>) => {- if (op.startsWith("devices.") && op.includes("airing")) calls.push(op);- const f = override[op];- if (f) return f(args);- return (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args);- }) as DataAdapter["call"],- });- return { adapter, calls };-}--function Harness({ team = null }: { team?: string | null }) {- const { data: machines = [], setupGuide } = useMachines();- return (- <>- <ul aria-label="Computers">- {machines.map((m) => (- <li key={m.id}>{m.name}</li>- ))}- </ul>- <AddMachineDialog open onOpenChange={() => {}} guide={setupGuide} pollMs={20} team={team} />- </>- );-}--async function mount(adapter: DataAdapter, team: string | null = null, withCards = false) {- const none = unavailableCore("test: no core");- // The core's `upsell.card`, as one fixed card per reason.- const core = withCards- ? {- ...none,- tryCall: (<T,>(method: string, args: Record<string, unknown> = {}) =>- method === "upsell.card"- ? ({ reason: args.reason, title: "Your team is out of seats", body: "Add a seat.", price: "$30 a seat a month", cta: { label: "Add seats", url: "https://app.cua.ai/billing" }, dismiss: "Not now" } as T)- : undefined) as typeof none.tryCall,- }- : none;- render(- <BridgeProvider adapter={adapter} core={core}>- <Harness team={team} />- </BridgeProvider>,- );- await act(() => new Promise((r) => setTimeout(r, 10)));-}--const dialog = () => document.querySelector<HTMLElement>("[data-add-machine]")!;-const phase = () => dialog()?.getAttribute("data-add-machine");--describe("Add a computer by link or QR code", () => {- it("makes a link on opening: QR code, link, both commands and how long it lasts", async () => {- const { adapter, calls } = host();- await mount(adapter);- await waitFor(() => expect(phase()).toBe("ready"));- expect(calls[0]).toBe("devices.createPairingCode");- expect(document.querySelector("[data-pairing-qr] path")?.getAttribute("d")).toMatch(/^M\d/);- expect(screen.getByText(/^https:\/\/cua\.ai\/add\/K7QM-4XPB-/)).toBeTruthy();- expect(screen.getByText(/sh -s -- --pair K7QM-4XPB-/)).toBeTruthy();- // The bare code too, for Join with a code on a computer that has the app.- expect(document.querySelector("[data-pairing-code] code")?.textContent).toMatch(/^K7QM-4XPB-[0-9A-Z]{4}$/);- expect(screen.getByLabelText("Copy code")).toBeTruthy();- expect(screen.getByText("Waiting for the computer…")).toBeTruthy();- expect(document.querySelector("[data-pairing-expires]")?.textContent).toBe("Works once. Expires in 30 min");-- fireEvent.click(screen.getByText("Windows (preview)"));- await waitFor(() => expect(screen.getByText(/install\.ps1\)\)\) -Pair K7QM-4XPB-/)).toBeTruthy());- // The by-hand steps stay one click away.- expect(document.querySelector("details[data-manual-steps] summary")?.textContent?.trim()).toBe("Set it up by hand instead");- });-- it("waits for the other computer and says which one was added", async () => {- const { adapter, calls } = host();- await mount(adapter);- await waitFor(() => expect(phase()).toBe("used"), { timeout: 3000 });- expect(calls.filter((c) => c === "devices.pairingCodes").length).toBeGreaterThanOrEqual(3);- expect(document.querySelector("[data-pairing-added]")?.textContent).toMatch(/^Added Office PC\./);- // The machine list reads it again: the new computer is there.- // (The page behind the dialog is inert, so not by role.)- await waitFor(() => expect(document.querySelector('ul[aria-label="Computers"]')?.textContent).toContain("Office PC"));- expect(screen.queryByText("Revoke link")).toBeNull();- });-- it("adds the new machine to the team once it joined (pairing alone does not)", async () => {- const org = "0f1e2d3c-0000-4000-8000-000000000001";- const shared: Record<string, unknown>[] = [];- let finish: () => void = () => {};- const { adapter } = host({}, {- "sharing.share": (args) => {- shared.push(args);- // A plan bought a moment ago: the host is still retrying.- return new Promise((r) => (finish = () => r([])));- },- });- await mount(adapter, org);- await waitFor(() => expect(document.querySelector('[data-pairing-team="adding"]')?.textContent).toContain("Finishing setup…"), { timeout: 3000 });- expect(shared).toHaveLength(1);- expect(shared[0]).toMatchObject({ who: `team:${org}`, role: "editor" });- expect(String(shared[0]?.spaceId)).toMatch(/^relay:/);- finish();- await waitFor(() => expect(document.querySelector('[data-pairing-team="added"]')?.textContent).toMatch(/Your team can use it now\./));- });-- it("a team that never paid fails at once in words, with an Upgrade button for the owner", async () => {- const org = "0f1e2d3c-0000-4000-8000-000000000001";- const opened: unknown[] = [];- const { adapter } = host({}, {- "sharing.share": () => Promise.reject(new Error("Team computers need the Teams plan. https://app.cua.ai/buy/teams")),- "session.openExternal": (args) => {- opened.push(args.url);- return Promise.resolve(undefined);- },- });- await mount(adapter, org);- await waitFor(() => expect(document.querySelector('[data-pairing-team="failed"]')).toBeTruthy(), { timeout: 3000 });- const text = document.querySelector("[data-pairing-added]")?.textContent ?? "";- expect(text).toContain("It isn't on your team yet. Team computers need the Teams plan.");- expect(text).not.toContain("HTTP 402");- expect(text).not.toContain("https://");- fireEvent.click(document.querySelector("[data-pairing-upgrade]")!);- await waitFor(() => expect(opened).toEqual(["https://app.cua.ai/buy/teams"]));- });-- it("a member is told to ask the owner, and a raw plan error from an older host is reworded", async () => {- const { adapter } = host({}, {- "sharing.share": () => Promise.reject(new Error("Spaces API: HTTP 402 (feature_required: team_machines)")),- });- await mount(adapter, "0f1e2d3c-0000-4000-8000-000000000001");- await waitFor(() => expect(document.querySelector('[data-pairing-team="failed"]')).toBeTruthy(), { timeout: 3000 });- const text = document.querySelector("[data-pairing-added]")?.textContent ?? "";- expect(text).toContain("Ask the team owner to upgrade.");- expect(text).not.toContain("feature_required");- expect(document.querySelector("[data-pairing-upgrade]")).toBeNull();- });-- it("lets you choose the team, the current one by default, and adds the machine to it", async () => {- const acme = "0f1e2d3c-0000-4000-8000-0000000000a1";- const shared: Record<string, unknown>[] = [];- const { adapter } = host({}, {- "teams.list": () =>- Promise.resolve({- teams: [- { id: acme, alias: "acme", name: "Acme", role: "owner", plan: "teams" },- { id: "0f1e2d3c-0000-4000-8000-0000000000b2", alias: "side", name: "", role: "member", plan: "teams" },- ],- currentTeamId: acme,- }),- "sharing.share": (args) => {- shared.push(args);- return Promise.resolve([]);- },- });- await mount(adapter);- // Offered: just me, or Acme (the member-only team is not); Acme is the current team.- await waitFor(() => expect(document.querySelector("[data-add-machine-team]")?.getAttribute("data-add-machine-team")).toBe(acme));- await waitFor(() => expect(document.querySelector('[data-pairing-team="added"]')).toBeTruthy(), { timeout: 3000 });- expect(shared[0]).toMatchObject({ who: `team:${acme}` });- });-- it("adds the machine to no team when there is none to choose", async () => {- const shared: unknown[] = [];- const { adapter } = host({}, {- "teams.list": () => Promise.resolve({ teams: [], currentTeamId: null }),- "sharing.share": (args) => {- shared.push(args);- return Promise.resolve([]);- },- });- await mount(adapter);- await waitFor(() => expect(phase()).toBe("used"), { timeout: 3000 });- expect(document.querySelector("[data-add-machine-team]")).toBeNull();- expect(shared).toHaveLength(0);- });-- it("says when the machine could not join the team", async () => {- const { adapter } = host({}, {- "sharing.share": () => Promise.reject(new Error("Teams are not available on this server yet. Try again later, or update Cua.")),- });- await mount(adapter, "acme");- await waitFor(() => expect(document.querySelector('[data-pairing-team="failed"]')?.textContent).toMatch(/isn't on your team yet. Teams are not available/), { timeout: 3000 });- });-- it("revokes the link, then makes a new one", async () => {- const { adapter, calls } = host();- await mount(adapter);- await waitFor(() => expect(phase()).toBe("ready"));- fireEvent.click(screen.getByText("Revoke link"));- await waitFor(() => expect(phase()).toBe("revoked"));- expect(calls).toContain("devices.revokePairingCode");- expect(screen.getByText(/This link was revoked/)).toBeTruthy();- fireEvent.click(screen.getByText("Make a new link"));- await waitFor(() => expect(phase()).toBe("ready"));- expect(calls.filter((c) => c === "devices.createPairingCode")).toHaveLength(2);- });-- it("says when the link expired and offers a new one", async () => {- // A code the relay made 31 minutes ago (30 minutes is its life).- const { adapter } = host({ now: () => Date.now() - 31 * 60_000 });- await mount(adapter);- await waitFor(() => expect(phase()).toBe("expired"));- expect(screen.getByText("This link expired.")).toBeTruthy();- expect(screen.getByText("Make a new link")).toBeTruthy();- });-- it("shows that it is making the link", async () => {- const { adapter } = host({}, { "devices.createPairingCode": () => new Promise(() => {}) });- await mount(adapter);- await waitFor(() => expect(phase()).toBe("minting"));- expect(screen.getByText("Making a link…")).toBeTruthy();- });-- it("falls back to the steps by hand when the relay can't make links", async () => {- const { adapter } = host({}, { "devices.createPairingCode": () => Promise.reject(new HostError("relay: 404 Not Found", "failed")) });- await mount(adapter);- await waitFor(() => expect(phase()).toBe("error"));- expect(screen.getByText(/Your Cua relay can't make links yet/)).toBeTruthy();- expect(document.querySelector("[data-manual-steps]")?.tagName).toBe("DIV");- expect(screen.getByText("Install Cua Spaces on the other computer")).toBeTruthy();- });-- it("says what failed otherwise, and tries again", async () => {- let fail = true;- const { adapter, calls } = host({}, {});- const base = adapter.call.bind(adapter);- const flaky = Object.assign(Object.create(adapter) as DataAdapter, {- call: ((op: string, args: never) =>- op === "devices.createPairingCode" && fail ? Promise.reject(new Error("not found: relay: no such device")) : base(op as never, args)) as DataAdapter["call"],- });- await mount(flaky);- await waitFor(() => expect(phase()).toBe("error"));- expect(screen.getByText(/This machine isn't set up for access yet\. Set it up first, then add machines\./)).toBeTruthy();- expect(document.body.textContent).not.toMatch(/relay: no such device|not found:/);- fail = false;- fireEvent.click(screen.getByText("Try again"));- await waitFor(() => expect(phase()).toBe("ready"));- expect(calls).toContain("devices.createPairingCode");- });-- it("asks to sign in when signed out, and makes no link", async () => {- const { adapter, calls } = host({ signedIn: false });- await mount(adapter);- expect(screen.getByText(/Sign in to add a computer with a link/)).toBeTruthy();- expect(screen.getByText("Sign in")).toBeTruthy();- expect(document.querySelector("[data-manual-steps]")?.tagName).toBe("DIV");- expect(calls).toEqual([]);- });-- it("makes no link on a device that is not enrolled", async () => {- const notice = { kind: "needs-enrollment", status: "Needs enrollment", text: "Enroll this Mac to open your computers.", actionLabel: "Enroll This Mac…" };- const { adapter, calls } = host(- {},- {- "machines.list": async () => {- const rows = (await createDemoAdapter({ latencyMs: 0 }).call("machines.list", {})) as { current?: boolean }[];- return rows.map((r) => (r.current ? { ...r, accessNotice: notice } : r));- },- },- );- await mount(adapter);- await waitFor(() => expect(screen.getByText(/Enroll this Mac to open your computers\. Set the computer up by hand instead\./)).toBeTruthy());- expect(calls).toEqual([]);- });-});--describe("expiresInText", () => {- it("rounds minutes up, and counts seconds in the last minute", () => {- expect(expiresInText(1800, 0)).toBe("Expires in 30 min");- expect(expiresInText(1800, 1_000)).toBe("Expires in 30 min");- expect(expiresInText(100, 50_000)).toBe("Expires in 50 s");- expect(expiresInText(100, 200_000)).toBe("Expires in 0 s");- });-- it("with the upsell cards on, an owner out of seats gets the card, and a member does not", async () => {- setFlagOverride("upsell_cards", true);- const org = "0f1e2d3c-0000-4000-8000-000000000001";- const { adapter } = host({}, { "sharing.share": () => Promise.reject(new Error("Your team has no free seats. https://app.cua.ai/buy/teams")) });- await mount(adapter, org, true);- await waitFor(() => expect(document.querySelector('[data-upgrade-card="seats"]')).toBeTruthy(), { timeout: 3000 });- expect(document.querySelector("[data-pairing-upgrade]")).toBeNull();- cleanup();- const member = host({}, { "sharing.share": () => Promise.reject(new Error("Your team has no free seats. Ask the team owner to add seats.")) });- await mount(member.adapter, org, true);- await waitFor(() => expect(document.querySelector('[data-pairing-team="failed"]')).toBeTruthy(), { timeout: 3000 });- expect(document.querySelector("[data-upgrade-card]")).toBeNull();- });-});diff --git a/apps/cua-spaces-web/src/legacy/__tests__/agents-detail-tabs.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/agents-detail-tabs.test.tsxdeleted file mode 100644index 45309d7fd2..0000000000--- a/apps/cua-spaces-web/src/legacy/__tests__/agents-detail-tabs.test.tsx+++ /dev/null@@ -1,57 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.-// Before the redesign: public's test for this page, run with `spaces_redesign` off-// (the drift guard that keeps the default UI working).--// The Agents page's persistent-agent detail, as the SwiftUI app's: the run's-// conversation, then the core's Memory, Routines and "Access to this-// computer" tabs (the access audit under Access).--import { vi as __vi } from "vitest";-__vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");-import { cleanup, fireEvent, waitFor, within } from "@testing-library/react";-import { afterEach, describe, expect, it } from "vitest";-import { wasmBuilt } from "@/bridge/__tests__/testCore";-import { mountApp, stubBrowserApis } from "@/__tests__/app-harness";--afterEach(cleanup);-stubBrowserApis();--const tab = (name: string) => document.querySelector<HTMLElement>(`[data-agent-tab="${name}"]`);-const panel = (name: string) => document.querySelector<HTMLElement>(`[data-agent-panel="${name}"]`);--describe.skipIf(!wasmBuilt)("Agents, a persistent agent's detail", () => {- it("shows Memory, adds a routine and lists Access with its audit", { timeout: 20_000 }, async () => {- await mountApp("/agents?agent=ada", { failsCreates: false, listsGhost: false });- await waitFor(() => expect(tab("memory")).not.toBeNull(), { timeout: 8000 });- expect([...document.querySelectorAll("[data-agent-tab]")].map((t) => t.textContent)).toEqual(["Conversation", "Memory", "Routines", "Access to this machine"]);- expect(tab("run")!.getAttribute("aria-selected")).toBe("true");-- fireEvent.click(tab("memory")!);- await waitFor(() => expect(within(panel("memory")!).getByText("notes/review-checklist.md")).toBeTruthy());- fireEvent.click(within(panel("memory")!).getByText("MEMORY.md"));- await waitFor(() => expect(panel("memory")!.querySelector("[data-agent-file-text]")?.textContent).toContain("light and dark"));- expect(within(panel("memory")!).getAllByRole("button", { name: "Restore" })).toHaveLength(2);- fireEvent.click(within(panel("memory")!).getByRole("button", { name: "Close" }));-- fireEvent.click(tab("routines")!);- const routines = await waitFor(() => panel("routines")!);- expect(within(routines).getByText("Morning design notes")).toBeTruthy();- expect(within(routines).getByText("Every day at 9:00 AM")).toBeTruthy();- const add = within(routines).getByRole("button", { name: "Add routine" }) as HTMLButtonElement;- expect(add.disabled).toBe(true);- fireEvent.change(routines.querySelector("[data-routine-title]")!, { target: { value: "Inbox" } });- fireEvent.change(routines.querySelector("[data-routine-prompt]")!, { target: { value: "Sort my inbox" } });- await waitFor(() => expect(add.disabled).toBe(false));- fireEvent.click(add);- await waitFor(() => expect(within(panel("routines")!).getByText("Inbox")).toBeTruthy());- expect(within(panel("routines")!).getByText("Every day at 8:00 AM")).toBeTruthy();-- fireEvent.click(tab("access")!);- const access = await waitFor(() => panel("access")!);- expect(within(access).getByText("This machine")).toBeTruthy();- expect(within(access).getByRole("button", { name: "Revoke" })).toBeTruthy();- expect(within(access).getByText("Audit")).toBeTruthy();- expect(within(access).getByText("Used relay:this-mac")).toBeTruthy();- });-});diff --git a/apps/cua-spaces-web/src/legacy/__tests__/agents-page.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/agents-page.test.tsxdeleted file mode 100644index 65f9031b5e..0000000000--- a/apps/cua-spaces-web/src/legacy/__tests__/agents-page.test.tsx+++ /dev/null@@ -1,82 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.-// Before the redesign: public's test for this page, run with `spaces_redesign` off-// (the drift guard that keeps the default UI working).--// The Agents page: always-on agents under Running, recent runs with Watch or-// Replay, a run that needs the person, and the empty page by what is true-// on this computer.--import { vi as __vi } from "vitest";-__vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");-import { cleanup, fireEvent, waitFor, within } from "@testing-library/react";-import { afterEach, describe, expect, it } from "vitest";-import { wasmBuilt } from "@/bridge/__tests__/testCore";-import { mountApp, stubBrowserApis } from "@/__tests__/app-harness";--afterEach(cleanup);-stubBrowserApis();--const section = (id: string) => document.querySelector<HTMLElement>(`[data-agents-section="${id}"]`);-const noRuns = (op: string) => (op === "agents.list" || op === "agents.runs" ? [] : undefined);-const host = { failsCreates: false, listsGhost: false } as const;--describe.skipIf(!wasmBuilt)("Agents page", () => {- it("shows always-on agents under Running and the runs below, without a Connect button", { timeout: 20_000 }, async () => {- await mountApp("/agents", host);- await waitFor(() => expect(section("running")).not.toBeNull(), { timeout: 8000 });- expect(within(section("running")!).getByText("ada")).toBeTruthy();- expect(document.querySelector("[data-agent-view]")).toBeNull();- expect(section("running")!.compareDocumentPosition(section("runs")!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();- expect(document.body.textContent).not.toContain("Connect an agent");- expect(document.querySelector("[data-connected-apps-link]")).not.toBeNull();- const buttons = [...section("runs")!.querySelectorAll("[data-run-open]")].map((b) => b.textContent);- expect(buttons).toContain("Watch");- expect(buttons).toContain("Replay");- });-- it("offers Open Space for a run that needs you, in its own section", { timeout: 20_000 }, async () => {- await mountApp("/agents", host);- await waitFor(() => expect(section("waiting")).not.toBeNull(), { timeout: 8000 });- expect(within(section("waiting")!).getByText("OpenClaw needs you to sign in to GitHub")).toBeTruthy();- expect(within(section("waiting")!).getByRole("button", { name: "Open Space" })).toBeTruthy();- // No reply to a waiting agent from the app yet: nothing else to press.- expect(within(section("waiting")!).getAllByRole("button")).toHaveLength(1);- });-- it("opens a run and goes back to the overview", { timeout: 20_000 }, async () => {- await mountApp("/agents", host);- await waitFor(() => expect(section("runs")).not.toBeNull(), { timeout: 8000 });- fireEvent.click(section("runs")!.querySelector("[data-run-open]")!);- await waitFor(() => expect(document.querySelector("[data-agent-view]")).not.toBeNull());- fireEvent.click(document.querySelector("[data-agents-back]")!);- await waitFor(() => expect(section("runs")).not.toBeNull());- });-- it("Set up opens Connectors with the app in view when coding apps are found but Cua is not in them", { timeout: 20_000 }, async () => {- const { router } = await mountApp("/agents", { ...host, intercept: noRuns, demo: { agents: "unset" } });- await waitFor(() => expect(document.querySelector("[data-agents-empty]")).not.toBeNull(), { timeout: 8000 });- await waitFor(() => expect(document.querySelector("[data-agents-empty]")?.getAttribute("data-agents-empty")).toBe("setup"), { timeout: 8000 });- const setup = await waitFor(() => {- const b = document.querySelector("[data-agents-setup]");- expect(b).not.toBeNull();- return b!;- }, { timeout: 8000 });- fireEvent.click(setup);- // Cua connects an app only where the person says so: Connectors, not in place.- await waitFor(() => expect(router.state.location.pathname).toBe("/settings/connectors"), { timeout: 8000 });- expect(router.state.location.search).toHaveProperty("app");- });-- it("teaches the first prompts when Cua is already in the apps", { timeout: 20_000 }, async () => {- await mountApp("/agents", { ...host, intercept: noRuns });- await waitFor(() => expect(document.querySelector('[data-agents-empty="ready"]')).not.toBeNull(), { timeout: 8000 });- expect(document.querySelectorAll("[data-agent-prompt]")).toHaveLength(3);- });-- it("says no coding app was found", { timeout: 20_000 }, async () => {- await mountApp("/agents", { ...host, intercept: noRuns, demo: { agents: "none" } });- await waitFor(() => expect(document.querySelector('[data-agents-empty="none"]')).not.toBeNull(), { timeout: 8000 });- expect(document.querySelectorAll("[data-agent-prompt]")).toHaveLength(0);- });-});diff --git a/apps/cua-spaces-web/src/legacy/__tests__/first-space-ready.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/first-space-ready.test.tsxdeleted file mode 100644index 14a10886a8..0000000000--- a/apps/cua-spaces-web/src/legacy/__tests__/first-space-ready.test.tsx+++ /dev/null@@ -1,191 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.-// Before the redesign: public's test for this page, run with `spaces_redesign` off-// (the drift guard that keeps the default UI working).--import { vi as __vi } from "vitest";-__vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");-import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import type { ReactNode } from "react";--import type { AgentSetupRow, Space } from "@/bridge";-import { BridgeContext, type BridgeContextValue } from "@/bridge/BridgeProvider";-import { RunAgentDialog, runAgentPrompt } from "@/legacy/components/agents/run-agent-dialog";-import { suggestedTask, useFirstRunStep, useFirstSpaceMilestones } from "@/components/first-run-guide";-import { SpaceReadyCard, useAgentOffer } from "@/legacy/components/space-ready-card";-import { EXPLAINED_KEY, needsExplainer, TeleportExplainer } from "@/components/teleport/explainer";--const nav = vi.fn();-let rows: AgentSetupRow[] = [];-const configureAgents = vi.fn(async () => rows);--vi.mock("@tanstack/react-router", () => ({ useNavigate: () => nav }));-vi.mock("@/bridge", async (orig) => ({- ...(await orig<typeof import("@/bridge")>()),- useAgents: () => ({ agentSetup: async () => rows, configureAgents }),-}));--const space = { id: "s1", name: "Research" } as Space;-const row = (over: Partial<AgentSetupRow>): AgentSetupRow => ({ agent: "claude-code", name: "Claude Code", installed: true, configured: false, ...over }) as AgentSetupRow;--beforeEach(() => {- nav.mockReset();- configureAgents.mockClear();- localStorage.clear();-});-afterEach(cleanup);--describe("SpaceReadyCard", () => {- it("says the first Space is ready, names the agents found, and offers one real task", async () => {- rows = [row({}), row({ agent: "codex", name: "Codex", configured: true }), row({ agent: "hermes", name: "Hermes", installed: false })];- const onRun = vi.fn();- render(<SpaceReadyCard space={space} onRun={onRun} />);- expect(screen.getByRole("heading", { name: "Your first Space is ready" })).toBeTruthy();- expect(await screen.findByText(/We found Claude Code and Codex on this computer/)).toBeTruthy();- expect(screen.getByText("Run a project's tests on a clean Linux computer")).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "Try this task" }));- expect(onRun).toHaveBeenCalledOnce();- expect(onRun.mock.calls[0]![0].prompt).toMatch(/run its tests/);- expect(document.body.textContent).not.toMatch(/relay|MCP|\bhost\b|weather|flight|pizza/i);- });-- it("opens the Space", async () => {- rows = [];- render(<SpaceReadyCard space={space} onRun={() => {}} />);- fireEvent.click(await screen.findByRole("button", { name: "Open Research" }));- expect(nav).toHaveBeenCalledWith({ to: "/spaces/$spaceId", params: { spaceId: "s1" } });- });-- it("says how to connect when no agent is found, and can be closed", async () => {- rows = [];- const onDismiss = vi.fn();- render(<SpaceReadyCard space={space} onRun={() => {}} onDismiss={onDismiss} />);- expect(await screen.findByText(/Connect an agent such as Claude Code or Codex/)).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "Not now" }));- expect(onDismiss).toHaveBeenCalledOnce();- });-});--describe("the guided first run's events", () => {- const track = vi.fn();- const wrapper = ({ children }: { children?: ReactNode }) => {- const store = { telemetry: { track } };- const value = { mode: "electron", core: {}, adapter: null, store, ready: Promise.resolve(store) } as unknown as BridgeContextValue;- return <BridgeContext.Provider value={value}>{children}</BridgeContext.Provider>;- };- const events = () => track.mock.calls.map((c) => (c[0] as { feature: string }[])[0]!.feature);- const s = (status: string) => ({ id: "s1", name: "Research", os: "linux", status }) as unknown as Space;- beforeEach(() => track.mockClear());-- it("counts shown, created, ready and task started once each", async () => {- const step = renderHook(() => useFirstRunStep(), { wrapper }).result.current;- act(() => step("guide_shown"));- const m = renderHook(({ list }) => useFirstSpaceMilestones(list), { wrapper, initialProps: { list: [s("provisioning")] } });- m.rerender({ list: [s("running")] });- m.rerender({ list: [s("running")] });- act(() => step("task_started"));- act(() => step("task_started"));- await waitFor(() => expect(events()).toEqual(["first_run_guide_shown", "first_space_created", "first_space_ready", "suggested_task_started"]));- });-- it("does not count created or ready on an install that never showed the guide", async () => {- renderHook(() => useFirstSpaceMilestones([s("running")]), { wrapper });- await Promise.resolve();- expect(track).not.toHaveBeenCalled();- });-- it("suggests real work on a clean computer, for the Space's system", () => {- expect(suggestedTask({ ...s("running"), os: "macos" } as Space).title).toBe("Run a project's tests on a clean Mac");- expect(suggestedTask(s("running")).prompt).toContain('"Research"');- });-- it("the run dialog shows the suggested request", async () => {- rows = [row({ configured: true })];- const { prompt } = suggestedTask(s("running"));- render(<RunAgentDialog open space={space} onOpenChange={() => {}} prompt={prompt} />);- expect(await screen.findByText(prompt)).toBeTruthy();- });-});--describe("useAgentOffer", () => {- const track = vi.fn();- const wrapper = ({ children }: { children?: ReactNode }) => {- const store = { telemetry: { track } };- const value = { mode: "electron", core: {}, adapter: null, store, ready: Promise.resolve(store) } as unknown as BridgeContextValue;- return <BridgeContext.Provider value={value}>{children}</BridgeContext.Provider>;- };- const events = () => track.mock.calls.map((c) => (c[0] as { feature: string }[])[0]!.feature);- beforeEach(() => track.mockClear());-- it("records shown once, then clicked and completed, and never shows again", async () => {- const { result, rerender } = renderHook(() => useAgentOffer(true), { wrapper });- await waitFor(() => expect(events()).toEqual(["agent_offer_shown"]));- act(() => result.current.clicked());- act(() => result.current.completed());- await waitFor(() => expect(events()).toEqual(["agent_offer_shown", "agent_offer_clicked", "agent_offer_completed"]));- expect(result.current.visible).toBe(false);- rerender();- const again = renderHook(() => useAgentOffer(true), { wrapper });- expect(again.result.current.visible).toBe(false);- expect(events()).toHaveLength(3);- });-- it("stays closed after Not now, and counts shown once per install", async () => {- const first = renderHook(() => useAgentOffer(true), { wrapper });- await waitFor(() => expect(events()).toEqual(["agent_offer_shown"]));- act(() => first.result.current.dismiss());- expect(first.result.current.visible).toBe(false);- expect(renderHook(() => useAgentOffer(true), { wrapper }).result.current.visible).toBe(false);- expect(events()).toEqual(["agent_offer_shown"]);- });-- it("is hidden until a Space is ready", () => {- expect(renderHook(() => useAgentOffer(false), { wrapper }).result.current.visible).toBe(false);- expect(track).not.toHaveBeenCalled();- });-});--describe("RunAgentDialog", () => {- it("shows the request to paste when an agent is connected", async () => {- rows = [row({ configured: true })];- render(<RunAgentDialog open space={space} onOpenChange={() => {}} />);- expect((await screen.findByText(runAgentPrompt("Research"))).hasAttribute("data-run-agent-prompt")).toBe(true);- fireEvent.click(screen.getByRole("button", { name: "Copy and see Agents" }));- expect(nav).toHaveBeenCalledWith({ to: "/agents" });- });-- it("Connect opens Connectors with the agent in view (Cua connects only where the person says so)", async () => {- rows = [row({})];- const closed = vi.fn();- render(<RunAgentDialog open space={space} onOpenChange={closed} />);- fireEvent.click(await screen.findByRole("button", { name: "Connect Claude Code" }));- await waitFor(() => expect(nav).toHaveBeenCalledWith({ to: "/settings/connectors", search: { app: "claude-code" } }));- expect(closed).toHaveBeenCalledWith(false);- expect(configureAgents).not.toHaveBeenCalled();- });-- it("says so when no agent is installed", async () => {- rows = [];- render(<RunAgentDialog open space={space} onOpenChange={() => {}} onManual={() => {}} />);- expect(await screen.findByRole("button", { name: "Show me how" })).toBeTruthy();- });-});--describe("Teleport explainer", () => {- it("explains teleport and the Mac's permission prompt in plain words", () => {- render(<TeleportExplainer />);- const text = screen.getByText(/Your Mac will ask for permission/).closest("p")?.textContent ?? "";- expect(text).toMatch(/Keychain/);- expect(document.body.textContent).not.toMatch(/relay|MCP|\bhost\b|machine/i);- });-- it("shows once on a Mac, never elsewhere", () => {- const mac = vi.spyOn(globalThis.navigator, "platform", "get").mockReturnValue("MacIntel");- expect(needsExplainer()).toBe(true);- localStorage.setItem(EXPLAINED_KEY, "1");- expect(needsExplainer()).toBe(false);- mac.mockRestore();- });-});diff --git a/apps/cua-spaces-web/src/legacy/__tests__/join-with-code-dialog.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/join-with-code-dialog.test.tsxdeleted file mode 100644index 6ed5bcdc03..0000000000--- a/apps/cua-spaces-web/src/legacy/__tests__/join-with-code-dialog.test.tsx+++ /dev/null@@ -1,121 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.-// Before the redesign: public's test for this page, run with `spaces_redesign` off-// (the drift guard that keeps the default UI working).--import { vi as __vi } from "vitest";-__vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");-import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it } from "vitest";--import { BridgeProvider } from "@/bridge";-import { HostError, type DataAdapter } from "@/bridge/adapter";-import { createDemoAdapter } from "@/bridge/adapters/demo";-import { unavailableCore } from "@/bridge/core";-import { JoinWithCodeDialog } from "@/legacy/components/join-with-code-dialog";--afterEach(cleanup);--/** The demo host, recording `host.joinWithCode` and optionally answering it differently. */-function host(override?: (args: Record<string, unknown>) => Promise<unknown>) {- const base = createDemoAdapter({ latencyMs: 0, stepMs: 0, signedIn: true, onboarded: true });- const joins: Record<string, unknown>[] = [];- const adapter = Object.assign(Object.create(base) as DataAdapter, {- call: ((op: string, args: Record<string, unknown>) => {- if (op === "host.joinWithCode") {- joins.push(args);- if (override) return override(args);- }- return (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args);- }) as DataAdapter["call"],- });- return { adapter, joins };-}--async function mount(adapter: DataAdapter, props: { initialCode?: string; initialRelay?: string | null } = {}) {- render(- <BridgeProvider adapter={adapter} core={unavailableCore("test: no core")}>- <JoinWithCodeDialog open onOpenChange={() => {}} {...props} />- </BridgeProvider>,- );- await act(() => new Promise((r) => setTimeout(r, 10)));-}--const state = () => document.querySelector("[data-join-with-code]")?.getAttribute("data-join-with-code");-const field = () => screen.getByLabelText("Pairing code") as HTMLInputElement;-const join = () => screen.getByRole("button", { name: "Join" }) as HTMLButtonElement;--describe("Join with a code", () => {- it("keeps Join off until the text is a code, then joins with the canonical code", async () => {- const { adapter, joins } = host();- await mount(adapter);- expect(join().disabled).toBe(true);- fireEvent.change(field(), { target: { value: "k7qm-4xpb" } });- expect(join().disabled).toBe(true);- fireEvent.change(field(), { target: { value: "k7qm-4xpb-2rhd" } });- expect(join().disabled).toBe(false);- fireEvent.click(join());- await waitFor(() => expect(state()).toBe("joined"));- expect(joins).toEqual([{ code: "K7QM4XPB2RHD", relay: null }]);- expect(document.querySelector("[data-join-joined]")?.textContent).toContain("joined");- });-- it("fills a code that came from a link and waits for Join", async () => {- const { adapter, joins } = host();- await mount(adapter, { initialCode: "K7QM4XPB2RHD", initialRelay: "https://relay.example" });- expect(field().value).toBe("K7QM-4XPB-2RHD");- expect(document.querySelector("[data-join-relay]")?.textContent).toContain("https://relay.example");- expect(joins).toEqual([]);- fireEvent.click(join());- await waitFor(() => expect(state()).toBe("joined"));- expect(joins).toEqual([{ code: "K7QM4XPB2RHD", relay: "https://relay.example" }]);- });-- it("takes the relay from a pasted link", async () => {- const { adapter, joins } = host();- await mount(adapter);- fireEvent.change(field(), { target: { value: "https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Frelay.example" } });- fireEvent.click(join());- await waitFor(() => expect(state()).toBe("joined"));- expect(joins).toEqual([{ code: "K7QM4XPB2RHD", relay: "https://relay.example" }]);- });-- it("shows why a code failed and lets the person try again", async () => {- let n = 0;- const { adapter } = host(async () => {- if (n++ === 0) throw new HostError("this pairing code was already used", "failed");- return null;- });- await mount(adapter, { initialCode: "K7QM4XPB2RHD" });- fireEvent.click(join());- await waitFor(() => expect(state()).toBe("failed"));- expect(document.querySelector("[data-join-error]")?.textContent).toBe(- "That code didn't work. It may be used, expired or mistyped. Make a new one in Add a machine.",- );- expect(field().disabled).toBe(false);- fireEvent.click(join());- await waitFor(() => expect(state()).toBe("joined"));- });-- it("hides the command's internal prefixes", async () => {- const { adapter } = host(async () => {- throw new HostError("cua: unauthenticated: host setup failed at register: relay: pairing code is not valid; make a new one", "failed");- });- await mount(adapter, { initialCode: "K7QM4XPB2RHD" });- fireEvent.click(join());- await waitFor(() => expect(state()).toBe("failed"));- const text = document.querySelector("[data-join-error]")?.textContent ?? "";- expect(text).toContain("That code didn't work");- expect(text).not.toMatch(/unauthenticated|host setup failed|relay:/);- });-- it("says plainly when the host can't join with a code", async () => {- const { adapter } = host(async () => {- throw new HostError("no such method", "unsupported");- });- await mount(adapter, { initialCode: "K7QM4XPB2RHD" });- fireEvent.click(join());- await waitFor(() => expect(state()).toBe("failed"));- expect(document.querySelector("[data-join-error]")?.textContent).toContain("Update the app");- });-});diff --git a/apps/cua-spaces-web/src/legacy/__tests__/resources.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/resources.test.tsxdeleted file mode 100644index ae19945296..0000000000--- a/apps/cua-spaces-web/src/legacy/__tests__/resources.test.tsx+++ /dev/null@@ -1,177 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.-// Before the redesign: public's test for this page, run with `spaces_redesign` off-// (the drift guard that keeps the default UI working).--// Processor, memory and disk on Home and a Space's page (CUA-1880): the-// numbers' store, the strips, the low-disk warning and its "See what's-// using space" (real routes, wasm core, the demo host).--import { vi as __vi } from "vitest";-__vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");-import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";-import { BridgeProvider, HostError, RESOURCES_HIDDEN_MS, RESOURCES_VISIBLE_MS, useResources, type DataAdapter, type ResourcesSnapshot } from "@/bridge";-import { createDemoAdapter } from "@/bridge/adapters/demo";-import { DEMO_DISK_FREE, demoDiskWarning } from "@/bridge/adapters/demo/resources";-import { wasmBuilt } from "@/bridge/__tests__/testCore";-import { mountApp, stubBrowserApis } from "@/__tests__/app-harness";--afterEach(cleanup);-stubBrowserApis();--const lowDisk = (op: string, out: unknown) => {- if (op !== "resources.get" || !out) return out;- const snap = out as ResourcesSnapshot;- const warning = demoDiskWarning(DEMO_DISK_FREE.low, snap.thisMac.diskTotal);- return { ...snap, thisMac: { ...snap.thisMac, diskFree: DEMO_DISK_FREE.low, warning }, warning };-};--describe("the resources store", () => {- function Probe({ seen }: { seen: { snap?: ResourcesSnapshot | null } }) {- seen.snap = useResources();- return null;- }-- it("reads every 10 s while visible and every 5 minutes while hidden, saying which", async () => {- vi.useFakeTimers();- try {- const demo = createDemoAdapter({ latencyMs: 0 });- const calls: boolean[] = [];- const adapter: DataAdapter = { ...demo, call: (op, args) => (op === "resources.get" && calls.push((args as { visible: boolean }).visible), demo.call(op, args)) };- const seen: { snap?: ResourcesSnapshot | null } = {};- render(- <BridgeProvider adapter={adapter}>- <Probe seen={seen} />- </BridgeProvider>,- );- await act(() => vi.advanceTimersByTimeAsync(10));- expect(calls).toEqual([true]);- expect(seen.snap?.thisMac.id).toBe("this-mac");- await act(() => vi.advanceTimersByTimeAsync(RESOURCES_VISIBLE_MS));- expect(calls.length).toBe(2);- // Hidden: the slow pace, and the read says so.- Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true });- document.dispatchEvent(new Event("visibilitychange"));- await act(() => vi.advanceTimersByTimeAsync(RESOURCES_VISIBLE_MS * 3));- expect(calls.length).toBe(2);- await act(() => vi.advanceTimersByTimeAsync(RESOURCES_HIDDEN_MS));- expect(calls.at(-1)).toBe(false);- // Back: at once.- Object.defineProperty(document, "visibilityState", { value: "visible", configurable: true });- const before = calls.length;- document.dispatchEvent(new Event("visibilitychange"));- await act(() => vi.advanceTimersByTimeAsync(5));- expect(calls.length).toBe(before + 1);- expect(calls.at(-1)).toBe(true);- } finally {- Object.defineProperty(document, "visibilityState", { value: "visible", configurable: true });- vi.useRealTimers();- }- });-- it("a host without the operation reads as null, and is not asked again", async () => {- vi.useFakeTimers();- try {- const demo = createDemoAdapter({ latencyMs: 0 });- let asked = 0;- const adapter: DataAdapter = {- ...demo,- call: (op, args) => {- if (op !== "resources.get") return demo.call(op, args);- asked += 1;- return Promise.reject(new HostError("resources.get", "unimplemented"));- },- };- const seen: { snap?: ResourcesSnapshot | null } = {};- render(- <BridgeProvider adapter={adapter}>- <Probe seen={seen} />- </BridgeProvider>,- );- await act(() => vi.advanceTimersByTimeAsync(RESOURCES_VISIBLE_MS * 3));- expect(seen.snap).toBeNull();- expect(asked).toBe(1);- } finally {- vi.useRealTimers();- }- });-});--describe.skipIf(!wasmBuilt)("resources on Home and a Space's page", () => {- it("Home: no computer strips and no per-Space meters; nothing while there is room", async () => {- await mountApp("/spaces", { failsCreates: false, listsGhost: false });- await waitFor(() => expect(document.querySelector('[data-space-id="local:agent-sandbox"]')).not.toBeNull());- // Give the resources a moment to arrive: still nothing to say.- await act(() => new Promise((r) => setTimeout(r, 100)));- expect(document.querySelector("[data-computer-resources]")).toBeNull();- expect(document.querySelector("[data-computer-warnings]")).toBeNull();- expect(document.querySelector("[data-space-meters]")).toBeNull();- // A computer that is just offline is not a warning.- expect(document.body.textContent).not.toMatch(/is offline/);- });-- it("low disk: one quiet line for This Mac, and See what's using space lists the Spaces biggest first", async () => {- const { router } = await mountApp("/spaces", { failsCreates: false, listsGhost: false, answer: lowDisk });- const warning = await waitFor(() => {- const el = document.querySelector<HTMLElement>('[data-computer-warnings] [data-low-disk="low"]');- if (!el) throw new Error("no warning");- return el;- });- expect(warning.textContent).toMatch(/^Disk almost full on This Mac \(41 GB left\)/);- expect(document.querySelectorAll("[data-computer-warning]")).toHaveLength(1);- fireEvent.click(warning.querySelector("[data-see-space-use]")!);- await waitFor(() => expect(router.state.location.search).toEqual({ sort: "size" }));- await waitFor(() => expect(document.querySelector("[data-sorted-by-size]")).not.toBeNull());- const ids = Array.from(document.querySelectorAll("[data-space-id]")).map((t) => t.getAttribute("data-space-id"));- // Biggest first; your other computers' Spaces report their sizes too now, so only This Mac's order is fixed here.- expect(ids.filter((id) => id?.startsWith("local:"))).toEqual(["local:design-review", "local:agent-sandbox"]);- });-- it("a Space's page: given vs in use, how it fits on this Mac, and the warning", async () => {- await mountApp(`/spaces/${encodeURIComponent("local:design-review")}`, { failsCreates: false, listsGhost: false, answer: lowDisk });- const panel = await waitFor(() => {- const el = document.querySelector<HTMLElement>("[data-space-resources]");- if (!el) throw new Error("no panel");- return el;- });- const card = (label: string) => panel.querySelector(`[data-resource-card="${label}"]`)?.textContent ?? "";- expect(card("Processor")).toContain("Given 4 of this Mac’s 12 cores");- expect(card("Memory")).toContain("Given 8 GB of this Mac’s 64 GB");- // Its own data on this Mac, of the size it was given.- expect(card("Space for files")).toBe("Space for files19 of 80 GB");- // Title, number, the one "Given" line and the bar: no explanations, no footer.- expect(panel.textContent).not.toMatch(/Busy means|free for its apps|Uses about|Updates every|file names/);- const fit = panel.querySelector("[data-disk-fit]")!;- expect(fit.textContent).toContain("How it fits on this Mac");- expect(fit.querySelector('[data-disk-part="yours"]')?.textContent).toBe("Your own files and apps · 929 GB");- expect(fit.querySelector('[data-disk-part="space"]')?.textContent).toMatch(/ · 19 GB$/);- expect(fit.querySelector('[data-disk-part="others"]')?.textContent).toBe("Other Spaces · 6 GB");- // Each shared base once, with who shares it.- const bases = Array.from(fit.querySelectorAll('[data-disk-part="base"]')).map((b) => b.textContent);- expect(bases).toHaveLength(2);- expect(bases[0]).toMatch(/ image · 25 GB, only this Space uses it$/);- expect(bases[1]).toBe("linux 24.04 image · 4.1 GB, used by 1 Space");- expect(fit.querySelector('[data-disk-part="free"]')?.textContent).toBe("Free · 41 GB");- expect(fit.querySelector("[data-low-disk]")).not.toBeNull();- });-- it("a container's page: its own data with no fake total", async () => {- await mountApp(`/spaces/${encodeURIComponent("local:agent-sandbox")}`, { failsCreates: false, listsGhost: false, answer: lowDisk });- const panel = await waitFor(() => {- const el = document.querySelector<HTMLElement>("[data-space-resources]");- if (!el) throw new Error("no panel");- return el;- });- const files = panel.querySelector('[data-resource-card="Space for files"]')!;- expect(files.textContent).toBe("Space for files6 GB");- expect(files.querySelector("[data-bar-fill]")).toBeNull();- expect(panel.querySelector('[data-resource-card="Memory"]')?.textContent).toContain("Given 4 GB of this Mac’s 64 GB");- });-- it("another computer's Space shows its panel once that computer reports its numbers", async () => {- await mountApp(`/spaces/${encodeURIComponent("relay:mac-mini/qa-windows")}`, { failsCreates: false, listsGhost: false });- await waitFor(() => expect(document.querySelector("[data-detail-title]")).not.toBeNull());- await waitFor(() => expect(document.querySelector("[data-space-resources]")).not.toBeNull());- });-});diff --git a/apps/cua-spaces-web/src/legacy/__tests__/spaces-creating-elsewhere.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/spaces-creating-elsewhere.test.tsxdeleted file mode 100644index bc5b030755..0000000000--- a/apps/cua-spaces-web/src/legacy/__tests__/spaces-creating-elsewhere.test.tsx+++ /dev/null@@ -1,67 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.-// Before the redesign: public's test for this page, run with `spaces_redesign` off-// (the drift guard that keeps the default UI working).--// A Space another of your computers is creating (CUA-2349): the Mac mini-// publishes it through the relay, and this computer's Spaces page shows-// "Creating macOS on Mac mini… 40%" until it is ready.--import { vi as __vi } from "vitest";-__vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");-import { act, cleanup, screen, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it } from "vitest";--import { DEMO_CREATING_ELSEWHERE } from "@/bridge/adapters/demo";-import type { CreatingElsewhere } from "@/bridge/contracts/spaces";-import { creatingElsewhereLine } from "@/lib/spaces";-import { mountApp, stubBrowserApis } from "@/__tests__/app-harness";--stubBrowserApis();-afterEach(cleanup);--const WAIT = { timeout: 8000 };--const tile = () => document.querySelector("[data-creating-elsewhere]");--async function mount(creating: { current: CreatingElsewhere[] }, noSpaces = false) {- return mountApp("/spaces", { failsCreates: false, listsGhost: false, demo: { noSpaces }, creatingElsewhere: () => creating.current });-}--describe("a Space another computer is creating", { timeout: 30_000 }, () => {- it("shows under that computer's name with how far it got, and goes once it is done", async () => {- const creating = { current: [...DEMO_CREATING_ELSEWHERE] };- const { emit } = await mount(creating);- await waitFor(() => expect(tile()).not.toBeNull(), WAIT);- expect(tile()!.getAttribute("data-creating-elsewhere")).toBe("mac-mini");- expect(tile()!.textContent).toContain("browser-qa");- expect(tile()!.getAttribute("aria-label")).toBe("browser-qa: Creating macOS on Mac mini… 40%");- expect(screen.getByText("Creating macOS on Mac mini…")).toBeTruthy();- expect(tile()!.querySelector("[data-state-label]")!.textContent).toBe("40%");- // Nothing to open yet: not a link.- expect(tile()!.closest("a")).toBeNull();-- creating.current = [{ ...DEMO_CREATING_ELSEWHERE[0]!, phase: "booting", percent: 70 }];- act(() => emit({ type: "spaces.changed" }));- await waitFor(() => expect(tile()!.querySelector("[data-state-label]")!.textContent).toBe("70%"), WAIT);-- creating.current = [];- act(() => emit({ type: "spaces.changed" }));- await waitFor(() => expect(tile()).toBeNull(), WAIT);- });-- it("is not the empty home when this computer has no Space yet", async () => {- await mount({ current: [...DEMO_CREATING_ELSEWHERE] }, true);- await waitFor(() => expect(tile()).not.toBeNull(), WAIT);- expect(document.querySelector("[data-empty-home]")).toBeNull();- expect(screen.queryByText("No Spaces yet")).toBeNull();- });-});--describe("creatingElsewhereLine", () => {- it("says what, where and how far in plain words", () => {- expect(creatingElsewhereLine({ os: "macos", machineName: "Mac mini", percent: 40 })).toBe("Creating macOS on Mac mini… 40%");- expect(creatingElsewhereLine({ os: "linux", machineName: "Studio", percent: 99.6 })).toBe("Creating Linux on Studio… 100%");- expect(creatingElsewhereLine({ os: "", machineName: " ", percent: -3 })).toBe("Creating a Space on another computer… 0%");- });-});diff --git a/apps/cua-spaces-web/src/legacy/__tests__/spaces-filter.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/spaces-filter.test.tsxdeleted file mode 100644index edb3804b21..0000000000--- a/apps/cua-spaces-web/src/legacy/__tests__/spaces-filter.test.tsx+++ /dev/null@@ -1,92 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.-// Before the redesign: public's test for this page, run with `spaces_redesign` off-// (the drift guard that keeps the default UI working).--// 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 { vi as __vi } from "vitest";-__vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");-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 "@/__tests__/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/legacy/__tests__/spaces-list-incomplete.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/spaces-list-incomplete.test.tsxdeleted file mode 100644index 57ad096f3a..0000000000--- a/apps/cua-spaces-web/src/legacy/__tests__/spaces-list-incomplete.test.tsx+++ /dev/null@@ -1,99 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.-// Before the redesign: public's test for this page, run with `spaces_redesign` off-// (the drift guard that keeps the default UI working).--// The Spaces page while the list is not complete: right after an app update-// restarts the daemon, before the first read, or while the account's other-// computers are still answering. It shows what is known and one quiet line,-// never "Create your first Space"; that only comes for a complete list with-// no Space, in the grid's place under the warnings and the filters.--import { vi as __vi } from "vitest";-__vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");-import { act, cleanup, screen, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it } from "vitest";--import { listView } from "@/bridge";-import type { ListStatus } from "@/bridge/contracts/spaces";-import { noCore, testCore, wasmBuilt } from "@/bridge/__tests__/testCore";-import { mountApp, stubBrowserApis } from "@/__tests__/app-harness";--stubBrowserApis();-afterEach(cleanup);--/** The whole app mounts and settles first (`useQuiet`). */-const WAIT = { timeout: 8000 };--/** A host whose list status the test moves, with no Space or the demo's. */-async function mount(status: { current: ListStatus }, noSpaces: boolean) {- return mountApp("/spaces", {- failsCreates: false,- listsGhost: false,- demo: { noSpaces },- listStatus: () => status.current,- });-}--/** The empty state: the first-run home (with the core) or its plain stand-in. */-const emptyHome = () => document.querySelector("[data-empty-home]") ?? screen.queryByText("No Spaces yet")?.closest("div") ?? null;-const reaching = () => document.querySelector("[data-spaces-reaching]")?.textContent ?? null;-const spacesCount = () => document.querySelector('a[href="/spaces"]')?.textContent ?? "";--describe("the Spaces page while the list is incomplete", { timeout: 30_000 }, () => {- it("never shows the empty home before the first read or while computers answer", async () => {- const status = { current: { loaded: false, incomplete: false, reaching: 0, stale: false } };- const { emit } = await mount(status, true);- await waitFor(() => expect(reaching()).toBe("Loading Spaces…"), WAIT);- expect(emptyHome()).toBeNull();- expect(screen.getByText("Loading Spaces…", { selector: "p:not([data-spaces-reaching])" })).toBeTruthy();- // No count in the sidebar before the list was read (not "0").- expect(spacesCount()).not.toMatch(/0/);-- // This machine answered, 6 computers have not yet.- status.current = { loaded: true, incomplete: true, reaching: 6, stale: false };- act(() => emit({ type: "spaces.changed" }));- await waitFor(() => expect(reaching()).toBe("Reaching 6 machines…"), WAIT);- expect(emptyHome()).toBeNull();-- // Every computer answered and there is no Space: now it is empty.- status.current = { loaded: true, incomplete: false, reaching: 0, stale: false };- act(() => emit({ type: "spaces.changed" }));- await waitFor(() => expect(emptyHome()).not.toBeNull(), WAIT);- expect(reaching()).toBeNull();- });-- it("shows the Spaces known so far with the line under them", async () => {- const status = { current: { loaded: true, incomplete: true, reaching: 1, stale: false } };- await mount(status, false);- await waitFor(() => expect(reaching()).toBe("Reaching 1 machine…"), WAIT);- const grid = document.querySelector("ul.grid");- expect(grid?.children.length).toBeGreaterThan(0);- // The line follows the tiles, so they do not move when it goes.- expect(grid!.compareDocumentPosition(document.querySelector("[data-spaces-reaching]")!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();- expect(emptyHome()).toBeNull();- });-- it("puts the empty home in the grid's place, under the filters", async () => {- await mount({ current: { loaded: true, incomplete: false, reaching: 0, stale: false } }, true);- await waitFor(() => expect(emptyHome()).not.toBeNull(), WAIT);- const filters = document.querySelector('[aria-label="Filter by state"]')!;- expect(filters.compareDocumentPosition(emptyHome()!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();- });-});--describe("listView", () => {- // The core's decision, and the TypeScript stand-in without it, agree.- const cases: [ListStatus, number, { empty: boolean; reachingLine: string | null }][] = [- [{ loaded: false, incomplete: false, reaching: 0, stale: false }, 0, { empty: false, reachingLine: "Loading Spaces…" }],- [{ loaded: true, incomplete: true, reaching: 6, stale: false }, 0, { empty: false, reachingLine: "Reaching 6 machines…" }],- [{ loaded: true, incomplete: true, reaching: 1, stale: false }, 2, { empty: false, reachingLine: "Reaching 1 machine…" }],- [{ loaded: true, incomplete: true, reaching: 0, stale: false }, 0, { empty: false, reachingLine: "Reaching your machines…" }],- [{ loaded: true, incomplete: false, reaching: 0, stale: false }, 0, { empty: true, reachingLine: null }],- [{ loaded: true, incomplete: false, reaching: 0, stale: false }, 3, { empty: false, reachingLine: null }],- ];- it.each(cases)("%o with %i Spaces", async (status, count, want) => {- expect(listView(noCore, status, count)).toEqual(want);- if (wasmBuilt) expect(listView(await testCore(), status, count)).toEqual(want);- });-});diff --git a/apps/cua-spaces-web/src/legacy/components/add-machine-dialog.tsx b/apps/cua-spaces-web/src/legacy/components/add-machine-dialog.tsxdeleted file mode 100644index 107cce0617..0000000000--- a/apps/cua-spaces-web/src/legacy/components/add-machine-dialog.tsx+++ /dev/null@@ -1,388 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { CheckIcon, ChevronRightIcon, CopyIcon, ExternalLinkIcon, LoaderCircleIcon } from "lucide-react";-import { useEffect, useState, type ReactNode } from "react";-import { encode } from "uqr";--import { expiresInText, FINISHING_SETUP, teamName, useFlag, useMachines, useTeamChoices, usePairingCode, useSession, type HostFormField, type HostSetupGuide, type Machine, type PairingHook } from "@/bridge";-import { Button } from "@/components/ui/button";-import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";-import { Segmented } from "@/components/ui/segmented";-import { Select } from "@/components/ui/select";-import { toast } from "@/components/ui/toast";-import { UpgradeCard } from "@/components/upgrade-card";-import { cn } from "@/lib/utils";--/** Where Cua Spaces is downloaded (`teleport::flow::CUA_INSTALL_URL`). */-export const INSTALL_URL = "https://cua.ai/install";--/** What each setup choice means for the other machine (the core's toggle help, `host::panel`). */-const CHOICE_HELP: Record<string, string> = {- desktop: "Your devices can see and control its screen.",- spare: "Its screen stays private. Your devices create Spaces on it.",-};--type Shell = "sh" | "powershell";-const SHELLS = [- { value: "sh", label: "macOS / Linux" },- { value: "powershell", label: "Windows (preview)" },-] as const satisfies readonly { value: Shell; label: string }[];--/**- * "Add a machine". Signed in on an enrolled device, opening it makes a- * one-time link (and QR code, and install commands) that adds the other- * computer to the account, and waits until that computer uses it. Without- * one (signed out, not enrolled, a relay that can't make links), it explains- * setting the other computer up by hand, in the words that computer shows- * (the core's `host.panel` and `host.formView`).- */-export function AddMachineDialog({- open,- onOpenChange,- guide,- pollMs,- team = null,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;- guide: HostSetupGuide;- /** How often to ask whether the link was used (tests). */- pollMs?: number;- /** The team (organization id) chosen at first; default: the current team, when it can take machines. */- team?: string | null;-}) {- const { data: session, signIn } = useSession();- const { data: listed, refresh } = useMachines();- const machines = listed ?? [];- const signedIn = session?.signedIn ?? false;- // Signed in but not enrolled: this device can't vouch for a new machine- // (known once the machines are read).- const notice = machines.find((m) => m.current)?.accessNotice ?? null;- // Which team the new machine joins (none: just this account). The- // account's teams that can take machines, the current one first.- const choices = useTeamChoices(open && signedIn);- const [picked, setPicked] = useState<string | null | undefined>(undefined);- useEffect(() => {- if (!open) setPicked(undefined);- }, [open]);- const chosen = picked !== undefined ? picked : (team ?? choices.current);- const pairing = usePairingCode({ open, enabled: signedIn && listed !== undefined && !notice, pollMs, team: chosen, onUsed: () => void refresh().catch(() => {}) });- const fail = (title: string) => (e: unknown) => toast(title, { description: e instanceof Error ? e.message : String(e) });-- // Any reason there is no link: the manual steps are the way, so show them.- const manualOnly = !signedIn || Boolean(notice) || pairing.phase === "error";-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogPopup className="top-[8vh] w-[min(600px,calc(100vw-2rem))]" data-add-machine={pairing.phase}>- <div className="max-h-[84vh] overflow-y-auto px-6 pt-5 pb-4">- <DialogTitle className="text-[15px] font-semibold">Add a computer</DialogTitle>- <DialogDescription className="mt-1 text-[13px] text-muted-foreground">- {manualOnly- ? "Any Mac, Linux or Windows computer you own can run Spaces for you. You set it up on that computer, and it shows up here once it is online."- : "Open this link on the other computer, scan the code with its camera, or run the command in its terminal. It installs Cua and adds the computer to your account."}- </DialogDescription>-- {!signedIn ? (- <Notice>- <p>Sign in to add a computer with a link. You can also set it up by hand.</p>- <Button size="sm" className="mt-2" onClick={() => void signIn().catch(fail("Couldn't start sign-in"))}>- Sign in- </Button>- </Notice>- ) : notice ? (- <Notice>{notice.text || "This device isn't enrolled yet, so it can't make a link."} Set the computer up by hand instead.</Notice>- ) : pairing.phase === "error" ? (- <Notice>- {pairing.error?.unsupported- ? "Your Cua relay can't make links yet. Set the computer up by hand instead."- : `${pairing.error?.message ?? "Couldn't make a link."} Set the computer up by hand instead.`}- <Button variant="outline" size="sm" className="mt-2 flex" onClick={pairing.renew}>- Try again- </Button>- </Notice>- ) : (- <>- {choices.teams.length > 0 && pairing.phase !== "used" ? (- <div className="mt-4 flex items-center gap-2 text-[13px]" data-add-machine-team={chosen ?? "me"}>- <span className="text-muted-foreground">Add it for</span>- <Select- aria-label="Add it for"- className="h-8 min-w-40"- value={chosen ?? "me"}- options={[- { value: "me", label: "Just me" },- ...choices.teams.map((t) => ({ value: t.id, label: `${teamName(t)} (team)` })),- ]}- onValueChange={(v) => setPicked(v === "me" ? null : v)}- />- </div>- ) : null}- <PairingPanel pairing={pairing} machines={machines} />- </>- )}-- {pairing.phase === "used" ? null : <ManualSteps guide={guide} open={manualOnly} />}- </div>- <div className="flex justify-end gap-2 border-t px-6 py-3">- {pairing.phase === "ready" ? (- <Button variant="outline" onClick={() => void pairing.revoke().catch(fail("Couldn't revoke the link"))}>- Revoke link- </Button>- ) : null}- <Button onClick={() => onOpenChange(false)}>Done</Button>- </div>- </DialogPopup>- </Dialog>- );-}--function Notice({ children }: { children: ReactNode }) {- return <div className="mt-4 rounded-lg border bg-card px-3 py-2.5 text-[13px] text-muted-foreground">{children}</div>;-}--/** The link, its QR code, the commands, and how long it lasts. */-function PairingPanel({ pairing, machines }: { pairing: PairingHook; machines: Machine[] }) {- const cards = useFlag("upsell_cards");- const [shell, setShell] = useState<Shell>("sh");- const { openExternal } = useSession();- const { phase, code } = pairing;-- if (phase === "idle" || phase === "minting" || !code) {- return (- <div className="mt-5 flex items-center gap-2 text-[13px] text-muted-foreground" data-pairing-minting>- <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden /> Making a link…- </div>- );- }-- if (phase === "used") {- const name = machines.find((m) => m.id === code.machine)?.name;- const team = pairing.team;- if (team?.phase === "adding") {- return (- <div className="mt-5 flex items-center gap-2 text-[13px] text-muted-foreground" data-pairing-team="adding">- <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden /> {FINISHING_SETUP}- </div>- );- }- // Only a team owner gets the checkout link, so only an owner gets the card.- const failedText = team?.phase === "failed" ? (team.error ?? "") : "";- const cardReason = !team?.upgradeUrl ? null : /no free seats/.test(failedText) ? "seats" : /as many computers as it has seats/.test(failedText) ? "machines" : null;- const asCard = cards && cardReason !== null;- return (- <>- <div className="mt-5 flex items-center gap-2.5 rounded-lg border bg-card px-3 py-3 text-[13px]" data-pairing-added data-pairing-team={team?.phase}>- <CheckIcon className="size-4 shrink-0 text-success" aria-hidden />- <span className="min-w-0 flex-1">- {name ? `Added ${name}.` : "Added the computer."}{" "}- {team?.phase === "added"- ? "Your team can use it now."- : team?.phase === "failed"- ? `It isn't on your team yet. ${team.error ?? "Something went wrong."}`- : "It shows in your computers."}- </span>- {team?.phase === "failed" && team.upgradeUrl && !asCard ? (- <Button size="sm" data-pairing-upgrade="" onClick={() => void openExternal(team.upgradeUrl!).catch(() => {})}>- Upgrade- </Button>- ) : null}- </div>- {asCard ? <UpgradeCard reason={cardReason} className="mt-3" /> : null}- </>- );- }-- if (phase === "expired" || phase === "revoked") {- return (- <div className="mt-5 rounded-lg border bg-card px-3 py-3 text-[13px] text-muted-foreground" data-pairing-ended={phase}>- {phase === "expired" ? "This link expired." : "This link was revoked. It can't add a computer now."}- <Button size="sm" className="mt-2 flex" onClick={pairing.renew}>- Make a new link- </Button>- </div>- );- }-- const command = shell === "sh" ? code.installSh : code.installPowershell;- return (- <div className="mt-5" data-pairing-ready>- <div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-5">- {code.url ? <QrCode text={code.url} /> : null}- <div className="min-w-0 space-y-3">- <div>- <div className="mb-1 text-xs font-medium text-muted-foreground">Link</div>- {code.url ? <CopyField text={code.url} label="Copy link" /> : null}- </div>- {code.code ? (- <div data-pairing-code>- <div className="mb-1 text-xs font-medium text-muted-foreground">Code</div>- <CopyField text={code.code} label="Copy code" mono />- <p className="mt-1.5 text-xs text-muted-foreground">Already have Cua Spaces there? Open Computers, choose Join with a code and enter it.</p>- </div>- ) : null}- <div>- <Segmented aria-label="The other computer's system" value={shell} options={SHELLS} onValueChange={setShell} />- {command ? <CopyField text={command} label="Copy command" mono /> : null}- </div>- </div>- </div>- <div className="mt-4 flex items-center justify-between gap-3 text-xs text-muted-foreground">- <span className="flex items-center gap-2" data-pairing-waiting>- <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden /> Waiting for the computer…- </span>- <span className="tabular-nums" data-pairing-expires>- Works once. {expiresInText(code.expiresAt, pairing.now)}- </span>- </div>- </div>- );-}--/** One line to copy: the link, or a command. */-function CopyField({ text, label, mono }: { text: string; label: string; mono?: boolean }) {- const [copied, setCopied] = useState(false);- const copy = () => {- void navigator.clipboard?.writeText(text).then(- () => {- setCopied(true);- setTimeout(() => setCopied(false), 1200);- },- () => {},- );- };- return (- <div className="mt-1.5 flex items-center gap-1 rounded-lg border bg-muted/40 pl-3">- <code className={cn("min-w-0 flex-1 py-1.5 text-xs", mono ? "font-mono break-all" : "truncate font-sans")} title={text}>- {text}- </code>- <Button size="icon-sm" variant="ghost" aria-label={label} onClick={copy}>- {copied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}- </Button>- </div>- );-}--/** The link as a QR code, drawn here (nothing leaves the page). */-export function QrCode({ text, size = 148 }: { text: string; size?: number }) {- const qr = encode(text, { ecc: "M", border: 2 });- let d = "";- qr.data.forEach((row, y) =>- row.forEach((dark, x) => {- if (dark) d += `M${x} ${y}h1v1h-1z`;- }),- );- return (- <svg- role="img"- aria-label="QR code of the link"- data-pairing-qr- width={size}- height={size}- viewBox={`0 0 ${qr.size} ${qr.size}`}- shapeRendering="crispEdges"- className="rounded-lg border bg-white"- >- <path d={d} fill="#000" />- </svg>- );-}--/** The by-hand setup: install, sign in, set up for access. */-function ManualSteps({ guide, open }: { guide: HostSetupGuide; open: boolean }) {- const { data: session, openExternal } = useSession();- const identity = session?.identity;- const fail = (title: string) => (e: unknown) => toast(title, { description: e instanceof Error ? e.message : String(e) });- const fields = guide.form?.fields ?? [];- const basic = fields.filter((f) => !f.advanced);- const advanced = fields.filter((f) => f.advanced);-- const steps = (- <ol className="mt-4 space-y-5">- <Step n={1} title="Install Cua Spaces on the other computer">- <Button variant="outline" size="sm" className="mt-2" onClick={() => void openExternal(INSTALL_URL).catch(fail("Couldn't open the page"))}>- Open download page <ExternalLinkIcon />- </Button>- </Step>-- <Step n={2} title="Sign in with the same account">- <p>- Use {identity ? <span className="font-medium text-foreground">{identity}</span> : "the account you use here"}. Computers join the- account they are set up with.- </p>- </Step>-- <Step n={3} title="Open This computer and choose how to use it">- <ul className="mt-1 divide-y overflow-hidden rounded-lg border bg-card">- {guide.choices.map((c) => (- <li key={c.id} className="px-3 py-2">- <div className="text-[13px] text-foreground">{c.label}</div>- {CHOICE_HELP[c.id] ? <div className="text-xs">{CHOICE_HELP[c.id]}</div> : null}- </li>- ))}- </ul>- </Step>-- <Step n={4} title={guide.form ? `Fill in the form and press ${quote(submitLabel(guide.form.submitLabel))}` : "Set it up for access"}>- <p>It connects through the Cua relay, so you don't need to forward ports.</p>- {basic.length ? (- <dl className="mt-2 divide-y overflow-hidden rounded-lg border bg-card">- {basic.map((f) => (- <FieldRow key={f.id} field={f} />- ))}- {advanced.length ? <div className="bg-muted/40 px-3 py-1.5 text-xs font-medium">{guide.form?.advancedLabel ?? "Advanced"}</div> : null}- {advanced.map((f) => (- <FieldRow key={f.id} field={f} />- ))}- </dl>- ) : null}- </Step>-- <Step n={5} title="Grant permissions if it shares its desktop">- <p>On a Mac, This computer lists the System Settings panes to turn on, such as Screen Recording and Accessibility.</p>- </Step>- </ol>- );-- if (open) return <div data-manual-steps>{steps}</div>;- return (- <details className="group mt-5 border-t pt-3" data-manual-steps>- <summary className="flex cursor-default list-none items-center gap-1 text-[13px] text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden">- <ChevronRightIcon className="size-3.5 transition-transform group-open:rotate-90" aria-hidden /> Set it up by hand instead- </summary>- {steps}- </details>- );-}--function Step({ n, title, children }: { n: number; title: string; children: ReactNode }) {- return (- <li className="grid grid-cols-[24px_minmax(0,1fr)] gap-3">- <span className="flex size-6 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground tabular-nums">{n}</span>- <div className="pt-0.5 text-[13px] text-muted-foreground">- <h3 className="mb-1 font-medium text-foreground">{title}</h3>- {children}- </div>- </li>- );-}--/** One form field: its label, and what goes in it. */-function FieldRow({ field: f }: { field: HostFormField }) {- const value = f.choices?.length- ? f.choices.map((c, i) => (i ? c.label[0]!.toLowerCase() + c.label.slice(1) : c.label)).join(", or ")- : f.toggle- ? "Off unless you need it"- : (f.placeholder ?? f.value);- return (- <div className="flex items-baseline justify-between gap-4 px-3 py-2">- <dt className="shrink-0 text-[13px] text-foreground">{f.label}</dt>- <dd className="min-w-0 truncate text-right text-xs">{value}</dd>- </div>- );-}--const quote = (s: string) => `“${s}”`;-/** "Set up for access" (the label while idle). */-const submitLabel = (s: string) => s.replace(/…$/, "");diff --git a/apps/cua-spaces-web/src/legacy/components/agents/agents-empty.tsx b/apps/cua-spaces-web/src/legacy/components/agents/agents-empty.tsxdeleted file mode 100644index c6861f5b20..0000000000--- a/apps/cua-spaces-web/src/legacy/components/agents/agents-empty.tsx+++ /dev/null@@ -1,123 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { useNavigate } from "@tanstack/react-router";-import { CheckIcon, CopyIcon } from "lucide-react";-import { useEffect, useState } from "react";--import { useAgents, type AgentSetupRow } from "@/bridge";-import { Button } from "@/components/ui/button";--const MAIN_PROMPT = "Reproduce the crash from issue #4821 on a fresh Windows 11 Space and show me a recording.";-const MORE_PROMPTS = ["Run our tests on Ubuntu and macOS at the same time and tell me which ones fail.", "Check that the installer works on a clean Windows machine."];--/** "Claude Code, Codex and Cursor". */-export function nameList(names: string[]): string {- if (names.length <= 1) return names[0] ?? "";- return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;-}--/**- * The Agents page before any run. It says what to do next, by what is true- * on this computer: coding apps found but Cua not in them yet (one Set up- * button, asked once, in place); Cua already in them (the first prompts to- * try); or no coding app found.- */-export function AgentsEmpty() {- const { agentSetup } = useAgents();- const navigate = useNavigate();- const [rows, setRows] = useState<AgentSetupRow[] | null>(null);- const busy = false;-- useEffect(() => {- let live = true;- agentSetup().then(- (r) => live && setRows(r),- () => live && setRows([]),- );- return () => {- live = false;- };- // eslint-disable-next-line react-hooks/exhaustive-deps -- once per showing- }, []);-- if (rows === null) return <div className="min-h-64" />;- const installed = rows.filter((r) => r.installed);- const ready = installed.filter((r) => r.configured);- const todo = installed.filter((r) => !r.configured);- const state = installed.length === 0 ? "none" : ready.length === 0 ? "setup" : "ready";-- // Set up opens Connectors with the app in view: Cua connects an app only where the person says so.- const setUp = () => void navigate({ to: "/settings/connectors", search: { app: todo[0]?.agent } });-- return (- <div className="mx-auto flex w-full max-w-xl flex-col items-center pt-8 text-center" data-agents-empty={state}>- <img src="/cua-key-128.png" alt="" className="size-24" />- <h2 className="mt-6 text-[22px] font-semibold tracking-[-0.01em]">- {state === "ready" ? "Ask an agent to work in a Space" : state === "setup" ? "Your agents can't use Cua yet" : "No coding app found yet"}- </h2>- <p className="mt-3 text-[15px] leading-relaxed text-muted-foreground">- {state === "ready"- ? "Open Claude Code, Codex or Cursor and ask it for something that needs a clean computer. It makes the Space, works in it and shows you the result here."- : state === "setup"- ? `${nameList(todo.map((r) => r.name))} ${todo.length === 1 ? "is" : "are"} on this Mac. Let ${todo.length === 1 ? "it" : "them"} use Cua, then ask one to work in a Space.`- : "Install Claude Code, Codex or Cursor and Cua will notice. Spaces work without one."}- </p>- {state === "setup" ? (- <Button size="lg" className="mt-6" disabled={busy} onClick={setUp} data-agents-setup>- {busy ? "Setting up…" : "Set up"}- </Button>- ) : null}- {state !== "none" ? (- <>- <div className="mt-8 w-full">- {state === "setup" ? <p className="mb-3 text-[13px] text-muted-foreground">Then try</p> : null}- <CopyPrompt text={MAIN_PROMPT} large={state === "ready"} />- </div>- {state === "ready" ? (- <div className="mt-6 flex w-full flex-col gap-3">- <p className="text-[13px] text-muted-foreground">Or try</p>- {MORE_PROMPTS.map((p) => (- <CopyPrompt key={p} text={p} />- ))}- </div>- ) : null}- <p className="mt-8 max-w-sm text-[13px] text-muted-foreground">- {state === "ready" ? (- <>- {nameList(ready.map((r) => r.name))} can use Cua.{" "}- <button type="button" className="text-brand-strong hover:underline" onClick={() => void navigate({ to: "/settings/connectors", search: {} })}>- Manage- </button>- </>- ) : (- "Cua adds itself to each app's settings and leaves the rest alone. You can turn it off in Settings."- )}- </p>- </>- ) : null}- </div>- );-}--function CopyPrompt({ text, large }: { text: string; large?: boolean }) {- const [copied, setCopied] = useState(false);- return (- <div data-agent-prompt="" className="flex min-h-12 items-center gap-3 rounded-xl border bg-card px-4 py-3 text-left shadow-xs">- <p className={large ? "min-w-0 flex-1 text-[15px] leading-relaxed" : "min-w-0 flex-1 text-[13px] text-muted-foreground"}>{text}</p>- <Button- size="icon"- variant="ghost"- aria-label={copied ? "Copied" : "Copy this prompt"}- onClick={() => {- void navigator.clipboard?.writeText(text).then(() => {- setCopied(true);- setTimeout(() => setCopied(false), 1500);- });- }}- >- {copied ? <CheckIcon /> : <CopyIcon />}- </Button>- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/agents/run-agent-dialog.tsx b/apps/cua-spaces-web/src/legacy/components/agents/run-agent-dialog.tsxdeleted file mode 100644index b697dcda9b..0000000000--- a/apps/cua-spaces-web/src/legacy/components/agents/run-agent-dialog.tsx+++ /dev/null@@ -1,146 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { useNavigate } from "@tanstack/react-router";-import { CheckIcon, CopyIcon } from "lucide-react";-import { useEffect, useState } from "react";--import { useAgents, type AgentSetupRow, type Space } from "@/bridge";-import { Button } from "@/components/ui/button";-import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";--/** What to ask the agent: one request that works in a Space with nothing else set up. */-export const runAgentPrompt = (spaceName: string) => `Open the Cua Space "${spaceName}" and tell me what's on its screen.`;--/**- * "Run an agent here": the shortest way from a ready Space to an agent- * working in it. If a coding agent on this computer already works with Cua,- * it shows the one request to paste into it. If not, it sets one up here- * first (one button) and then shows the request. The agent's work shows up- * on the Agents page.- */-export function RunAgentDialog({ open, space, onOpenChange, onManual, onConnected, prompt: asked }: { open: boolean; space: Space; onOpenChange: (open: boolean) => void; onManual?: () => void; onConnected?: () => void; /** The request to show; the default only looks at the screen. */ prompt?: string }) {- const { agentSetup } = useAgents();- const navigate = useNavigate();- const [rows, setRows] = useState<AgentSetupRow[] | null>(null);- const busy = false;- const [copied, setCopied] = useState(false);-- useEffect(() => {- if (!open) return;- let live = true;- setRows(null);- agentSetup().then(- (r) => live && setRows(r),- () => live && setRows([]),- );- return () => {- live = false;- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [open]);-- const ready = (rows ?? []).filter((r) => r.configured);- const pending = (rows ?? []).filter((r) => r.installed && !r.configured);- const prompt = asked ?? runAgentPrompt(space.name);- const first = ready[0];- const toSet = pending[0];-- // Connect opens Connectors with the app in view: Cua connects an app only where the person says so.- const setUp = () => {- onOpenChange(false);- void navigate({ to: "/settings/connectors", search: { app: toSet?.agent } });- };- const copy = () => {- onConnected?.();- void navigator.clipboard?.writeText(prompt).then(() => {- setCopied(true);- setTimeout(() => setCopied(false), 1500);- });- };-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogPopup data-run-agent={rows === null ? "loading" : ready.length ? "ready" : "setup"} className="top-[12vh] w-[min(520px,calc(100vw-2rem))] bg-popover">- <div className="px-6 pt-5 pb-6">- <DialogTitle className="text-[15px] font-semibold">Run an agent in {space.name}</DialogTitle>- {rows === null ? (- <DialogDescription className="mt-3 text-[13px] text-muted-foreground">Looking for your agents…</DialogDescription>- ) : first ? (- <>- <DialogDescription className="mt-1.5 text-[13px] leading-relaxed text-muted-foreground">- {first.name} is connected. Open it, paste this, and watch it work in {space.name}.- </DialogDescription>- <div className="mt-4 flex items-start gap-2 rounded-lg border bg-muted/40 py-2 pr-1 pl-3">- <p className="min-w-0 flex-1 py-1 text-[13px] leading-relaxed" data-run-agent-prompt="">- {prompt}- </p>- <Button size="icon-sm" variant="ghost" aria-label="Copy" onClick={copy}>- {copied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}- </Button>- </div>- <p className="mt-3 text-xs text-muted-foreground">If {first.name} was already open, restart it first so it can see Cua.</p>- <div className="mt-5 flex justify-end gap-2">- <Button variant="outline" onClick={() => onOpenChange(false)}>- Close- </Button>- <Button- data-run-agent-watch=""- onClick={() => {- copy();- onOpenChange(false);- void navigate({ to: "/agents" });- }}- >- Copy and see Agents- </Button>- </div>- </>- ) : toSet ? (- <>- <DialogDescription className="mt-1.5 text-[13px] leading-relaxed text-muted-foreground">- To let an agent work in {space.name}, connect it to Cua first. This takes a few seconds and changes nothing else about {toSet.name}.- </DialogDescription>- <ul className="mt-4 divide-y rounded-lg border">- {pending.map((r) => (- <li key={r.agent} className="px-3 py-2 text-[13px]">- {r.name}- </li>- ))}- </ul>- <div className="mt-5 flex justify-end gap-2">- <Button variant="outline" onClick={() => onOpenChange(false)}>- Not now- </Button>- <Button data-run-agent-setup="" disabled={busy} onClick={setUp}>- {busy ? "Connecting…" : pending.length === 1 ? `Connect ${toSet.name}` : "Connect these agents"}- </Button>- </div>- </>- ) : (- <>- <DialogDescription className="mt-1.5 text-[13px] leading-relaxed text-muted-foreground">- We couldn't find an agent such as Claude Code or Codex on this computer. Install one, then come back here. Or connect one by hand.- </DialogDescription>- <div className="mt-5 flex justify-end gap-2">- <Button variant="outline" onClick={() => onOpenChange(false)}>- Close- </Button>- {onManual ? (- <Button- onClick={() => {- onOpenChange(false);- onManual();- }}- >- Show me how- </Button>- ) : null}- </div>- </>- )}- </div>- </DialogPopup>- </Dialog>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/cli-hint.tsx b/apps/cua-spaces-web/src/legacy/components/cli-hint.tsxdeleted file mode 100644index b8cf23f38d..0000000000--- a/apps/cua-spaces-web/src/legacy/components/cli-hint.tsx+++ /dev/null@@ -1,89 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--/**- * The terminal command next to a GUI action, for people who would rather- * type it: quiet, copyable, and only where the app's CLI is on this- * computer (`SettingsSnapshot.cli`). The commands are `lib/cli-commands.ts`'s.- */--import { CheckIcon, CopyIcon } from "lucide-react";-import { useState } from "react";--import { useSettings } from "@/bridge";-import { Button } from "@/components/ui/button";-import { shownCli } from "@/lib/cli-commands";-import { cn } from "@/lib/utils";--/** The CLI to name in hints, or null when they stay hidden. */-export function useCliName(): string | null {- return shownCli(useSettings().data?.cli);-}--function useCopy(text: string): [boolean, () => void] {- const [copied, setCopied] = useState(false);- const copy = () => {- void navigator.clipboard?.writeText(text).then(() => {- setCopied(true);- setTimeout(() => setCopied(false), 1200);- });- };- return [copied, copy];-}--function CopyButton({ text, className }: { text: string; className?: string }) {- const [copied, copy] = useCopy(text);- return (- <Button- type="button"- size="icon-sm"- variant="ghost"- data-cli-copy=""- aria-label={copied ? "Copied" : `Copy ${text}`}- title={copied ? "Copied" : "Copy"}- onClick={copy}- className={cn("size-6 shrink-0 text-muted-foreground hover:text-foreground", className)}- >- {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}- </Button>- );-}--/** The empty state's line: "Prefer the terminal?" and each command, copyable. */-export function CliHintLine({ commands, className }: { commands: string[]; className?: string }) {- if (!commands.length) return null;- return (- <div data-cli-hint="line" className={cn("flex flex-wrap items-center justify-center gap-x-2 gap-y-1.5 text-xs text-muted-foreground", className)}>- <span>Prefer the terminal?</span>- {commands.map((command) => (- <span key={command} className="inline-flex items-center rounded-md bg-foreground/[0.05] py-0.5 pr-0.5 pl-2">- <code data-cli-command="" className="font-mono text-[11px] text-foreground/80 select-all">- {command}- </code>- <CopyButton text={command} />- </span>- ))}- </div>- );-}--/** New Space's Summary block: "Or run this in Terminal", the commands, one copy. */-export function CliHintBlock({ commands }: { commands: string[] }) {- const text = commands.join("\n");- const [copied, copy] = useCopy(text);- if (!commands.length) return null;- return (- <div data-cli-hint="block" className="mt-4">- <div className="flex items-center justify-between px-1 pb-1.5">- <span className="text-xs text-muted-foreground">Or run this in Terminal</span>- <Button type="button" size="sm" variant="ghost" data-cli-copy="" onClick={copy} className="h-6 gap-1 px-1.5 text-xs text-muted-foreground hover:text-foreground">- {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}- {copied ? "Copied" : "Copy"}- </Button>- </div>- <pre data-cli-command="" className="overflow-x-auto rounded-lg bg-foreground/[0.04] px-3 py-2.5 font-mono text-[11.5px] leading-[1.6] whitespace-pre-wrap [overflow-wrap:anywhere] text-foreground/85 select-all dark:bg-black/25">- {text}- </pre>- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/diagnostic-report-dialog.tsx b/apps/cua-spaces-web/src/legacy/components/diagnostic-report-dialog.tsxdeleted file mode 100644index 1c5e756e81..0000000000--- a/apps/cua-spaces-web/src/legacy/components/diagnostic-report-dialog.tsx+++ /dev/null@@ -1,123 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { useEffect, useLayoutEffect, useRef, useState, type ComponentProps } from "react";--import type { CreateReport, ReportPart } from "@/bridge";-import { Button } from "@/components/ui/button";-import { Checkbox } from "@/components/ui/checkbox";-import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";--/** The tallest a part grows before it scrolls (matches `max-h-60`). */-const TEXT_MAX_PX = 240;--/** A textarea that grows to show every wrapped line, up to [`TEXT_MAX_PX`]- * (then it scrolls). Rows would count line breaks, not wrapped lines. */-function FitTextarea({ value, ...props }: Omit<ComponentProps<"textarea">, "rows">) {- const ref = useRef<HTMLTextAreaElement>(null);- const fit = () => {- const el = ref.current;- if (!el) return;- el.style.height = "auto";- if (el.scrollHeight === 0) return;- const border = el.offsetHeight - el.clientHeight;- el.style.height = `${Math.min(el.scrollHeight + border, TEXT_MAX_PX)}px`;- };- useLayoutEffect(fit, [value]);- useEffect(() => {- window.addEventListener("resize", fit);- return () => window.removeEventListener("resize", fit);- }, []);- return <textarea ref={ref} rows={2} value={value} {...props} />;-}--/**- * The review sheet for a failed create's diagnostic report (standard- * crash-report pattern): the app core's redacted report, each part- * editable and kept by default, and nothing sent until the person presses- * Send in their mail app. Open email opens a message to Cua support there- * with the parts they kept.- */-export function DiagnosticReportDialog({- open,- onOpenChange,- report,- onSend,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;- report: CreateReport | null;- onSend: (subject: string, parts: ReportPart[]) => Promise<void>;-}) {- const [parts, setParts] = useState<(ReportPart & { kept: boolean })[]>([]);- const [busy, setBusy] = useState(false);- const [error, setError] = useState<string | null>(null);- useEffect(() => {- if (open && report) {- setParts(report.parts.map((p) => ({ ...p, kept: true })));- setError(null);- }- }, [open, report]);-- const kept = parts.filter((p) => p.kept);- const send = async () => {- if (!report || kept.length === 0) return;- setBusy(true);- setError(null);- try {- await onSend(- report.subject,- kept.map(({ id, label, text }) => ({ id, label, text })),- );- onOpenChange(false);- } catch (e) {- setError(e instanceof Error ? e.message : String(e));- } finally {- setBusy(false);- }- };- const edit = (id: string, change: Partial<{ text: string; kept: boolean }>) =>- setParts((all) => all.map((p) => (p.id === id ? { ...p, ...change } : p)));-- return (- <Dialog open={open} onOpenChange={(next) => (busy ? undefined : onOpenChange(next))}>- <DialogPopup className="top-[8vh] w-[min(600px,calc(100vw-2rem))]" data-diagnostic-report="">- <div className="px-6 pt-5 pb-4">- <DialogTitle className="text-[15px] font-semibold">{report?.title ?? "Send a diagnostic report"}</DialogTitle>- <DialogDescription className="mt-1 text-[13px] text-muted-foreground">{report?.intro}</DialogDescription>- <div className="mt-4 flex max-h-[55vh] flex-col gap-4 overflow-y-auto">- {parts.map((p) => (- <div key={p.id} data-report-part={p.id}>- <label className="flex items-center gap-2 text-[13px] font-medium">- <Checkbox checked={p.kept} onCheckedChange={(v) => edit(p.id, { kept: Boolean(v) })} aria-label={`Include ${p.label}`} />- {p.label}- </label>- <FitTextarea- aria-label={p.label}- className="mt-1.5 max-h-60 min-h-[4.5rem] w-full resize-y overflow-y-auto rounded-md border bg-background px-2.5 py-2 font-mono text-xs leading-relaxed disabled:opacity-50"- value={p.text}- disabled={!p.kept || busy}- spellCheck={false}- onChange={(e) => edit(p.id, { text: e.target.value })}- />- </div>- ))}- </div>- {error ? (- <p role="alert" className="mt-2 text-xs text-destructive">- {error}- </p>- ) : null}- <div className="mt-4 flex justify-end gap-2">- <Button variant="outline" disabled={busy} onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button data-report-send="" disabled={busy || !report || kept.length === 0} onClick={() => void send()}>- {report?.sendLabel ?? "Open email"}- </Button>- </div>- </div>- </DialogPopup>- </Dialog>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/empty-home.tsx b/apps/cua-spaces-web/src/legacy/components/empty-home.tsxdeleted file mode 100644index 436abc489d..0000000000--- a/apps/cua-spaces-web/src/legacy/components/empty-home.tsx+++ /dev/null@@ -1,95 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--/**- * The main window with no Spaces yet, as the SwiftUI app draws it: a- * monitor, "Create your first Space" with the three steps ahead (the guided- * first run, CUA-2062; counted once as `first_run_guide_shown`), one tile per system this machine runs (Linux,- * and macOS on Apple silicon Macs) with its time and size from the core,- * under the Spaces header (its New Space opens the wizard with nothing- * chosen). A tile opens New Space with that system chosen, on this machine- * (the wizard says when it can't run here). Below them, the same creates- * as terminal commands, when the app's CLI is installed.- */--import { useNewSpaceWizard, type EmptyHome as EmptyHomeView, type EmptyTile } from "@/bridge";-import { useEffect } from "react";--import { CliHintLine, useCliName } from "@/legacy/components/cli-hint";-import { useFirstRunStep } from "@/components/first-run-guide";-import { OsIcon } from "@/components/os-icon";-import { createAliasCommand } from "@/lib/cli-commands";--/** `unread`: the host could not read the Spaces list (`listNotice`): the- * title says so and no system is offered, as the SwiftUI app's does. */-export function EmptyHome({ home, unread = false }: { home: EmptyHomeView; unread?: boolean }) {- const wizard = useNewSpaceWizard();- const start = (tile: EmptyTile) => wizard.show(null, tile.os);- const step = useFirstRunStep();- // The same creates in a terminal, when the app's CLI is on this computer.- const cli = useCliName();- const commands = cli ? home.tiles.map((tile) => createAliasCommand(cli, tile.os)) : [];- useEffect(() => {- if (!unread) step("guide_shown");- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [unread]);- return (- <section data-empty-home="" aria-labelledby="empty-home-title" className="flex flex-col items-center px-8 pt-8 pb-10 text-center">- <MonitorGlyph />- <h2 id="empty-home-title" className="mt-4 text-[22px] font-bold tracking-[-0.01em] text-foreground">- {unread ? "Spaces could not be loaded" : "Create your first Space"}- </h2>- {unread ? null : (- <>- <p className="mt-2.5 max-w-md text-[13px] text-muted-foreground">- A Space is a fresh computer for you and your agents. {home.detail}- </p>- <ol data-first-run-steps="" className="mt-3 flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs text-muted-foreground">- <li>1. Pick a system</li>- <li>2. Wait while it sets up</li>- <li>3. Try a task with an agent</li>- </ol>- <div className="mt-5 flex flex-wrap justify-center gap-3">- {home.tiles.map((tile) => (- <Tile key={tile.os} tile={tile} onStart={start} />- ))}- </div>- <CliHintLine commands={commands} className="mt-4" />- </>- )}- </section>- );-}--function Tile({ tile, onStart }: { tile: EmptyTile; onStart: (t: EmptyTile) => void }) {- return (- <button- type="button"- data-empty-tile={tile.os}- aria-label={`${tile.name}, ${tile.detail}`}- onClick={() => onStart(tile)}- className="flex h-20 w-72 cursor-default items-center gap-3 rounded-2xl bg-card px-4 text-left shadow-[0_0_0_0.5px_hsl(var(--shadow-color)/0.06),0_2px_10px_hsl(var(--shadow-color)/0.08)] outline-none transition-[background-color,box-shadow,scale] duration-150 hover:shadow-[0_0_0_0.5px_hsl(var(--shadow-color)/0.1),0_4px_16px_hsl(var(--shadow-color)/0.13)] active:scale-[0.98] focus-visible:ring-2 focus-visible:ring-ring/60 dark:bg-white/[0.06] dark:hover:bg-white/[0.09]"- >- <span className="flex size-11 shrink-0 items-center justify-center rounded-[10px] bg-foreground/[0.06]">- <OsIcon os={tile.os} className="size-6" />- </span>- <span className="min-w-0">- <span className="block text-[13px] font-semibold">{tile.name}</span>- <span data-empty-tile-detail="" className="mt-0.5 block truncate text-xs text-muted-foreground">- {tile.detail}- </span>- </span>- </button>- );-}--/** SF Symbols' `desktopcomputer`, filled, in the secondary color. */-function MonitorGlyph() {- return (- <svg viewBox="0 0 40 34" aria-hidden className="h-[34px] w-10 text-muted-foreground/40">- <rect x="0.5" y="0.5" width="39" height="26" rx="3.5" fill="currentColor" />- <rect x="2.5" y="2.5" width="35" height="19" rx="1.5" className="fill-background" opacity="0.5" />- <path d="M15 27h10l1 4.5h3v2H11v-2h3z" fill="currentColor" />- </svg>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/getting-started.tsx b/apps/cua-spaces-web/src/legacy/components/getting-started.tsxdeleted file mode 100644index aea2730019..0000000000--- a/apps/cua-spaces-web/src/legacy/components/getting-started.tsx+++ /dev/null@@ -1,236 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--/**- * The getting-started checklist in the sidebar: five first steps, ticked- * off as they happen, each skippable, closable, and back from the command- * palette or Help > Getting Started. Its steps, words and progress are the- * core's (`bridge/checklist.ts`); this draws them and runs each step.- */--import { useNavigate } from "@tanstack/react-router";-import { CheckIcon, ChevronDownIcon } from "lucide-react";-import { useEffect, useSyncExternalStore } from "react";--import {- useAgents,- useBridge,- useChecklist,- useExperiments,- useMachines,- useSession,- useShareSheet,- useSpaces,- useTeleport,- type ChecklistStep,- type Space,-} from "@/bridge";-import { spaceDetail } from "@/bridge/space-detail";-import { WEBKIT_EVENT, WEBKIT_OPEN_CHECKLIST_EVENT, type WebkitEventDetail } from "@/bridge/webkit-protocol";-import { toast, toastError } from "@/components/ui/toast";-import { useNewSpace } from "@/hooks/use-new-space";-import { realSpaces, spaceState } from "@/lib/spaces";-import { cn } from "@/lib/utils";--/**- * Where "Add a machine" goes. One place, so a new add-machine flow (a link- * or QR code, a team invite) only has to change this.- */-export const ADD_MACHINE_HREF = "/machines?add=1";--/** The first Space whose own page offers `action` now (the core's detail- * actions: Share follows Settings, Experiments; both need it running). */-function spaceFor(spaces: Space[], offers: (space: Space) => boolean | undefined): { space?: Space; offered: boolean } {- const real = realSpaces(spaces).filter((s) => spaceState(s) === "running" || spaceState(s) === "stopped");- let offered = false;- for (const space of real) {- const on = offers(space);- if (on === undefined) continue;- offered = true;- if (on) return { space, offered };- }- return { offered };-}--/** Whether the sidebar's checklist is open (Help > Getting Started opens it). */-let expanded = false;-const expandListeners = new Set<() => void>();-export function setExpanded(on: boolean): void {- expanded = on;- for (const l of [...expandListeners]) l();-}-function useExpanded(): boolean {- return useSyncExternalStore(- (l) => {- expandListeners.add(l);- return () => void expandListeners.delete(l);- },- () => expanded,- () => false,- );-}--/** What each step's row does when clicked. */-function useChecklistGo(): (step: ChecklistStep) => void {- const navigate = useNavigate();- const newSpace = useNewSpace();- const { data: spaces = [], isLoading: spacesLoading } = useSpaces();- const { data: session } = useSession();- const teleport = useTeleport();- const share = useShareSheet();- const { core } = useBridge();- const exp = useExperiments();- const experiments = exp.unsupported ? undefined : (exp.data?.experiments ?? {});- const { data: machines = [] } = useMachines();- const thisMachine = machines.find((m) => m.current);- const offers = (id: string) => (space: Space) => {- const a = spaceDetail(core, space, null, thisMachine?.arch ?? null, experiments, thisMachine?.accessNotice ?? null).actions.find((x) => x.id === id);- return a ? a.enabled : undefined;- };- /** Opens `open` on a Space that offers it, or says what is missing. */- const onSpace = (id: string, open: (space: Space) => Promise<void>, what: string) => {- if (spacesLoading) return;- if (realSpaces(spaces).length === 0) return newSpace();- const { space, offered } = spaceFor(spaces, offers(id));- if (space) return void open(space).catch(toastError(`Couldn't open ${what}`));- if (!offered && id === "share") {- return void toast("Sharing isn't available yet", { description: "It is not switched on for this account." });- }- toast("Start a Space first", { description: `${what} works on a running Space.` });- };- return (step) => {- switch (step) {- case "add_machine":- return void navigate({ href: ADD_MACHINE_HREF });- case "create_space":- return newSpace();- case "teleport":- return onSpace("teleport", (space) => teleport.open(space), "Teleport");- case "share":- return onSpace("share", (space) => share.open(space, session?.signedIn ?? false), "Share");- case "run_agent":- return void navigate({ to: "/agents" });- }- };-}--/**- * "Get started 2/5" at the bottom of the sidebar. Its steps open in place,- * above it: each does its thing when clicked, and has a quiet Skip (a- * skipped step counts as done). Hide closes it ("Done" once complete); Help- * > Getting Started brings it back, open. The steps, words and progress are- * the core's (`bridge/checklist.ts`).- */-export function SidebarGetStarted() {- const { view, shown, dismiss, skip } = useChecklist();- const open = useExpanded();- const go = useChecklistGo();- const visible = view?.visible ?? false;-- useEffect(() => {- if (visible) shown();- }, [visible, shown]);-- if (!view || !visible) return null;- const settled = view.rows.filter((r) => r.done || r.skipped).length;- const share = settled / view.rows.length;- return (- <section data-checklist="" data-open={open || undefined} aria-label={view.title} className="mx-2 mb-1">- {open ? (- <ol className="mb-1 border-t border-foreground/10 pt-1" data-checklist-steps="">- {view.rows.map(({ step, title, detail, done, skipped }) => (- <li key={step} data-checklist-step={step} data-done={done || undefined} data-skipped={skipped || undefined} className="group flex h-7 items-center gap-2 rounded-md px-2 text-[12.5px] hover:bg-foreground/5">- <span- aria-hidden- className={cn(- "flex size-3.5 shrink-0 items-center justify-center rounded-full border",- done ? "border-brand bg-brand text-white" : skipped ? "border-foreground/25 bg-foreground/10" : "border-foreground/25",- )}- >- {done ? <CheckIcon className="size-2" strokeWidth={3.5} /> : null}- </span>- <button- type="button"- title={detail}- disabled={done || skipped}- onClick={() => go(step)}- className={cn("min-w-0 flex-1 truncate text-left outline-none disabled:cursor-default", done || skipped ? "text-muted-foreground line-through decoration-foreground/30" : "text-foreground")}- >- {title}- <span className="sr-only">{done ? " (done)" : skipped ? " (skipped)" : ""}</span>- </button>- {done ? null : skipped ? (- <span className="text-[11px] text-muted-foreground">Skipped</span>- ) : (- <button type="button" className="text-[11px] text-muted-foreground opacity-70 hover:text-foreground hover:opacity-100" onClick={() => skip(step)} data-checklist-skip={step}>- {view.skipLabel}- </button>- )}- </li>- ))}- </ol>- ) : null}- <div className="flex h-7 items-center gap-2 rounded-md px-2 text-[13px] text-muted-foreground hover:bg-foreground/5">- <button type="button" className="flex min-w-0 flex-1 items-center gap-2 text-left outline-none hover:text-foreground" onClick={() => setExpanded(!open)} aria-expanded={open} data-checklist-toggle="">- <svg viewBox="0 0 16 16" aria-hidden className="size-3.5 shrink-0 -rotate-90">- <circle cx="8" cy="8" r="6.5" fill="none" stroke="currentColor" strokeOpacity=".25" strokeWidth="2" />- <circle cx="8" cy="8" r="6.5" fill="none" stroke="currentColor" strokeWidth="2" strokeDasharray={`${share * 40.8} 40.8`} />- </svg>- <span className="flex-1 truncate">{view.title}</span>- <span className="tabular-nums" data-checklist-count="">- {settled}/{view.rows.length}- </span>- <ChevronDownIcon aria-hidden className={cn("size-3.5 transition-transform", open ? "" : "rotate-180")} />- </button>- {open || view.complete ? (- <button type="button" className="text-[11px] hover:text-foreground" onClick={() => dismiss()} aria-label={view.closeLabel} data-checklist-hide="">- {view.hideLabel}- </button>- ) : null}- </div>- </section>- );-}--/**- * Tells the checklist what the app already shows (another machine, a- * Space, an agent; the core ticks those steps off) and answers Help >- * Getting Started. In the Mac app and Electron the host ticks those steps- * off itself (`checklist::observe_from`) and this page's observations are- * not sent; they count only where the page keeps its own copy (the demo). Teleport and Share tick themselves off where they- * finish (`bridge/teleport.ts`, `bridge/share.ts`). Mounted once, under- * the main layout.- */-export function ChecklistTracker() {- const { state, send, reopen } = useChecklist();- const { data: machines } = useMachines();- const { data: spaces } = useSpaces();-- const otherMachine = machines?.some((m) => !m.current) ?? false;- const hasSpace = spaces ? realSpaces(spaces).some((s) => ["running", "stopped"].includes(spaceState(s))) : false;- useEffect(() => {- if (otherMachine || hasSpace) send({ type: "observe", otherMachine, hasSpace, agentRan: false });- }, [otherMachine, hasSpace, send]);-- useEffect(() => {- const onHostEvent = (event: Event) => {- if ((event as CustomEvent<WebkitEventDetail>).detail?.event !== WEBKIT_OPEN_CHECKLIST_EVENT) return;- reopen();- setExpanded(true);- };- window.addEventListener(WEBKIT_EVENT, onHostEvent);- return () => window.removeEventListener(WEBKIT_EVENT, onHostEvent);- }, [reopen]);-- // Agents are only read while this step is open.- return state.done.run_agent ? null : <AgentProgress onRun={() => send({ type: "observe", otherMachine: false, hasSpace: false, agentRan: true })} />;-}--function AgentProgress({ onRun }: { onRun: () => void }) {- const { data } = useAgents();- const ran = (data?.runs.length ?? 0) > 0 || (data?.agents.length ?? 0) > 0;- useEffect(() => {- if (ran) onRun();- }, [ran, onRun]);- return null;-}diff --git a/apps/cua-spaces-web/src/legacy/components/join-with-code-dialog.tsx b/apps/cua-spaces-web/src/legacy/components/join-with-code-dialog.tsxdeleted file mode 100644index ec0dd00203..0000000000--- a/apps/cua-spaces-web/src/legacy/components/join-with-code-dialog.tsx+++ /dev/null@@ -1,115 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { CheckIcon, LoaderCircleIcon } from "lucide-react";-import { useEffect, useState, type FormEvent } from "react";--import { displayPairingCode, normalizePairingCode, pairingLinkRelay, useJoinWithCode, useMachines } from "@/bridge";-import { Button } from "@/components/ui/button";-import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";--/**- * "Join with a code": adds this computer to the account that made a- * one-time code in "Add a machine" on another device. Meant for a computer- * that has Cua Spaces but is not signed in to that account (a team machine,- * or a computer you don't want to sign in on). `initialCode` is a code that- * arrived by a `cua://add/<code>` link; it fills the field, and nothing- * joins until the person presses Join.- */-export function JoinWithCodeDialog({- open,- onOpenChange,- initialCode = "",- initialRelay = null,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;- initialCode?: string;- initialRelay?: string | null;-}) {- const { refresh } = useMachines();- const joining = useJoinWithCode({ onJoined: () => void refresh().catch(() => {}) });- const [text, setText] = useState(initialCode);- const { reset } = joining;- useEffect(() => {- if (open) {- setText(initialCode ? displayPairingCode(initialCode) : "");- reset();- }- }, [open, initialCode, reset]);-- const busy = joining.phase === "joining";- const joined = joining.phase === "joined";- const ready = normalizePairingCode(text) !== null;- const relay = initialRelay ?? pairingLinkRelay(text);- const submit = (e: FormEvent) => {- e.preventDefault();- if (!busy && !joined && ready) void joining.join(text, relay);- };-- return (- <Dialog open={open} onOpenChange={(next) => (busy ? undefined : onOpenChange(next))}>- <DialogPopup className="top-[14vh] w-[min(460px,calc(100vw-2rem))]" data-join-with-code={joining.phase}>- <form onSubmit={submit} className="px-6 pt-5 pb-4">- <DialogTitle className="text-[15px] font-semibold">Join with a code</DialogTitle>- <DialogDescription className="mt-1 text-[13px] text-muted-foreground">- Paste the code from Add a computer on your other device. This computer is added to the account that made it, and that account can then reach it. Only use a code you made yourself or got from someone you trust.- </DialogDescription>- {relay ? (- <p className="mt-2 text-xs text-muted-foreground" data-join-relay>- This code uses its own relay: <span className="font-medium text-foreground">{relay}</span>- </p>- ) : null}- {joined ? (- <div className="mt-4 flex items-center gap-2.5 rounded-lg border bg-card px-3 py-3 text-[13px]" data-join-joined>- <CheckIcon className="size-4 shrink-0 text-success" aria-hidden />- <span>This computer joined. It shows in your computers.</span>- </div>- ) : (- <>- <Input- autoFocus- aria-label="Pairing code"- placeholder="XXXX-XXXX-XXXX"- className="mt-4 font-mono tracking-wider"- value={text}- disabled={busy}- spellCheck={false}- autoCapitalize="characters"- autoComplete="off"- onChange={(e) => setText(e.target.value)}- />- {joining.error ? (- <p role="alert" className="mt-2 text-xs text-destructive" data-join-error>- {joining.error}- </p>- ) : null}- {busy ? (- <p className="mt-3 flex items-center gap-2 text-xs text-muted-foreground" data-join-busy>- <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden /> Setting this computer up…- </p>- ) : null}- </>- )}- <div className="mt-4 flex justify-end gap-2">- {joined ? (- <Button type="button" onClick={() => onOpenChange(false)}>- Done- </Button>- ) : (- <>- <Button type="button" variant="outline" disabled={busy} onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button type="submit" disabled={busy || !ready}>- Join- </Button>- </>- )}- </div>- </form>- </DialogPopup>- </Dialog>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/keyvault/approval-dialog.tsx b/apps/cua-spaces-web/src/legacy/components/keyvault/approval-dialog.tsxdeleted file mode 100644index f61210ffe1..0000000000--- a/apps/cua-spaces-web/src/legacy/components/keyvault/approval-dialog.tsx+++ /dev/null@@ -1,79 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { useState } from "react";--import { useBridge, type ApprovalAction, type ApprovalState, type ApprovalView, type KeyvaultOverview, type KvCommand } from "@/bridge";-import { Button } from "@/components/ui/button";-import { Checkbox } from "@/components/ui/checkbox";-import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";--/**- * Review a waiting request (the SwiftUI `ApprovalSheet`): nothing is ticked- * until the user ticks it, Approve sends exactly the ticked rows, and the- * host confirms with Touch ID. The rows, the gate and the labels are the- * core's (`approval.*`).- */-export function ApprovalDialog({- overview,- labels,- requestId,- busy,- onApprove,- onDeny,- onClose,-}: {- overview: KeyvaultOverview;- labels: { cancel: string; deny: string; confirmNote: string };- requestId: string;- busy: boolean;- onApprove: (requestId: string, items: string[] | null) => void;- onDeny: (requestId: string) => void;- onClose: () => void;-}) {- const { core } = useBridge();- const [state, setState] = useState<ApprovalState>(() => core.call<ApprovalState>("approval.open", { requestId }));- const view = core.tryCall<ApprovalView>("approval.view", { overview, state });- const send = (action: ApprovalAction) => setState(core.call<ApprovalState>("approval.reduce", { overview, state, action }));- if (!view) return null;- const approve = () => {- const command = core.tryCall<KvCommand | null>("approval.approveCommand", { overview, state });- if (command?.type === "approve") onApprove(command.requestId, command.items);- };- return (- <Dialog open onOpenChange={(open) => !open && onClose()}>- <DialogPopup>- <div className="px-5 pt-5 pb-3" data-approval>- <DialogTitle className="text-[15px] font-semibold">{view.title}</DialogTitle>- <p className="mt-1 text-xs text-muted-foreground" title={view.claims.join("\n")}>- {view.badge.text} · to {view.targets} · {view.wants}- </p>- <ul className="mt-3 max-h-64 divide-y overflow-y-auto rounded-lg border bg-card">- {view.rows.map((row) => (- <li key={row.key}>- <label className="flex cursor-default items-center gap-3 px-4 py-2.5" data-approval-row={row.key}>- <Checkbox aria-label={`Approve ${row.title}`} checked={row.selected} onCheckedChange={() => send({ type: "toggle", key: row.key })} />- <span className="min-w-0 flex-1 truncate text-[13px]">{row.title}</span>- <span className="shrink-0 text-xs text-muted-foreground">{row.account}</span>- </label>- </li>- ))}- </ul>- {view.blockedReason ? <p className="mt-2 text-xs text-muted-foreground">{view.blockedReason}</p> : null}- </div>- <div className="flex items-center gap-2 border-t bg-muted/60 px-5 py-3">- <span className="flex-1 text-xs text-muted-foreground">{labels.confirmNote}</span>- <Button variant="outline" onClick={onClose}>- {labels.cancel}- </Button>- <Button variant="outline" disabled={busy} onClick={() => onDeny(requestId)}>- {labels.deny}- </Button>- <Button disabled={!view.canApprove || busy} onClick={approve} data-approval-approve>- {view.approveLabel}- </Button>- </div>- </DialogPopup>- </Dialog>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/keyvault/category-pane.tsx b/apps/cua-spaces-web/src/legacy/components/keyvault/category-pane.tsxdeleted file mode 100644index ebd5b0a6a3..0000000000--- a/apps/cua-spaces-web/src/legacy/components/keyvault/category-pane.tsx+++ /dev/null@@ -1,121 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { useEffect, useRef } from "react";--import type { KvAccessCommand, KvListView, KvPage } from "@/bridge";-import { Button } from "@/components/ui/button";-import { cn } from "@/lib/utils";--/**- * Waiting, Access or Recent (the SwiftUI `CategoryList`): the core's pane- * for the category. Waiting rows are requests an agent made (Deny, or Review- * to pick what to approve); Access rows are live grants, rules and copies in- * Spaces, each with its own Revoke, Remove or Wipe and, for copies, Dismiss- * (hides it from the notch only); Recent is the decision log.- */-export function CategoryPane({- list,- page,- dismissed,- focus,- busy,- onReview,- onDeny,- onRun,- onDismiss,-}: {- list: KvListView;- page: KvPage;- /** Copies (import ids) already hidden from the notch. */- dismissed: readonly string[];- /** The Access row to bring forward (a Space's "Signed in" badge). */- focus: string | null;- busy: boolean;- onReview: (requestId: string) => void;- onDeny: (requestId: string) => void;- onRun: (command: KvAccessCommand) => void;- onDismiss: (imports: string[]) => void;-}) {- const focused = useRef<HTMLLIElement | null>(null);- useEffect(() => {- if (focus) focused.current?.scrollIntoView?.({ block: "center" });- }, [focus, list.access.length]);- return (- <div className="mx-auto w-full max-w-3xl space-y-5 px-8 pb-16">- {list.pending.length ? (- <Section>- {list.pending.map((p) => (- <Row key={p.id} data-waiting={p.id} title={p.claims.join("\n")}>- <span className="min-w-0 flex-1 truncate">- {p.caller} ({p.badge.text}) · {p.summary} · {p.wants}- </span>- <Button size="sm" variant="outline" disabled={busy} onClick={() => onDeny(p.id)}>- {page.labels.deny}- </Button>- <Button size="sm" disabled={page.disabled || busy} onClick={() => onReview(p.id)}>- {page.labels.review}- </Button>- </Row>- ))}- </Section>- ) : null}- {list.access.length ? (- <Section>- {page.revokeAll ? (- <li className="flex justify-end px-4 py-2">- <Button size="sm" variant="outline" disabled={busy} onClick={() => onRun({ type: "revoke-grant", id: "*" })}>- {page.labels.revokeAll}- </Button>- </li>- ) : null}- {list.access.map((a) => {- const hidden = a.imports.length > 0 && a.imports.every((i) => dismissed.includes(i));- return (- <Row key={a.key} data-access={a.key} focused={focus === a.key} ref={focus === a.key ? focused : undefined} title={a.detail}>- <span className="min-w-0 flex-1 truncate">{a.detail ? `${a.text} · ${a.detail}` : a.text}</span>- {/* Hides the notch's indicator only; Wipe removes the access. */}- {a.imports.length > 0 && !hidden ? (- <Button size="sm" variant="ghost" title="Hide from the notch. Access stays until you wipe it." onClick={() => onDismiss(a.imports)}>- Dismiss- </Button>- ) : null}- <Button size="sm" variant="outline" disabled={busy} onClick={() => onRun(a.command as KvAccessCommand)}>- {a.actionLabel}- </Button>- </Row>- );- })}- </Section>- ) : null}- {list.recent.length ? (- <>- <Section>- {list.recent.map((r) => (- <Row key={r.decision.entry.seq}>- <span className="min-w-0 flex-1 truncate">- {r.decision.verb} {r.decision.what}- </span>- <span className="shrink-0 text-xs text-muted-foreground">{r.age}</span>- </Row>- ))}- </Section>- {page.logStatus ? <p className="px-1 text-xs text-muted-foreground">{page.logStatus}</p> : null}- </>- ) : null}- {list.emptyText ? <p className="px-1 text-[13px] text-muted-foreground" data-category-empty>{list.emptyText}</p> : null}- </div>- );-}--function Section({ children }: { children: React.ReactNode }) {- return <ul className="divide-y overflow-hidden rounded-lg border bg-card">{children}</ul>;-}--function Row({ children, focused, ...rest }: React.ComponentProps<"li"> & { focused?: boolean }) {- return (- <li {...rest} data-focused={focused || undefined} className={cn("flex items-center gap-2 px-4 py-2.5 text-[13px] transition-colors", focused && "bg-brand-surface")}>- {children}- </li>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/keyvault/keyvault-page.tsx b/apps/cua-spaces-web/src/legacy/components/keyvault/keyvault-page.tsxdeleted file mode 100644index d7942e6f59..0000000000--- a/apps/cua-spaces-web/src/legacy/components/keyvault/keyvault-page.tsx+++ /dev/null@@ -1,291 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { CheckIcon, CopyIcon, KeyRoundIcon, LockIcon } from "lucide-react";-import { useEffect, useState } from "react";--import { isNativeHost, useBridge, useKeyvault, type KvCategory } from "@/bridge";-import { KEYVAULT_SETUP_COMMAND } from "@/bridge/ops/keyvault-setup";-import { EmptyState, PageHeader } from "@/legacy/components/page";-import { Button } from "@/components/ui/button";-import { ConfirmDialog } from "@/components/ui/alert-dialog";-import { Segmented } from "@/components/ui/segmented";-import { toastError } from "@/components/ui/toast";-import { hostOs, keyvaultUnlockWay } from "@/lib/host-labels";--import { ApprovalDialog } from "@/legacy/components/keyvault/approval-dialog";-import { KeyvaultOptions } from "@/components/keyvault/options-dialog";-import { CategoryPane } from "@/legacy/components/keyvault/category-pane";-import { VaultList } from "@/legacy/components/keyvault/vault-list";--/** A failed action says why; an answer of "no" to the host's own question is not a failure. */-const reportFailure = (title: string) => {- const report = toastError(title);- return (e: unknown) => {- if ((e as { code?: string } | null)?.code !== "cancelled") report(e);- };-};--/** Items waiting on the user's confirmation to delete (a host that asks itself needs no page dialog). */-interface DeleteAsk {- ids: string[];- title: string;- message: string;-}--/**- * The Keyvault, as the SwiftUI app has it: a vault list (items grouped by the- * app they came from, each with a lock) and the Waiting, Access and Recent- * categories. Every list, count and label is the core's (`views.sidebar`,- * `views.vault`, `pane`); the host decides access and no secret value is here.- * `initialView` and `focus` come from a Space's "Signed in" badge: its Access- * row is brought forward.- */-export function KeyvaultPage({ initialView = "all", focus = null }: { initialView?: KvCategory; focus?: string | null }) {- const kv = useKeyvault();- const { data, unlock, unlockItems, lockItems, deleteItems, setUp, approve, deny, runCommand, dismissAccess, showItems, vaultAction, pane } = kv;- const { core, mode } = useBridge();- const views = data?.views ?? null;- // No vault yet: the core's page offers setup; without it, the overview says so.- const canSetup = views ? views.page.canSetup : data?.overview.availability === "no_vault";- // The core's page decides (a vault not set up yet is not locked); without it, the overview.- const locked = views- ? views.page.canUnlock- : data- ? data.overview.availability === "locked" || data.overview.status?.unlocked === false- : false;- // Not running, not set up, or only partly read: the host says why.- const availability = data?.overview.availability;- const unavailable = !canSetup && Boolean(availability && availability !== "ready" && availability !== "locked");- const notice = canSetup- ? null- : unavailable- ? (views?.page.unavailableTitle ?? data?.overview.message ?? "Keyvault isn't available.")- : (data?.overview.partialErrors ?? []).join(" ");- // Under the heading, why and what to do (the broker's sentence), as the- // SwiftUI app's unavailable page has it.- const noticeDetail = unavailable && views?.page.unavailableTitle ? (views.page.message ?? data?.overview.message ?? null) : null;- const [category, setCategory] = useState<KvCategory>(initialView);- const [focused, setFocused] = useState<string | null>(focus);- const [settingUp, setSettingUp] = useState(false);- const [recoveryKey, setRecoveryKey] = useState<string | null>(null);- const [reviewing, setReviewing] = useState<string | null>(null);- const [asking, setAsking] = useState<DeleteAsk | null>(null);- // A Space's badge brings its Access row forward, then lets the highlight go.- useEffect(() => {- if (!focused) return;- const t = setTimeout(() => setFocused(null), 2500);- return () => clearTimeout(t);- }, [focused]);- // Requests in flight (the broker answers one at a time, and Touch ID can take a moment).- const [pending, setPending] = useState(0);- const busy = pending > 0;- const act = (title: string, p: Promise<unknown>) => {- setPending((n) => n + 1);- void p.catch(reportFailure(title)).finally(() => setPending((n) => n - 1));- };- const unlockVault = () => act("Couldn't unlock Keyvault", unlock());- const setUpVault = () => {- setSettingUp(true);- void setUp()- .then(setRecoveryKey, reportFailure("Couldn't set up Keyvault"))- .finally(() => setSettingUp(false));- };- const actions = {- lock: (ids: string[]) => act("Couldn't change access", lockItems(ids)),- unlock: (ids: string[]) => act("Couldn't change access", unlockItems(ids)),- };- /** A native host confirms in its own alert; other hosts get the core's words here. */- const requestDelete = (ids: string[]) => {- if (isNativeHost(mode) || !data) return act("Couldn't delete", deleteItems(ids));- const copies = core.tryCall<number>("keyvault.liveCopySpaces", { overview: data.overview, ids, now: Date.now() }) ?? 0;- const ask = core.tryCall<{ title: string; message: string }>("keyvault.deleteConfirm", { count: ids.length, liveCopies: copies });- if (ask) setAsking({ ids, ...ask });- else act("Couldn't delete", deleteItems(ids));- };- const categories = views?.sidebar.categories ?? [];- const list = views && category !== "all" ? pane({ kind: "category", category }) : null;- const waiting = data?.overview.pending ?? [];-- return (- <div className="flex h-full flex-col">- <div className="mx-auto w-full max-w-3xl px-8 pt-6">- <PageHeader- title="Keyvault"- description="Saved logins your agents can use. Each use asks you first unless you allow it."- actions={- <>- <KeyvaultOptions />- {locked ? (- <Button variant="outline" onClick={unlockVault}>- <LockIcon /> Unlock- </Button>- ) : null}- </>- }- />- {locked ? (- <div className="mb-4 flex items-center gap-3 rounded-xl border bg-brand-surface/60 px-4 py-3">- <LockIcon className="size-4 text-brand-strong" />- <p className="flex-1 text-[13px]">Keyvault is locked. Unlock to change who can use a login.</p>- </div>- ) : null}- {views?.page.disabledBanner ? (- <p className="mb-4 rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-2.5 text-[13px]" data-vault-disabled>- {views.page.disabledBanner}- </p>- ) : null}- {views?.page.resetNotice ? <p className="mb-4 rounded-xl border bg-brand-surface/60 px-4 py-2.5 text-[13px]">{views.page.resetNotice}</p> : null}- {notice ? <p className="mb-4 px-1 text-xs text-muted-foreground" data-vault-notice>{notice}</p> : null}- {noticeDetail && noticeDetail !== notice ? (- <p className="-mt-2 mb-4 px-1 text-xs text-muted-foreground" data-vault-notice-detail>- {noticeDetail}- </p>- ) : null}- {recoveryKey ? <RecoveryKey value={recoveryKey} onDone={() => setRecoveryKey(null)} /> : null}- {canSetup ? (- <SetUpVault- passphrase={views?.page.form?.method === "passphrase"}- help={views?.page.form?.help ?? null}- label={views?.page.labels.setUp ?? "Set up Keyvault"}- busy={settingUp}- onSetUp={setUpVault}- />- ) : categories.length ? (- <div className="mb-3">- <Segmented- aria-label="Keyvault"- value={category}- onValueChange={setCategory}- options={categories.map((c) => ({- value: c.category,- label: (- <>- {c.title}- {c.badge ? (- <span data-waiting-badge className="min-w-4 rounded-full bg-brand px-1 text-center text-2xs font-medium text-white tabular-nums">- {c.badge}- </span>- ) : c.count !== null ? (- <span className="text-2xs text-muted-foreground tabular-nums">{c.count}</span>- ) : null}- </>- ),- }))}- />- </div>- ) : null}- </div>- <div className="min-h-0 flex-1 overflow-y-auto">- {canSetup ? null : !views || !data ? (- <div className="mx-auto max-w-3xl px-8">- <EmptyState icon={<KeyRoundIcon />} title="Keyvault">- The list needs the app core, which isn't loaded.- </EmptyState>- </div>- ) : !views.page.ready ? null : list ? (- <CategoryPane- list={list}- page={views.page}- dismissed={data.overview.dismissed ?? []}- focus={focused}- busy={busy}- onReview={setReviewing}- onDeny={(id) => act("Couldn't deny", deny(id))}- onRun={(c) => act("Couldn't change access", runCommand(c))}- onDismiss={(imports) => act("Couldn't dismiss", dismissAccess(imports))}- />- ) : (- <VaultList- view={views.vault}- query={data.vaultState.query}- blocked={locked || views.page.disabled}- busy={busy}- send={vaultAction}- actions={actions}- onShowItems={() => act("Couldn't show the items", showItems())}- onDelete={requestDelete}- />- )}- </div>- {reviewing && data && views && waiting.some((p) => p.id === reviewing) ? (- <ApprovalDialog- overview={data.overview}- labels={views.page.labels}- requestId={reviewing}- busy={busy}- onClose={() => setReviewing(null)}- onDeny={(id) => {- setReviewing(null);- act("Couldn't deny", deny(id));- }}- onApprove={(id, items) => {- setReviewing(null);- act("Couldn't approve", approve(id, items));- }}- />- ) : null}- <ConfirmDialog- open={asking !== null}- onOpenChange={(open) => !open && setAsking(null)}- title={asking?.title ?? ""}- description={asking?.message}- confirmLabel="Delete"- destructive- onConfirm={() => asking && act("Couldn't delete", deleteItems(asking.ids))}- />- </div>- );-}--/** No vault yet: what it is for, how it is protected, and the one next step. */-function SetUpVault({ passphrase, help, label, busy, onSetUp }: { passphrase: boolean; help: string | null; label: string; busy: boolean; onSetUp: () => void }) {- return (- <div data-vault-setup>- <EmptyState- icon={<KeyRoundIcon />}- title="No Keyvault yet"- action={- <Button onClick={onSetUp} disabled={busy}>- {busy ? "Setting up\u2026" : label}- </Button>- }- >- Set it up to save logins your agents can use.{" "}- {passphrase ? "You choose a passphrase to protect it." : (help ?? `${capitalized(keyvaultUnlockWay())} or a passphrase protects it.`)}- </EmptyState>- <p className="mt-3 px-1 text-center text-xs text-muted-foreground">- Or run <code className="font-mono">{KEYVAULT_SETUP_COMMAND}</code> in {hostOs() === "macos" ? "Terminal" : "a terminal"}.- </p>- </div>- );-}--/** The recovery key, shown once after setup: the only other way in. */-function RecoveryKey({ value, onDone }: { value: string; onDone: () => void }) {- const [copied, setCopied] = useState(false);- return (- <div data-vault-recovery className="mb-4 rounded-xl border bg-brand-surface/60 px-4 py-3">- <p className="text-[13px] font-medium">Save your recovery key</p>- <p className="mt-0.5 text-xs text-muted-foreground">It's shown once. You need it if {keyvaultUnlockWay()} or your passphrase stops working.</p>- <div className="mt-2 flex items-center gap-2">- <code className="flex-1 truncate rounded-md bg-background px-2 py-1 font-mono text-[13px]" data-recovery-key>- {value}- </code>- <Button- size="sm"- variant="outline"- aria-label={copied ? "Copied" : "Copy recovery key"}- onClick={() => void navigator.clipboard?.writeText(value).then(() => setCopied(true), () => {})}- >- {copied ? <CheckIcon /> : <CopyIcon />} {copied ? "Copied" : "Copy"}- </Button>- <Button size="sm" variant="ghost" onClick={onDone}>- Done- </Button>- </div>- </div>- );-}--const capitalized = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);diff --git a/apps/cua-spaces-web/src/legacy/components/keyvault/vault-list.tsx b/apps/cua-spaces-web/src/legacy/components/keyvault/vault-list.tsxdeleted file mode 100644index 9aa0b79086..0000000000--- a/apps/cua-spaces-web/src/legacy/components/keyvault/vault-list.tsx+++ /dev/null@@ -1,333 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { LegendList } from "@legendapp/list/react";-import { ChevronDownIcon, ChevronRightIcon, EyeOffIcon, FileIcon, FolderIcon, GlobeIcon, LockIcon, LockOpenIcon, SearchIcon, Trash2Icon } from "lucide-react";--import type { KvLock, Tri, VaultAction, VaultApp, VaultRow, VaultSelection, VaultView } from "@/bridge";-import { Button } from "@/components/ui/button";-import { Checkbox } from "@/components/ui/checkbox";-import { Input } from "@/components/ui/input";-import { KIND_ICON } from "@/legacy/components/teleport/saved-items";-import { vaultLines, type VaultLine } from "@/lib/keyvault";-import { cn } from "@/lib/utils";--interface LockActions {- /** Locks items (narrowing: no prompt, no Touch ID). */- lock: (ids: string[]) => void;- /** Asks, then Touch ID once, for these items (`name`: the one item's name). */- unlock: (ids: string[], name?: string) => void;-}--/**- * The vault list, as the SwiftUI app draws it: apps, their sites and items- * with a lock each; checkboxes select an item, a site or a whole app for- * the batch bar (lock, unlock, delete). Everything shown, the grouping, the- * selection and the search are the core's `VaultView`; a lock only asks the- * host. Hidden names (until Touch ID) say so and offer to show them.- */-export function VaultList({- view,- query,- blocked,- busy,- send,- actions,- onShowItems,- onDelete,-}: {- view: VaultView;- query: string;- /** The Keyvault is off or locked: unlocking items waits. */- blocked: boolean;- busy: boolean;- send: (action: VaultAction) => void;- actions: LockActions;- onShowItems: () => void;- onDelete: (ids: string[]) => void;-}) {- const lines = vaultLines(view);- return (- <div className="flex h-full min-h-0 flex-col">- <div className="mx-auto w-full max-w-3xl px-8">- <div className="relative mb-3">- <SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />- <Input value={query} onChange={(e) => send({ type: "query", text: e.target.value })} placeholder={view.searchPrompt} aria-label="Search Keyvault" className="pl-8" />- </div>- {view.namesHidden ? (- <div className="mb-3 flex items-center gap-3 rounded-xl border bg-brand-surface/60 px-4 py-2.5" data-vault-hidden>- <EyeOffIcon className="size-4 shrink-0 text-muted-foreground" />- <p className="min-w-0 flex-1 text-[13px] text-muted-foreground">{view.hiddenNote}</p>- <Button size="sm" variant="outline" disabled={busy} onClick={onShowItems} data-vault-show-items>- {view.showNamesLabel}- </Button>- </div>- ) : null}- <div className="flex h-8 items-center justify-between px-1 text-xs text-muted-foreground">- <span data-vault-summary>{view.selection.count > 0 ? view.selection.title : `${view.total} items in ${view.apps.length} apps`}</span>- {view.canSelectAll ? (- <button type="button" className="text-brand hover:underline" onClick={() => send({ type: view.selection.count === view.shown ? "clear" : "select-all" })}>- {view.selection.count === view.shown ? "Select None" : "Select All"}- </button>- ) : null}- </div>- </div>- <div className="min-h-0 flex-1">- {view.emptyText ? (- <p className="mx-auto max-w-3xl px-9 py-6 text-[13px] text-muted-foreground" data-vault-empty>- {view.emptyText}- </p>- ) : (- <LegendList<VaultLine>- data={lines}- keyExtractor={(line) => line.key}- getItemType={(line) => line.type}- estimatedItemSize={40}- recycleItems={false}- className="h-full"- contentContainerStyle={{ maxWidth: "48rem", marginInline: "auto", paddingInline: "2rem", paddingBottom: "5rem" }}- renderItem={({ item: line }) => <Line line={line} send={send} actions={actions} blocked={blocked || busy} />}- />- )}- </div>- {view.selection.count > 0 ? <BatchBar selection={view.selection} blocked={blocked} busy={busy} send={send} actions={actions} onDelete={onDelete} /> : null}- </div>- );-}--function Line({ line, send, actions, blocked }: { line: VaultLine; send: (a: VaultAction) => void; actions: LockActions; blocked: boolean }) {- switch (line.type) {- case "app":- return (- <GroupRow- indent={0}- selected={line.app.selected}- open={line.app.open}- label={line.app.name}- icon={<AppMonogram app={line.app} />}- title={<span className="text-[13px] font-semibold">{line.app.name}</span>}- detail={line.app.summary}- updated={line.app.updated}- lock={{ state: line.app.lock, name: line.app.name, unlockIds: line.app.unlockIds, lockIds: line.app.lockIds }}- onSelect={() => send({ type: "toggle-group", key: line.app.key })}- onOpen={() => send({ type: "toggle-open", key: line.app.key })}- actions={actions}- blocked={blocked}- />- );- case "site":- return (- <GroupRow- indent={1}- selected={line.site.selected}- open={line.site.open}- label={line.site.site}- icon={<GlobeIcon className="size-4 text-muted-foreground" />}- title={<span className="text-[13px]">{line.site.site}</span>}- detail={line.site.counts}- updated={line.site.updated}- lock={{ state: line.site.lock, name: line.site.site, unlockIds: line.site.unlockIds, lockIds: line.site.lockIds }}- onSelect={() => send({ type: "toggle-group", key: line.site.key })}- onOpen={() => send({ type: "toggle-open", key: line.site.key })}- actions={actions}- blocked={blocked}- />- );- case "files":- return (- <GroupRow- indent={1}- selected={line.files.selected}- open={line.files.open}- label="files"- icon={<FolderIcon className="size-4 text-muted-foreground" />}- title={<span className="text-[13px]">Files</span>}- detail={`${line.files.count} file${line.files.count === 1 ? "" : "s"}`}- updated=""- lock={{ state: line.files.lock, name: "files", unlockIds: line.files.unlockIds, lockIds: line.files.lockIds }}- onSelect={() => send({ type: "toggle-group", key: line.files.key })}- onOpen={() => send({ type: "toggle-open", key: line.files.key })}- actions={actions}- blocked={blocked}- />- );- case "item":- return <ItemRow row={line.row} indent={line.indent} send={send} actions={actions} blocked={blocked} />;- }-}--const triChecked = (t: Tri) => t === "on";--function AppMonogram({ app }: { app: VaultApp }) {- return (- <span aria-hidden className="flex size-5 items-center justify-center rounded-[5px] bg-foreground/10 text-[11px] font-semibold">- {app.name.slice(0, 1).toUpperCase()}- </span>- );-}--interface LockSpec {- state: KvLock;- name: string;- unlockIds: string[];- lockIds: string[];-}--function GroupRow({- indent,- selected,- open,- label,- icon,- title,- detail,- updated,- lock,- onSelect,- onOpen,- actions,- blocked,-}: {- indent: 0 | 1;- selected: Tri;- open: boolean;- label: string;- icon: React.ReactNode;- title: React.ReactNode;- detail: string;- updated: string;- lock: LockSpec;- onSelect: () => void;- onOpen: () => void;- actions: LockActions;- blocked: boolean;-}) {- const Chevron = open ? ChevronDownIcon : ChevronRightIcon;- return (- <div- data-vault-group={label}- // The parity spec reads each app group by its name.- data-vault-app={indent === 0 ? label : undefined}- onClick={onOpen}- className={cn("flex h-10 items-center gap-2.5 rounded-lg px-3 hover:bg-foreground/[0.04]", indent === 1 && "ml-6")}- >- <span onClick={(e) => e.stopPropagation()}>- <Checkbox aria-label={`Select ${label}`} checked={triChecked(selected)} indeterminate={selected === "mixed"} onCheckedChange={onSelect} />- </span>- <Chevron className="size-3.5 shrink-0 text-muted-foreground" aria-hidden />- {icon}- <span className="min-w-0 truncate">{title}</span>- <span className="min-w-0 truncate text-xs text-muted-foreground">{detail}</span>- <span className="flex-1" />- <span className="shrink-0 text-xs text-muted-foreground">{updated}</span>- <LockButton {...lock} actions={actions} blocked={blocked} />- </div>- );-}--function ItemRow({ row, indent, send, actions, blocked }: { row: VaultRow; indent: number; send: (a: VaultAction) => void; actions: LockActions; blocked: boolean }) {- const Icon = KIND_ICON[row.kind] ?? FileIcon;- const toggle = () => send({ type: "toggle", id: row.id });- return (- <div- role="row"- aria-selected={row.selected}- data-vault-item={row.id}- onClick={toggle}- className={cn("mb-px flex h-11 items-center gap-2.5 rounded-lg px-3 transition-colors hover:bg-foreground/[0.04]", row.selected && "bg-brand-surface hover:bg-brand-surface")}- style={{ marginLeft: `${(indent - 1) * 1.5}rem` }}- >- <span onClick={(e) => e.stopPropagation()}>- <Checkbox aria-label={`Select ${row.title}`} checked={row.selected} onCheckedChange={toggle} />- </span>- <Icon className="size-4 shrink-0 text-muted-foreground" aria-label={row.kindLabel} />- <div className="min-w-0 flex-1">- <div className="truncate text-[13px] font-medium">{row.title}</div>- {row.subtitle ? <div className="truncate text-xs text-muted-foreground">{row.subtitle}</div> : null}- </div>- <span className="shrink-0 text-xs text-muted-foreground">{row.updated}</span>- <LockButton- state={row.locked ? "locked" : "unlocked"}- name={row.title}- unlockIds={row.locked && !row.identityProvider ? [row.id] : []}- lockIds={row.locked ? [] : [row.id]}- help={row.lockHelp}- actions={actions}- blocked={blocked}- />- </div>- );-}--/** The lock: closed while every use needs approval, open once unattended- * access is allowed. A click flips it for what it stands for (an item, a- * site, an app); unlocking asks first, then Touch ID once. */-function LockButton({ state, name, unlockIds, lockIds, help, actions, blocked }: LockSpec & { help?: string; actions: LockActions; blocked: boolean }) {- const Icon = state === "locked" ? LockIcon : LockOpenIcon;- const text =- help ||- (state === "unlocked" ? "Unlocked. Click to lock." : state === "mixed" ? "Some unlocked. Click to unlock the rest." : "Locked. Click to allow unattended access.");- return (- <button- type="button"- data-lock={state}- aria-label={state === "unlocked" ? `Lock ${name}` : `Unlock ${name}`}- title={text}- disabled={blocked || (state === "locked" && unlockIds.length === 0)}- onClick={(e) => {- e.stopPropagation();- if (state === "unlocked") actions.lock(lockIds);- else if (unlockIds.length) actions.unlock(unlockIds, unlockIds.length === 1 ? name : undefined);- }}- className={cn(- "flex size-6 shrink-0 items-center justify-center rounded-md outline-none hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring/60 disabled:opacity-40",- state === "locked" ? "text-muted-foreground" : "text-amber-600 dark:text-amber-400",- state === "mixed" && "opacity-60",- )}- >- <Icon className="size-3.5" />- </button>- );-}--/** What the selection can do, together: lock, unlock, delete. */-function BatchBar({- selection,- blocked,- busy,- send,- actions,- onDelete,-}: {- selection: VaultSelection;- blocked: boolean;- busy: boolean;- send: (a: VaultAction) => void;- actions: LockActions;- onDelete: (ids: string[]) => void;-}) {- return (- <div className="flex shrink-0 items-center gap-2 border-t bg-muted/60 px-8 py-2.5" data-vault-batch>- <span className="text-[13px] font-medium">{selection.title}</span>- <Button size="sm" variant="ghost" onClick={() => send({ type: "clear" })}>- Clear- </Button>- <span className="flex-1" />- <Button size="sm" variant="outline" disabled={!selection.canLock || busy} onClick={() => actions.lock(selection.lockIds)}>- <LockIcon /> Lock- </Button>- <Button- size="sm"- variant="outline"- disabled={!selection.canUnlock || blocked || busy}- title={selection.alwaysAsk > 0 ? "Identity provider sessions always ask and stay locked." : undefined}- onClick={() => actions.unlock(selection.unlockIds)}- >- <LockOpenIcon /> Unlock- </Button>- <Button size="sm" variant="outline" disabled={busy} onClick={() => onDelete(selection.ids)}>- <Trash2Icon /> Delete- </Button>- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/page.tsx b/apps/cua-spaces-web/src/legacy/components/page.tsxdeleted file mode 100644index 258ec2ed40..0000000000--- a/apps/cua-spaces-web/src/legacy/components/page.tsx+++ /dev/null@@ -1,40 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import type { ReactNode } from "react";--import { cn } from "@/lib/utils";--export function Page({ children, className }: { children: ReactNode; className?: string }) {- // The gutter is always reserved: otherwise a page that scrolls (Settings >- // General) is narrower than one that doesn't, and the centred column jumps- // sideways between them.- return (- <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">- <div className={cn("mx-auto w-full max-w-5xl px-8 pt-6 pb-16", className)}>{children}</div>- </div>- );-}--export function PageHeader({ title, description, actions }: { title: string; description?: ReactNode; actions?: ReactNode }) {- return (- <header className="mb-6 flex items-end justify-between gap-4">- <div className="min-w-0">- <h1 className="text-[22px] font-semibold tracking-[-0.01em]">{title}</h1>- {description ? <p className="mt-1 text-[13px] text-muted-foreground">{description}</p> : null}- </div>- {actions ? <div className="flex shrink-0 items-center gap-2">{actions}</div> : null}- </header>- );-}--export function EmptyState({ icon, title, children, action }: { icon: ReactNode; title: string; children?: ReactNode; action?: ReactNode }) {- return (- <div className="flex flex-col items-center justify-center rounded-2xl border border-dashed px-8 py-20 text-center">- <div className="mb-4 flex size-10 items-center justify-center rounded-xl bg-muted text-muted-foreground [&_svg]:size-5">{icon}</div>- <h2 className="text-[15px] font-semibold">{title}</h2>- {children ? <p className="mt-1.5 max-w-sm text-[13px] text-muted-foreground">{children}</p> : null}- {action ? <div className="mt-5">{action}</div> : null}- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/resources/computer-resources.tsx b/apps/cua-spaces-web/src/legacy/components/resources/computer-resources.tsxdeleted file mode 100644index 206948c016..0000000000--- a/apps/cua-spaces-web/src/legacy/components/resources/computer-resources.tsx+++ /dev/null@@ -1,68 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { Link } from "@tanstack/react-router";--import { hostResources, type Machine, type ResourcesSnapshot } from "@/bridge";-import { thisComputerLabel } from "@/lib/host-labels";-import { lowDiskWarning, size } from "@/lib/resources";--/** One thing on a computer that needs action, as Home says it. */-export interface ComputerWarning {- /** `disk`; the same line takes permissions, updates and the budget once- * the app reports them per computer. */- kind: "disk";- machineId: string;- text: string;- level: "low" | "critical";- /** This computer: its Spaces can be sorted by what they use. */- local: boolean;-}--/**- * What needs action on your computers, nothing else: today a disk nearly or- * completely full ("Disk almost full on This Mac (12 GB left)"). A computer- * that is just offline is not a warning, and nothing shows while all is well.- *- * TODO: permissions needed, an update required and a budget- * reached go through this same line once the app reports them per computer.- */-export function computerWarnings(snapshot: ResourcesSnapshot | null, machines: readonly Machine[]): ComputerWarning[] {- const out: ComputerWarning[] = [];- for (const m of machines) {- const host = hostResources(snapshot, m);- if (!host) continue;- const name = m.current ? thisComputerLabel() : m.name;- const disk = lowDiskWarning(host, name);- if (!disk) continue;- out.push({- kind: "disk",- machineId: m.id,- level: disk.level,- local: Boolean(m.current),- text: disk.level === "critical" ? `Disk full on ${name} (${size(host.diskFree)} left)` : `Disk almost full on ${name} (${size(host.diskFree)} left)`,- });- }- return out;-}--/** Home's warning lines: one quiet row each, only while there is one. */-export function ComputerWarnings({ snapshot, machines }: { snapshot: ResourcesSnapshot | null; machines: readonly Machine[] }) {- const warnings = computerWarnings(snapshot, machines);- if (!warnings.length) return null;- return (- <section data-computer-warnings="" aria-label="Needs attention" className="mb-4 divide-y divide-foreground/10 border-y border-foreground/10">- {warnings.map((w) => (- <p key={`${w.kind}:${w.machineId}`} role="status" data-computer-warning={w.kind} data-low-disk={w.level} className="flex items-center gap-2.5 py-2 text-[13px] text-muted-foreground">- <span aria-hidden className={w.level === "critical" ? "size-1.5 shrink-0 rounded-full bg-destructive" : "size-1.5 shrink-0 rounded-full bg-[#d18a12]"} />- <span className="min-w-0 flex-1">{w.text}</span>- {w.local ? (- <Link to="/spaces" search={{ sort: "size" }} data-see-space-use="" className="shrink-0 text-[13px] text-muted-foreground underline decoration-foreground/30 underline-offset-2 hover:text-foreground">- See what’s using space- </Link>- ) : null}- </p>- ))}- </section>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/resources/meters.tsx b/apps/cua-spaces-web/src/legacy/components/resources/meters.tsxdeleted file mode 100644index 2f7849e062..0000000000--- a/apps/cua-spaces-web/src/legacy/components/resources/meters.tsx+++ /dev/null@@ -1,77 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { Link } from "@tanstack/react-router";--import { CuaKey } from "@/components/cua-key";-import { Button } from "@/components/ui/button";-import type { Meter } from "@/lib/resources";-import { cn } from "@/lib/utils";--/** A thin bar, 0 to 1. Blue; amber when the disk runs low; red when it's out. */-export function Bar({ fill, tone, className }: { fill: number; tone?: Meter["tone"]; className?: string }) {- return (- <div className={cn("h-1 overflow-hidden rounded-full bg-foreground/10", className)}>- <div- data-bar-fill={Math.round(fill * 100)}- className={cn("h-full rounded-full transition-[width] duration-500 ease-out", tone === "critical" ? "bg-destructive" : tone === "warning" ? "bg-warning" : "bg-brand-strong")}- style={{ width: `${Math.max(fill > 0 ? 2 : 0, fill * 100)}%` }}- />- </div>- );-}--/** "Processor 12 cores · 38% busy", with its bar under it. */-export function MeterRow({ meter }: { meter: Meter }) {- return (- <div data-meter={meter.label} className="min-w-0">- <div className="flex items-baseline justify-between gap-3 text-xs">- <span className="shrink-0 text-muted-foreground">{meter.label}</span>- <span className="truncate font-medium tabular-nums">{meter.value}</span>- </div>- <Bar fill={meter.fill} tone={meter.tone} className="mt-1.5" />- </div>- );-}--/** Three short meters in a row, value over bar, for a Space's tile. */-export function CompactMeters({ meters, className }: { meters: Meter[]; className?: string }) {- return (- <div data-space-meters="" className={cn("grid grid-cols-3 gap-2.5", className)}>- {meters.map((m) => (- <div key={m.label} data-meter={m.label} title={`${m.label}: ${m.help ?? m.value}`} className="min-w-0">- <div className="truncate text-2xs text-muted-foreground tabular-nums">{m.value}</div>- <Bar fill={m.fill} tone={m.tone} className="mt-1" />- </div>- ))}- </div>- );-}--/**- * "This Mac is almost out of space. Delete old Spaces or snapshots.", with- * the Cua key and "See what's using space" (the Spaces list, biggest- * first). `compact` drops the second line, for inside a panel.- */-export function LowDiskWarning({ warning, compact = false, className }: { warning: { level: "low" | "critical"; title: string; detail: string }; compact?: boolean; className?: string }) {- return (- <div- role="status"- data-low-disk={warning.level}- className={cn(- "flex items-center gap-3 px-4 py-3",- warning.level === "critical" ? "bg-destructive/10" : "bg-warning/15",- className,- )}- >- <CuaKey size={24} />- <div className="min-w-0 flex-1">- <p className="text-[13px] font-semibold">{warning.title}</p>- {compact ? null : <p className="mt-0.5 text-xs text-muted-foreground">{warning.detail}</p>}- </div>- <Button size="sm" variant="outline" data-see-space-use="" render={<Link to="/spaces" search={{ sort: "size" }} />}>- See what’s using space- </Button>- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/resources/space-resources-panel.tsx b/apps/cua-spaces-web/src/legacy/components/resources/space-resources-panel.tsxdeleted file mode 100644index 20d0bb0545..0000000000--- a/apps/cua-spaces-web/src/legacy/components/resources/space-resources-panel.tsx+++ /dev/null@@ -1,95 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { useBridge, type ComputerResources, type SpaceResources } from "@/bridge";-import { lowDiskWarning, spacePanel, type DiskFitView, type SpacePanelInput, type SpacePanelView } from "@/lib/resources";-import { cn } from "@/lib/utils";--import { Bar, LowDiskWarning } from "@/legacy/components/resources/meters";--/**- * A Space's numbers on its page: Processor, Memory and Space for files,- * each a title, the main number, the one "Given ..." line and a bar, then- * "How it fits on this Mac". The words are the core's- * (`resources.spacePanel`); a TypeScript stand-in answers only without it.- */-export function SpaceResourcesPanel({- space,- name,- host,- computer,- spaces,- baseName,-}: {- space: SpaceResources;- /** The Space's name ("macOS 1"). */- name: string;- /** Its computer's numbers, when it sent them. */- host: ComputerResources | null;- /** "this Mac" (`thisComputerText`), or the other computer's name. */- computer: string;- /** Every Space on that computer, for how it fits. */- spaces: SpaceResources[];- /** Its base image's system ("Ubuntu 24.04"), when known. */- baseName: string | null;-}) {- const { core } = useBridge();- const input: SpacePanelInput = { space, name, host, computer, spaces, baseName };- const view = core.tryCall<SpacePanelView>("resources.spacePanel", { input }) ?? spacePanel(input);- return (- <section data-space-resources="" aria-label="Resources" className="mt-6">- <div className="grid gap-4 md:grid-cols-3">- {view.cards.map((c) => (- <div key={c.label} data-resource-card={c.label} className="rounded-xl border bg-card p-4 shadow-xs">- <h3 className="text-xs text-muted-foreground">{c.label}</h3>- <p className="mt-1.5 text-xl leading-tight font-semibold tracking-[-0.01em] tabular-nums">{c.value}</p>- {c.given ? <p className="mt-1 text-xs text-muted-foreground">{c.given}</p> : null}- {c.fraction != null ? <Bar fill={c.fraction} className="mt-3.5" /> : null}- </div>- ))}- </div>- {host && view.fit ? <DiskFit fit={view.fit} host={host} computer={computer} /> : null}- </section>- );-}--const SWATCH: Record<string, string> = {- yours: "bg-muted-foreground/60",- thisSpace: "bg-brand-strong",- otherSpaces: "bg-brand/45",- base: "bg-success/60",- free: "border bg-foreground/10",-};--/** "How it fits on this Mac": your own files, this Space, other Spaces, each shared base once, free. */-function DiskFit({ fit, host, computer }: { fit: DiskFitView; host: ComputerResources; computer: string }) {- const warning = lowDiskWarning(host, computer.charAt(0).toUpperCase() + computer.slice(1));- const bar = fit.parts.filter((p) => p.kind !== "free");- return (- <div data-disk-fit="" className="mt-4 rounded-xl border bg-card p-4 shadow-xs">- <div className="flex items-baseline justify-between gap-3">- <h3 className="text-[13px] font-semibold">How it fits on {computer}</h3>- <span className="text-xs text-muted-foreground tabular-nums">{fit.total}</span>- </div>- <div className="mt-3 flex h-2 overflow-hidden rounded-full bg-foreground/10" role="img" aria-label={fit.parts.map((p) => `${p.label} ${p.value}`).join(", ")}>- {bar.map((p) => (- <div key={p.key} className={cn("h-full", SWATCH[p.kind])} style={{ width: `${p.fraction * 100}%` }} />- ))}- </div>- <ul className="mt-3 flex flex-wrap gap-x-5 gap-y-1.5 text-xs">- {fit.parts.map((p) => (- <li key={p.key} data-disk-part={p.kind === "base" ? "base" : p.key} className="flex items-center gap-1.5 tabular-nums">- <span className={cn("size-2 rounded-xs", SWATCH[p.kind])} aria-hidden />- {/* One inline run, so the flex gap only parts the swatch from the words. */}- <span>- {p.label} · {p.value}- {p.detail ? <span className="text-muted-foreground">, {p.detail}</span> : null}- </span>- </li>- ))}- </ul>- {fit.note ? <p data-disk-fit-note="" className="mt-3 text-xs text-muted-foreground">{fit.note}</p> : null}- {warning ? <LowDiskWarning warning={warning} compact className="mt-4 rounded-lg border" /> : null}- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/settings-group.tsx b/apps/cua-spaces-web/src/legacy/components/settings-group.tsxdeleted file mode 100644index 2774fb79cf..0000000000--- a/apps/cua-spaces-web/src/legacy/components/settings-group.tsx+++ /dev/null@@ -1,27 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import type { ReactNode } from "react";--export function SettingsGroup({ title, children }: { title: string; children: ReactNode }) {- return (- <section className="mb-8">- <h2 className="mb-2 px-1 text-xs font-semibold text-muted-foreground">{title}</h2>- <div className="divide-y overflow-hidden rounded-xl border bg-card shadow-xs">{children}</div>- </section>- );-}--export function SettingsRow({ label, description, control, htmlFor }: { label: ReactNode; description?: ReactNode; control: ReactNode; htmlFor?: string }) {- return (- <div className="flex min-h-12 items-center justify-between gap-6 px-4 py-2.5">- <div className="min-w-0">- <label htmlFor={htmlFor} className="block text-[13px]">- {label}- </label>- {description ? <p className="mt-0.5 text-xs text-muted-foreground">{description}</p> : null}- </div>- <div className="shrink-0">{control}</div>- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/shell/sidebar.tsx b/apps/cua-spaces-web/src/legacy/components/shell/sidebar.tsxdeleted file mode 100644index f3c6a505aa..0000000000--- a/apps/cua-spaces-web/src/legacy/components/shell/sidebar.tsx+++ /dev/null@@ -1,381 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { Link } from "@tanstack/react-router";-import { useEffect, useRef, useState, type PointerEvent, type ReactNode } from "react";--import { Loader2Icon, LogOutIcon, TriangleAlertIcon } from "lucide-react";--import type { SignInFooter, Space } from "@/bridge";-import { spokenName } from "@/bridge/space-names";--import { signInFooter, useBridge, useFeatureRecorded, useMachines, useNotifications, useRelayUsageView, useSession, useSpaces, useTrackPlanClick } from "@/bridge";-import { CuaKey } from "@/components/cua-key";-import { Button } from "@/components/ui/button";-import { toast } from "@/components/ui/toast";-import { Tooltip } from "@/components/ui/tooltip";-import { bindingFor } from "@/lib/keybindings";-import { realSpaces, spaceState } from "@/lib/spaces";-import { cn } from "@/lib/utils";-import { SIDEBAR_DEFAULT, useUiStore } from "@/stores/ui";-import { Shortcut } from "@/components/ui/kbd";-import { SignInLink } from "@/components/sign-in-link";-import { useNavItems } from "@/components/shell/nav";-import { SidebarUpdateButton } from "@/components/shell/update-indicator";-import { SidebarGetStarted } from "@/legacy/components/getting-started";--export function Sidebar() {- const width = useUiStore((s) => s.sidebarWidth);- const { data: spaces, listStatus } = useSpaces();- const { data: machines } = useMachines();- const notifications = useNotifications();- // No count before the list was read (not "0" while the daemon starts); while computers still answer, the- // Spaces known so far.- const spacesCount = spaces && listStatus.loaded ? realSpaces(spaces).length : undefined;- const counts: Partial<Record<string, number>> = { "/spaces": spacesCount, "/machines": machines?.length };- const navItems = useNavItems();- const unread = notifications.data?.unread ?? 0;-- return (- <aside- style={{ width }}- className="glass relative flex h-full shrink-0 flex-col border-r bg-sidebar text-sidebar-foreground"- aria-label="Sidebar"- >- {/* Room for the top bar and traffic lights; draggable like the title bar. */}- <div className="app-drag h-(--titlebar-height) shrink-0" />- <nav className="flex flex-col gap-px px-2.5">- {navItems.map((item) => {- // A host without the feed has no Notifications page.- if (item.to === "/notifications" && notifications.unsupported) return null;- const shortcut = item.command ? bindingFor(item.command) : undefined;- return (- <Link- key={item.to}- to={item.to}- className="group flex h-7 items-center gap-2.5 rounded-md px-2 text-[13px] outline-none hover:bg-foreground/5 focus-visible:ring-2 focus-visible:ring-ring/60 data-[status=active]:bg-foreground/[0.07] data-[status=active]:font-medium data-[status=active]:text-foreground dark:data-[status=active]:bg-white/[0.08]"- >- {({ isActive }) => (- <>- <item.icon className={cn("size-4 text-muted-foreground", isActive && "text-brand-strong")} strokeWidth={1.75} />- <span className="flex-1 truncate">{item.label}</span>- {item.to === "/notifications" && unread > 0 ? (- // The Cua key says they're Cua's; the count, in plain text, says how many are unread.- <span data-unread-badge className="flex items-center gap-1" aria-label={`${unread} unread`}>- <CuaKey size={16} />- <span className="text-2xs font-medium tabular-nums text-foreground">{unread}</span>- </span>- ) : null}- {counts[item.to] !== undefined ? (- <span className="text-2xs tabular-nums text-muted-foreground group-hover:hidden">{counts[item.to]}</span>- ) : null}- {shortcut ? <Shortcut spec={shortcut} className="hidden opacity-70 group-hover:inline-flex" /> : null}- </>- )}- </Link>- );- })}- </nav>- <div className="mt-auto">- <SidebarCreating spaces={spaces ?? []} />- <SidebarGetStarted />- <AccountFooter trailing={<SidebarUpdateButton />} />- </div>- <ResizeHandle />- </aside>- );-}--/** Spaces being made, wherever the user is (a create started in the first- * run keeps going after it): the name, the progress line and a bar. Opens- * the Space's row. */-function SidebarCreating({ spaces }: { spaces: Space[] }) {- const making = spaces.filter((s) => spaceState(s) === "creating");- if (making.length === 0) return null;- return (- <div className="flex flex-col gap-1.5 px-2.5 pb-2" data-sidebar-creating="">- {making.slice(0, 2).map((s) => {- const p = s.progress;- const fraction = p ? Math.max(0, Math.min(1, p.permille / 1000)) : 0;- return (- <Link- key={s.id}- to="/spaces"- className="block rounded-lg border bg-background/70 px-3 py-2 text-left outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring/60"- data-sidebar-creating-row={s.id}- >- <div className="text-2xs font-medium text-muted-foreground">Making</div>- <div className="truncate text-xs font-medium">{spokenName(s.name)}</div>- <div className="truncate text-2xs text-muted-foreground">{p?.transfer ?? p?.label ?? "Starting…"}</div>- <div className="mt-1.5 h-1 overflow-hidden rounded-full bg-foreground/10" role="progressbar" aria-label={`Making ${s.name}`} aria-valuenow={Math.round(fraction * 100)} aria-valuemin={0} aria-valuemax={100}>- <div className="h-full rounded-full bg-brand transition-[width]" style={{ width: `${Math.round(fraction * 100)}%` }} />- </div>- </Link>- );- })}- </div>- );-}--/** The account and its sign-in, every state in one place (the core's- * `signIn.footer`): signed in as, waiting for the browser with the code,- * Open again and Cancel, or why it failed with Try again and a toast. And a- * way back into a first run left halfway. `trailing` (the update button)- * sits at the far right of its first row. */-export function AccountFooter({ trailing }: { trailing?: ReactNode }) {- const { core } = useBridge();- const { data: session, signIn, signOut, cancelSignIn, openExternal } = useSession();- const plan = useRelayUsageView()?.planCard;- const trackPlanClick = useTrackPlanClick();- const [details, setDetails] = useState(false);- const footer = session- ? signInFooter(core, {- identity: session.signedIn ? (session.identity ?? "") : null,- cloudConfigured: session.account.configured,- canSignIn: true,- signIn: session.signIn,- hasUrl: Boolean(session.signInUrl),- })- : null;- useSignInFailureToast(footer);- // A browser sign-in that has not come back for a while: offer a code.- const waitingOnBrowser = footer?.state === "waiting" && !footer.code;- const stuck = useAfter(waitingOnBrowser, STILL_WAITING_MS);- useFeatureRecorded("sign_in_still_waiting", stuck);- // The last attempt used a code: another code would not help.- const triedCode = useRef(false);- if (footer?.state === "waiting" && footer.code) triedCode.current = true;- if (!session || !footer) return <div className="mt-auto flex h-12 items-center justify-end border-t px-3">{trailing}</div>;-- const unfinished = !session.onboarding.completed;- const run = (f: () => Promise<unknown>, what: string) =>- f().catch((e: unknown) => toast(what, { description: e instanceof Error ? e.message : String(e) }));- // A failure is shown here with its reason (and the toast): nothing to add.- const startSignIn = () => {- setDetails(false);- triedCode.current = false;- void signIn().catch(() => {});- };- // For when the browser never gets back to the app (another browser, a- // blocked connection): a code to type on any device.- const startWithCode = () => {- setDetails(false);- void signIn({ code: true }).catch(() => {});- };- const identity = footer.identity || (session.signedIn ? "Signed in" : null);-- return (- <div className="mt-auto border-t px-3 py-2.5" data-signin={footer.state}>- {unfinished ? (- <Link to="/onboarding" className="mb-2 block text-xs text-muted-foreground hover:text-foreground">- Finish setting up- </Link>- ) : null}- {footer.state === "signedIn" && identity ? (- <div className="flex items-center gap-2.5">- <div className="flex size-6 shrink-0 items-center justify-center rounded-full bg-muted text-2xs font-semibold text-muted-foreground uppercase">- {identity.slice(0, 1)}- </div>- <div className="min-w-0 flex-1 leading-tight">- <div className="truncate text-xs" title={footer.text} data-signin-identity="">- <span className="block text-2xs text-muted-foreground">Signed in as </span>- <span className="block truncate font-medium">{identity}</span>- </div>- {plan?.primary ? (- // The current plan, always visible; on Free it opens Pro's checkout.- <button- type="button"- data-account-plan={plan.plan}- className="block max-w-full truncate text-left text-2xs text-muted-foreground hover:text-foreground"- onClick={() => {- trackPlanClick("account_menu");- void openExternal(plan.primary!.url.replace("from=app_plan_card", "from=app_account_menu")).catch(() => {});- }}- >- {plan.label}- {plan.plan === "free" ? " · Upgrade" : ""}- </button>- ) : null}- </div>- {session.account.authMode === "user" ? (- <Tooltip content="Sign out" side="top">- <Button variant="ghost" size="icon-sm" aria-label="Sign out" onClick={() => void run(signOut, "Couldn't sign out")}>- <LogOutIcon className="size-3.5 text-muted-foreground" />- </Button>- </Tooltip>- ) : null}- {trailing}- </div>- ) : footer.state === "starting" || footer.state === "waiting" ? (- // The code to confirm, the page to open again if the tab was- // closed, and a way out (it also ends by itself, with a reason).- <div>- <p className="flex items-center gap-2 text-xs" role="status">- <Loader2Icon className="size-3.5 shrink-0 animate-spin text-muted-foreground" aria-hidden />- <span className="min-w-0 flex-1 truncate">{footer.text}</span>- <span className="shrink-0">{trailing}</span>- </p>- <div className="mt-1 flex flex-wrap items-center gap-x-1 pl-5.5 text-2xs text-muted-foreground">- {footer.code ? (- <>- <span className="select-text">- {footer.codeLabel} <span className="font-mono font-semibold text-foreground">{footer.code}</span>- </span>- <span aria-hidden>·</span>- </>- ) : null}- {footer.reopenLabel && session.signInUrl ? (- <>- <button- type="button"- className="underline underline-offset-2 hover:text-foreground"- onClick={() => void openExternal(session.signInUrl!).catch(() => {})}- data-signin-reopen=""- >- {footer.reopenLabel}- </button>- <span aria-hidden>·</span>- </>- ) : null}- {footer.cancelLabel ? (- <button type="button" className="underline underline-offset-2 hover:text-foreground" onClick={() => cancelSignIn()} data-signin-cancel="">- {footer.cancelLabel}- </button>- ) : null}- </div>- {stuck ? (- <div className="mt-1.5 pl-5.5 text-2xs text-muted-foreground" data-signin-stuck="">- <p>Still waiting? If the page won't finish, get a code and sign in from any browser or phone.</p>- <button type="button" className="mt-0.5 underline underline-offset-2 hover:text-foreground" onClick={startWithCode} data-signin-code="">- Get a code instead- </button>- </div>- ) : null}- {/* No browser opened: the page, to copy to any device. */}- {session.signIn.kind === "waiting" && session.signIn.opened === false && session.signInUrl ? (- <SignInLink url={session.signInUrl} compact />- ) : null}- </div>- ) : footer.state === "failed" ? (- <div role="alert">- <p className="flex items-start gap-2 text-xs">- <TriangleAlertIcon className="mt-px size-3.5 shrink-0 text-destructive" aria-hidden />- <span data-signin-reason={footer.reason ?? "unknown"}>{footer.text}</span>- </p>- <div className="mt-2 flex items-center gap-3 pl-5.5">- <Button size="sm" onClick={startSignIn} data-signin-retry="">- {footer.actionLabel}- </Button>- {footer.reason === "notConfirmed" && !triedCode.current ? (- <button- type="button"- className="text-2xs text-muted-foreground underline underline-offset-2 hover:text-foreground"- onClick={startWithCode}- data-signin-code=""- >- Get a code instead- </button>- ) : null}- {footer.detail ? (- <button- type="button"- className="text-2xs text-muted-foreground underline underline-offset-2 hover:text-foreground"- aria-expanded={details}- onClick={() => setDetails((d) => !d)}- data-signin-details=""- >- {footer.detailsLabel}- </button>- ) : null}- <span className="ml-auto">{trailing}</span>- </div>- {details && footer.detail ? (- <pre className="mt-2 max-h-28 overflow-auto rounded-md bg-muted px-2 py-1.5 font-mono text-2xs break-words whitespace-pre-wrap text-muted-foreground select-text">- {footer.detail}- </pre>- ) : null}- </div>- ) : (- <div className="flex items-center justify-between gap-2">- <span className="truncate text-xs text-muted-foreground">{footer.text}</span>- <div className="flex shrink-0 items-center gap-1.5">- {footer.actionLabel ? (- <Button variant="outline" size="sm" onClick={startSignIn}>- {footer.actionLabel}- </Button>- ) : null}- {trailing}- </div>- </div>- )}- </div>- );-}--/** A failed sign-in also toasts, once per failure, so it is seen wherever- * the person is looking. */-/** How long a browser sign-in waits before the page offers a code. */-const STILL_WAITING_MS = 45_000;--/** True once `active` has stayed true for `ms`; false again when it stops. */-function useAfter(active: boolean, ms: number): boolean {- const [late, setLate] = useState(false);- useEffect(() => {- if (!active) {- setLate(false);- return;- }- const t = setTimeout(() => setLate(true), ms);- return () => clearTimeout(t);- }, [active, ms]);- return late;-}--function useSignInFailureToast(footer: SignInFooter | null) {- const shown = useRef<string | null>(null);- const key = footer?.state === "failed" ? `${footer.reason}:${footer.text}:${footer.detail ?? ""}` : null;- useEffect(() => {- if (!key || !footer?.toast) {- shown.current = key;- return;- }- if (shown.current === key) return;- shown.current = key;- toast(footer.toast.title, { description: footer.toast.body ?? undefined, type: "error", group: "sign-in" });- }, [key, footer]);-}--function ResizeHandle() {- const setWidth = useUiStore((s) => s.setSidebarWidth);- const start = useRef<{ x: number; width: number } | null>(null);-- const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {- e.currentTarget.setPointerCapture(e.pointerId);- start.current = { x: e.clientX, width: useUiStore.getState().sidebarWidth };- };- const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {- if (start.current) setWidth(start.current.width + e.clientX - start.current.x);- };- const onPointerUp = () => {- start.current = null;- };-- return (- <div- role="separator"- aria-orientation="vertical"- aria-label="Resize sidebar"- tabIndex={0}- onPointerDown={onPointerDown}- onPointerMove={onPointerMove}- onPointerUp={onPointerUp}- onDoubleClick={() => setWidth(SIDEBAR_DEFAULT)}- onKeyDown={(e) => {- const w = useUiStore.getState().sidebarWidth;- if (e.key === "ArrowLeft") setWidth(w - 16);- if (e.key === "ArrowRight") setWidth(w + 16);- }}- className="app-no-drag absolute top-0 -right-1 z-10 h-full w-2 cursor-col-resize outline-none after:absolute after:inset-y-0 after:left-1/2 after:w-px after:bg-transparent after:transition-colors hover:after:bg-brand/60 focus-visible:after:bg-brand"- />- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/space-detail/facts.tsx b/apps/cua-spaces-web/src/legacy/components/space-detail/facts.tsxdeleted file mode 100644index 99d04a644f..0000000000--- a/apps/cua-spaces-web/src/legacy/components/space-detail/facts.tsx+++ /dev/null@@ -1,76 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { CheckIcon, CopyIcon, TriangleAlertIcon } from "lucide-react";-import { useEffect, useState } from "react";--import type { SpaceFact } from "@/bridge";-import { SettingsGroup } from "@/legacy/components/settings-group";-import { Tooltip } from "@/components/ui/tooltip";--/** A Space's facts as the core lists them (`sidebar.detail`): Status,- * Image, Identifier, System, Kind, Architecture, Memory, Storage. */-export function FactList({ title, facts }: { title: string; facts: SpaceFact[] }) {- return (- <SettingsGroup title={title}>- {facts.map((f) => (- <FactRow key={f.label} fact={f} />- ))}- </SettingsGroup>- );-}--function FactRow({ fact }: { fact: SpaceFact }) {- // The tooltip holds the full value, and an image's digest on its own line.- const help = fact.help && fact.help !== fact.value ? fact.help : null;- const value = (- <span data-fact-value className="min-w-0 truncate text-right text-[13px] select-text">- {fact.value}- </span>- );- return (- <div data-fact={fact.label} className="flex min-h-10 items-center justify-between gap-6 px-4 py-2">- <span className="shrink-0 text-[13px] text-muted-foreground">{fact.label}</span>- <span className="flex min-w-0 items-center gap-1.5" data-help={help ?? undefined}>- {help ? (- <Tooltip content={<span className="block max-w-sm break-all whitespace-pre-line">{help}</span>}>{value}</Tooltip>- ) : (- value- )}- {fact.warning ? (- <Tooltip content={fact.warning.help}>- <span data-fact-warning={fact.warning.help} aria-label={fact.warning.help} role="img" className="inline-flex shrink-0 text-warning">- <TriangleAlertIcon className="size-3.5" />- </span>- </Tooltip>- ) : null}- {fact.copy ? <CopyButton copy={fact.copy} /> : null}- </span>- </div>- );-}--function CopyButton({ copy }: { copy: NonNullable<SpaceFact["copy"]> }) {- const [done, setDone] = useState(false);- useEffect(() => {- if (!done) return;- const t = setTimeout(() => setDone(false), copy.confirmMs);- return () => clearTimeout(t);- }, [done, copy.confirmMs]);- const label = done ? copy.doneHelp : copy.help;- return (- <Tooltip content={label}>- <button- type="button"- data-copy-text={copy.text}- aria-label={label}- onClick={() => {- void navigator.clipboard?.writeText(copy.text).then(() => setDone(true), () => {});- }}- className="inline-flex size-6 shrink-0 cursor-default items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"- >- {done ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}- </button>- </Tooltip>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/space-detail/stream-surface.tsx b/apps/cua-spaces-web/src/legacy/components/space-detail/stream-surface.tsxdeleted file mode 100644index d5ebd597a3..0000000000--- a/apps/cua-spaces-web/src/legacy/components/space-detail/stream-surface.tsx+++ /dev/null@@ -1,313 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { AppWindowIcon } from "lucide-react";-import { useEffect, useRef, useState, type ReactNode } from "react";--import { useDesktopCover, useSettings, useSpaces, useSpaceThumbnail, type DesktopCover, type MachineAccessNotice, type SpaceOs, type StreamPhase } from "@/bridge";-import { OsIcon } from "@/components/os-icon";-import { Button } from "@/components/ui/button";-import { Kbd } from "@/components/ui/kbd";-import { toast } from "@/components/ui/toast";-import { useVideoSlot, videoHostPresent } from "@/components/video/use-video-slot";-import { cn, isMacPlatform } from "@/lib/utils";--/**- * Where a Space's live desktop goes.- *- * Layout contract:- * - One block with the app's card border and radius. The page sizes it- * (`className`); it never resizes itself, so nothing around it moves when- * video starts or stops.- * - The video fits inside at the guest display's aspect ratio- * (`aspectRatio`, also on the root as `data-aspect`), letterboxed and- * centred.- * - The root carries `data-stream-surface={spaceId}` and `data-stream-state`:- * `placeholder` (no video here), `connecting`, `live` (frames draw) or- * `failed` (the host couldn't stream it: the cover's Try again, with- * Open window; when no stream could be opened at all, an error toast says- * why, once per attempt).- * - `children` replaces the stream entirely (a create's progress, a- * stopped Space).- *- * Native video (apps/cua-spaces-macos/docs/native-video.md): when the host- * registers the `cuaVideo` handler (the SwiftUI shell, unless its- * `WebUINativeVideo` default is NO) and the Space can stream, the host draws- * the Space's desktop over the block and sends it pointer, scroll and keys.- * A line under the block says where keys go and how to take them back- * (Control+Option pressed and released alone, or a click outside). Anywhere else it is the placeholder, and the- * desktop opens in its own native window.- */-export interface StreamSurfaceProps {- spaceId: string;- /** For the placeholder's mark. */- os: SpaceOs;- /** Guest display width / height; 16:10 until known. */- aspectRatio?: number;- /** Streaming is possible (the core's `canStream`). */- canStream: boolean;- /** What shows when it can't stream (the core's `previewText`: "Not reachable"). */- previewText: string;- /** Signed in, but this device is not enrolled (the detail's `access`):- * the core's cover says why, with Connect greyed out and the action that- * fixes it, in place of everything else. */- access?: MachineAccessNotice | null;- /** The access line's action ("Enroll This Mac…"). */- onAccessAction?: () => void;- /** Shown instead of the stream (progress, stopped). */- children?: ReactNode;- className?: string;- /** Pointer and keys go to the Space (default). False only shows it (Watch). */- interactive?: boolean;-}--/** How long the desktop may take to send its first picture. After that the- * cover says it didn't, why, and offers Try again: the viewer never waits- * silently. */-export const CONNECT_TIMEOUT_MS = 20_000;-/** Why, when it timed out. */-export const CONNECT_TIMEOUT_REASON = "No picture arrived from the desktop within 20 seconds.";--/** True once `waiting` has held for `ms` without a break; a new `key` (another- * Space, or Try again) starts the wait over. */-function useTimedOut(waiting: boolean, ms: number, key: string): boolean {- const [over, setOver] = useState<string | null>(null);- useEffect(() => {- if (!waiting) return;- const t = setTimeout(() => setOver(key), ms);- return () => clearTimeout(t);- }, [waiting, ms, key]);- return waiting && over === key;-}--/** The root's radius (`rounded-xl`) and border, for the native layer's clip. */-const SURFACE_RADIUS = 12;-const SURFACE_BORDER = 1;--export function StreamSurface({ spaceId, os, aspectRatio = 16 / 10, canStream, previewText, access, onAccessAction, children, className, interactive = true }: StreamSurfaceProps) {- const ref = useRef<HTMLDivElement | null>(null);- const settings = useSettings();- const autoConnect = settings.data?.values.autoConnect ?? true;- // Nothing opens before the setting is read (it may say wait for Connect).- const settingsRead = settings.data !== undefined || settings.error != null;- // Connect (or Try again) pressed for this Space; a new attempt opens the- // stream again (`SpaceDetailView.connectRequested` and `press`).- const [pressed, setPressed] = useState<{ spaceId: string; attempt: number } | null>(null);- const requested = pressed?.spaceId === spaceId;- const attempt = requested ? pressed.attempt : 0;- const videoHere = videoHostPresent();- // The page's own content (a create's progress, a stopped Space) replaces- // the stream, unless this device may not connect at all.- const replaced = children != null && !access;- const wanted = canStream && !replaced && !access && ((settingsRead && autoConnect) || requested);- const slot = useVideoSlot(ref, {- active: wanted,- attempt,- spaceId,- tier: "full",- interactive,- radius: SURFACE_RADIUS,- inset: SURFACE_BORDER,- os,- });- // 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 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);- const press = () => setPressed({ spaceId, attempt: attempt + (cover.kind === "status" ? 1 : 0) });- const { data: spaces, openSpace } = useSpaces();- const name = spaces?.find((s) => s.id === spaceId)?.name ?? spaceId;- // No stream could be opened (the SwiftUI detail's provider failure): the- // cover offers Try again, and the reason shows once per attempt, as that- // detail's banner ("Could not open …"). Nothing asks again by itself: a- // poll or an approval leaves the failure as it is.- const openFailure = slot?.phase === "failed" && slot.opening ? (slot.reason ?? "") : null;- useEffect(() => {- if (openFailure === null) return;- toast(`Could not open ${name}`, { description: openFailure || undefined, type: "error" });- // eslint-disable-next-line react-hooks/exhaustive-deps -- once per failed attempt (each starts as connecting), not per rename- }, [openFailure]);- const open = () =>- openSpace(spaceId).then(- () => toast(`Opening ${name}`, { description: "Its desktop opens in a separate window." }),- (e: unknown) => toast(`Couldn't open ${name}`, { description: e instanceof Error ? e.message : String(e), type: "error" }),- );- // Where the host draws video, the core's cover (or nothing over live- // video); elsewhere the placeholder, and the desktop in its own window.- // Asked for video and got none: this shell has none for this page (no- // cua, sample data), so the placeholder after all.- const noVideoHere = wanted && slot === null;- const covered = !replaced && (Boolean(access) || (videoHere && !noVideoHere));- const state = slot ? (timedOut ? "failed" : slot.phase) : covered && cover.kind === "connecting" ? "connecting" : "placeholder";- // Why the cover says it could not connect, on the cover itself.- const reason = timedOut ? CONNECT_TIMEOUT_REASON : slot?.phase === "failed" ? (slot.reason ?? null) : null;- const dark = covered && (Boolean(thumbnail) || cover.kind !== "status");- return (- <>- <div- ref={ref}- data-stream-surface={spaceId}- data-stream-state={state}- data-aspect={aspectRatio.toFixed(4)}- className={cn("relative w-full overflow-hidden rounded-xl border shadow-xs", dark ? "bg-black" : "bg-muted/40", className)}- >- {covered ? (- cover.kind === "stream" ? null : (- <DesktopCoverView- os={os}- cover={cover}- thumbnail={access ? null : thumbnail}- reason={cover.kind === "status" ? reason : null}- onButton={press}- onAction={onAccessAction}- onOpen={slot?.phase === "failed" ? () => void open() : undefined}- />- )- ) : (- <div className="absolute inset-0 flex flex-col items-center justify-center px-6 text-center">- {children ?? (- <>- <OsIcon os={os} className="mb-4 size-8 text-muted-foreground/30" />- {canStream ? (- <>- <p className="text-[13px] text-muted-foreground">The desktop opens in its own window.</p>- <Button className="mt-4" onClick={() => void open()}>- <AppWindowIcon /> Open window- </Button>- </>- ) : (- <p data-preview-text className="text-[13px] text-muted-foreground">- {previewText}- </p>- )}- </>- )}- </div>- )}- </div>- {slot ? (- <div data-video-focus={slot.focused ? "space" : "page"} className="mt-2 flex h-7 items-center justify-between gap-3 px-1 text-xs text-muted-foreground">- <p className="min-w-0 truncate">- {slot.phase !== "live" ? null : slot.focused ? (- <>- {isMacPlatform() ? (- <>- Keys go to this Space. Press and release <Kbd>⌃⌥</Kbd> to stop.- </>- ) : (- <>- Keys go to this Space. Press <Kbd>Ctrl+Shift+F12</Kbd> to stop.- </>- )}- </>- ) : (- "Click the desktop to control it."- )}- </p>- <div className="flex shrink-0 items-center gap-1">- {slot.phase === "live" && slot.focused ? (- <Button variant="ghost" size="sm" onClick={() => slot.setFocus(false)}>- Stop controlling- </Button>- ) : null}- {slot.phase !== "failed" ? (- <Button variant="ghost" size="sm" onClick={() => void open()}>- <AppWindowIcon /> Open in window- </Button>- ) : null}- </div>- </div>- ) : null}- </>- );-}--/**- * What the preview shows over (or instead of) the live desktop, as the- * core says (`spaces.desktopCover`, the SwiftUI app's `DesktopCoverView`):- * the Space's latest thumbnail strongly blurred and slightly dimmed, with- * "Connecting…", Connect, or a line and Try again centered on it. With no- * thumbnail: black while it connects (or waits for Connect), the card's- * quiet fill for a Space that cannot stream. Signed in but not enrolled:- * why, its action, and Connect greyed out.- */-function DesktopCoverView({- os,- cover,- thumbnail,- reason,- onButton,- onAction,- onOpen,-}: {- os: SpaceOs;- cover: DesktopCover;- thumbnail: string | null;- /** Why it could not connect, under the line. */- reason?: string | null;- onButton: () => void;- onAction?: () => void;- /** The stream failed here: its own window instead. */- onOpen?: () => void;-}) {- const dark = Boolean(thumbnail) || cover.kind !== "status";- return (- <div data-desktop-cover={cover.kind} className={cn("absolute inset-0 flex flex-col items-center justify-center px-6 text-center", dark && "dark text-white")}>- {thumbnail ? (- <>- <img data-cover-thumbnail="" src={thumbnail} alt="" aria-hidden className="absolute inset-0 size-full scale-110 object-cover blur-2xl" />- <div className="absolute inset-0 bg-black/30" />- </>- ) : null}- <div className="relative flex flex-col items-center">- {!dark ? <OsIcon os={os} className="mb-4 size-8 text-muted-foreground/30" /> : null}- {cover.text ? (- <p- data-cover-text=""- {...(cover.kind === "status" ? { "data-preview-text": "" } : {})}- className={cn("max-w-md", cover.kind === "status" ? "text-[13px]" : "text-[15px]", dark ? "text-white/70" : "text-muted-foreground")}- >- {cover.text}- </p>- ) : null}- {reason ? (- <p data-cover-reason="" className={cn("mt-1 max-w-md text-xs", dark ? "text-white/60" : "text-muted-foreground")}>- {reason}- </p>- ) : null}- {cover.action ? (- <button- type="button"- className={cn("mt-2 text-[13px] outline-none hover:underline focus-visible:underline", dark ? "text-white" : "text-brand-strong")}- onClick={onAction}- data-access-action=""- >- {cover.action}- </button>- ) : null}- {cover.button || onOpen ? (- <div className="mt-4 flex gap-2">- {cover.button ? (- <Button- size={cover.kind === "connect" ? "lg" : "default"}- disabled={cover.buttonDisabled}- title={cover.buttonHelp ?? undefined}- onClick={onButton}- data-cover-button={cover.kind === "connect" ? "connect" : "retry"}- >- {cover.button}- </Button>- ) : null}- {onOpen ? (- <Button variant="outline" onClick={onOpen}>- <AppWindowIcon /> Open window- </Button>- ) : null}- </div>- ) : null}- </div>- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/space-ready-card.tsx b/apps/cua-spaces-web/src/legacy/components/space-ready-card.tsxdeleted file mode 100644index 390d6ebfc3..0000000000--- a/apps/cua-spaces-web/src/legacy/components/space-ready-card.tsx+++ /dev/null@@ -1,134 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { useNavigate } from "@tanstack/react-router";-import { XIcon } from "lucide-react";-import { useCallback, useEffect, useState } from "react";--import { useAgents, useFeatureRecorder, type AgentSetupRow, type Space } from "@/bridge";-import { CuaKey } from "@/components/cua-key";-import { suggestedTask, type SuggestedTask } from "@/components/first-run-guide";-import { Button } from "@/components/ui/button";--const KEY = "cua.agentOffer";--type Outcome = "dismissed" | "done";--const read = (): Outcome | null => {- try {- const v = globalThis.localStorage?.getItem(KEY);- return v === "dismissed" || v === "done" ? v : null;- } catch {- return null;- }-};--/**- * The offer to connect an agent after the first Space is ready. It stays- * until the person closes it or connects an agent, then never comes back.- * Events: `agent_offer_shown` (once per install), `agent_offer_clicked`,- * `agent_offer_completed` (an agent got connected, or its request was copied).- */-export function useAgentOffer(eligible: boolean) {- const record = useFeatureRecorder();- const [outcome, setOutcome] = useState<Outcome | null>(read);- const visible = eligible && outcome === null;- useEffect(() => {- if (!visible) return;- try {- if (globalThis.localStorage?.getItem(`${KEY}.shown`)) return;- globalThis.localStorage?.setItem(`${KEY}.shown`, "1");- } catch {- // Not kept: it may count again on the next launch.- }- record("agent_offer_shown");- }, [visible, record]);- const finish = useCallback((next: Outcome) => {- try {- globalThis.localStorage?.setItem(KEY, next);- } catch {- // Not kept: it may show again on the next launch.- }- setOutcome(next);- }, []);- return {- visible,- clicked: () => record("agent_offer_clicked"),- completed: () => {- if (!visible) return;- record("agent_offer_completed");- finish("done");- },- dismiss: () => finish("dismissed"),- };-}--/** "Claude Code", "Claude Code and Codex", "Claude Code, Codex and Hermes". */-export function listNames(names: string[]): string {- return names.length < 2 ? (names[0] ?? "") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;-}--/**- * The moment a user's first Space is ready (the guided first run's success- * state, CUA-2062): it says so, names the agents found on this computer, and- * offers one real task to try (`suggestedTask`). "Try this task" opens the- * run dialog with that request (which connects an agent first if needed);- * "Open" goes to the Space. Add computer and Share stay in the checklist- * below it, and a sign-in prompt may sit under it.- */-export function SpaceReadyCard({ space, onRun, onDismiss }: { space: Space; onRun: (task: SuggestedTask) => void; onDismiss?: () => void }) {- const { agentSetup } = useAgents();- const navigate = useNavigate();- const [rows, setRows] = useState<AgentSetupRow[] | null>(null);- useEffect(() => {- let live = true;- agentSetup().then(- (r) => live && setRows(r),- () => live && setRows([]),- );- return () => {- live = false;- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- const task = suggestedTask(space);- const found = (rows ?? []).filter((r) => r.installed);- const line = found.length- ? `We found ${listNames(found.map((r) => r.name))} on this computer. Give one a task and watch it work in ${space.name}.`- : "Connect an agent such as Claude Code or Codex, give it a task, and watch it work in this Space.";-- return (- <section data-space-ready="" aria-labelledby="space-ready-title" className="mb-6 rounded-xl border bg-card px-5 py-4 shadow-xs">- <div className="flex items-start gap-4">- <CuaKey size={40} className="size-10" />- <div className="min-w-0 flex-1">- <h2 id="space-ready-title" className="text-[14px] font-semibold">- Your first Space is ready- </h2>- <p className="mt-0.5 text-xs text-muted-foreground">- {space.name} is a fresh computer, set up and running. {rows === null ? "Looking for your agents…" : line}- </p>- </div>- {onDismiss ? (- <Button data-space-ready-dismiss="" size="icon-sm" variant="ghost" aria-label="Not now" onClick={onDismiss}>- <XIcon className="size-3.5" />- </Button>- ) : null}- </div>- <div data-suggested-task="" className="mt-4 flex items-center gap-4 rounded-lg border bg-muted/40 px-4 py-3">- <div className="min-w-0 flex-1">- <p className="text-2xs font-medium text-muted-foreground">Try this first</p>- <p className="mt-0.5 text-[13px] font-medium">{task.title}</p>- <p className="mt-0.5 text-xs text-muted-foreground">{task.why}</p>- </div>- <Button variant="outline" data-space-ready-open="" onClick={() => void navigate({ to: "/spaces/$spaceId", params: { spaceId: space.id } })}>- Open {space.name}- </Button>- <Button data-space-ready-run="" disabled={rows === null} onClick={() => onRun(task)}>- Try this task- </Button>- </div>- </section>- );-}diff --git a/apps/cua-spaces-web/src/legacy/components/teleport/saved-items.tsx b/apps/cua-spaces-web/src/legacy/components/teleport/saved-items.tsxdeleted file mode 100644index d3c1c81b37..0000000000--- a/apps/cua-spaces-web/src/legacy/components/teleport/saved-items.tsx+++ /dev/null@@ -1,151 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { ChevronDownIcon, ChevronRightIcon, CookieIcon, DatabaseIcon, EyeOffIcon, FileIcon, FolderIcon, GlobeIcon, KeyRoundIcon, SearchIcon } from "lucide-react";-import type { ReactNode } from "react";--import type { TeleportStore, Tri, VaultAction, VaultRow, VaultView } from "@/bridge";-import { Button } from "@/components/ui/button";-import { Checkbox } from "@/components/ui/checkbox";-import { vaultLines, type VaultLine } from "@/lib/keyvault";--export const KIND_ICON = { cookie: CookieIcon, local_storage: DatabaseIcon, password: KeyRoundIcon, file: FileIcon } as const;--/**- * The app's saved Keyvault items, to choose from as the review's source- * (the SwiftUI review's `SavedItemsChoice`): grouped by site with- * checkboxes and search, the names behind Touch ID. The core's vault list- * keeps the selection; the review sends exactly it.- */-export function SavedItems({ view, query, teleport }: { view: VaultView; query: string; teleport: TeleportStore }) {- const send = (action: VaultAction) => teleport.sendVault(action);- if (view.namesHidden) {- return (- <div className="flex items-center gap-3 px-4 py-3" data-saved-hidden>- <EyeOffIcon className="size-4 shrink-0 text-muted-foreground" />- <p className="min-w-0 flex-1 text-[13px] text-muted-foreground">{view.hiddenNote}</p>- <Button size="sm" variant="outline" onClick={() => void teleport.showNames()}>- {view.showNamesLabel}- </Button>- </div>- );- }- // The apps' own lines (one app here) are left out: the review is about its items.- const lines = vaultLines(view).filter((l) => l.type !== "app");- return (- <>- <div className="flex items-center gap-2 border-b px-4 py-1.5">- <SearchIcon className="size-3.5 shrink-0 text-muted-foreground" />- <input- aria-label="Search saved items"- placeholder="Search saved items"- value={query}- onChange={(e) => send({ type: "query", text: e.target.value })}- className="h-7 min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground"- />- <span className="text-xs text-muted-foreground tabular-nums" data-saved-summary>- {view.selection.count} of {view.shown} selected- </span>- <button type="button" className="text-xs text-brand hover:underline" onClick={() => send({ type: "select-all" })}>- All- </button>- <button type="button" className="text-xs text-brand hover:underline" onClick={() => send({ type: "clear" })}>- None- </button>- </div>- {view.emptyText ? <p className="px-4 py-3 text-[13px] text-muted-foreground">{view.emptyText}</p> : null}- <ul className="max-h-52 divide-y overflow-y-auto" data-saved-list>- {lines.map((line) => (- <li key={line.key}>- <SavedLine line={line} send={send} />- </li>- ))}- </ul>- </>- );-}--const triChecked = (t: Tri) => t === "on";--function SavedLine({ line, send }: { line: VaultLine; send: (a: VaultAction) => void }) {- switch (line.type) {- case "site":- return (- <Group- selected={line.site.selected}- open={line.site.open}- label={`Send ${line.site.site}`}- icon={<GlobeIcon className="size-3.5 text-muted-foreground" />}- title={line.site.site}- detail={line.site.counts}- onSelect={() => send({ type: "toggle-group", key: line.site.key })}- onOpen={() => send({ type: "toggle-open", key: line.site.key })}- />- );- case "files":- return (- <Group- selected={line.files.selected}- open={line.files.open}- label="Send Files"- icon={<FolderIcon className="size-3.5 text-muted-foreground" />}- title="Files"- detail={`${line.files.count} file${line.files.count === 1 ? "" : "s"}`}- onSelect={() => send({ type: "toggle-group", key: line.files.key })}- onOpen={() => send({ type: "toggle-open", key: line.files.key })}- />- );- case "item":- return <Item row={line.row} onToggle={() => send({ type: "toggle", id: line.row.id })} />;- case "app":- return null;- }-}--function Group({- selected,- open,- label,- icon,- title,- detail,- onSelect,- onOpen,-}: {- selected: Tri;- open: boolean;- label: string;- icon: ReactNode;- title: string;- detail: string;- onSelect: () => void;- onOpen: () => void;-}) {- const Chevron = open ? ChevronDownIcon : ChevronRightIcon;- return (- <div className="flex items-center gap-2 px-4 py-2" data-saved-group={title}>- <Checkbox aria-label={label} checked={triChecked(selected)} indeterminate={selected === "mixed"} onCheckedChange={onSelect} />- <button type="button" aria-label={open ? "Collapse" : "Expand"} aria-expanded={open} onClick={onOpen} className="text-muted-foreground">- <Chevron className="size-3.5" />- </button>- {icon}- <span className="truncate text-[13px]">{title}</span>- <span className="truncate text-xs text-muted-foreground">{detail}</span>- </div>- );-}--function Item({ row, onToggle }: { row: VaultRow; onToggle: () => void }) {- const Icon = KIND_ICON[row.kind] ?? FileIcon;- return (- <label className="flex cursor-default items-center gap-2 py-2 pr-4 pl-10" data-saved-item={row.id}>- <Checkbox aria-label={`Send ${row.title}`} checked={row.selected} onCheckedChange={onToggle} />- <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-label={row.kindLabel} />- <span className="min-w-0 flex-1">- <span className="block truncate text-[13px]">{row.title}</span>- {row.subtitle ? <span className="block truncate text-xs text-muted-foreground">{row.subtitle}</span> : null}- </span>- <span className="shrink-0 text-xs text-muted-foreground">{row.updated}</span>- </label>- );-}diff --git a/apps/cua-spaces-web/src/legacy/routes/agents/index.tsx b/apps/cua-spaces-web/src/legacy/routes/agents/index.tsxdeleted file mode 100644index 5ad5ccf9db..0000000000--- a/apps/cua-spaces-web/src/legacy/routes/agents/index.tsx+++ /dev/null@@ -1,475 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { getRouteApi, Link, useNavigate } from "@tanstack/react-router";-import { ArrowLeftIcon, BotIcon, KeyRoundIcon, SettingsIcon } from "lucide-react";-import { useEffect, useState } from "react";--import {- isUnsupported,- useAgentDetail,- useAgents,- useAgentTimeline,- useFeatureRecorded,- useSession,- type AgentRunSummary,- type AgentsData,- type AgentSummary,- type AgentTab,- type AgentTimeline,-} from "@/bridge";-import { AgentPanel } from "@/components/agents/agent-panels";-import { AgentsEmpty } from "@/legacy/components/agents/agents-empty";-import { HarnessMark } from "@/components/agents/harness-mark";-import { Timeline } from "@/components/agents/timeline";-import { EmptyState, PageHeader } from "@/legacy/components/page";-import { Button } from "@/components/ui/button";-import { toast } from "@/components/ui/toast";-import {- AGENT_STATE_LABEL,- RUN_STATUS_LABEL,- agentTone,- isWaiting,- resolveSelection,- runTone,- spaceLabel,- type AgentsSelection,- type Tone,-} from "@/lib/agents";-import { needsAgentKey } from "@/lib/agent-keys";-import { relativeTime, cn } from "@/lib/utils";--const Route = getRouteApi("/agents/");--/** Public's page before the redesign (`spaces_redesign` off); its search is the real route's. */-export const LegacyAgentsPage = AgentsPage;--/** Settings → Agents, where agents get their provider keys. */-function AgentKeysLink({ size }: { size?: "sm" }) {- return (- <Button variant="outline" size={size} render={<Link to="/settings/agents" />} data-agent-keys-link>- <KeyRoundIcon /> Add a provider key- </Button>- );-}--/** Re-renders every `ms` so ages stay current. */-function useNow(ms = 30_000): number {- const [now, setNow] = useState(() => Date.now());- useEffect(() => {- const t = setInterval(() => setNow(Date.now()), ms);- return () => clearInterval(t);- }, [ms]);- return now;-}--/** Settings, Connected apps: where Cua is switched on for each coding app. */-function ConnectedAppsLink() {- const navigate = useNavigate();- return (- <Button variant="outline" onClick={() => void navigate({ to: "/settings/connectors", search: {} })} data-connected-apps-link>- <SettingsIcon /> Connected apps- </Button>- );-}--function AgentsPage() {- const search = Route.useSearch();- const navigate = useNavigate({ from: "/agents/" });- const { data, isLoading, error } = useAgents();- useFeatureRecorded("agents_page_open");- // The page opens on the overview; a run or an agent opens its own view.- const opened = Boolean(search.agent || (search.run && search.space));- const selected = resolveSelection(data, search);- const select = (next: AgentsSelection) => void navigate({ search: next, replace: false });- const empty = data !== undefined && data.agents.length === 0 && data.runs.length === 0;- const detail = opened && (selected.ref || selected.agent);-- return (- <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">- <div className="mx-auto flex min-h-full w-full max-w-5xl flex-col px-8 pt-8 pb-16">- {detail ? (- <div className="flex min-h-0 flex-1 flex-col" data-agent-view>- <Button variant="ghost" size="sm" className="mb-4 -ml-2 self-start" onClick={() => select({})} data-agents-back>- <ArrowLeftIcon /> Agents- </Button>- <div className="flex min-h-[28rem] flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-xs">- <AgentDetail- key={selected.ref ? `${selected.ref.spaceId}/${selected.ref.runId}` : selected.agent?.name}- agent={selected.agent}- run={selected.run}- runRef={selected.ref}- />- </div>- </div>- ) : (- <>- <PageHeader title="Agents" description="What your agents have done in your Spaces." actions={<ConnectedAppsLink />} />- {error ? (- <EmptyState- icon={<BotIcon />}- title={isUnsupported(error) ? "Agents aren't available here yet" : "Couldn't load agents"}- action={<AgentKeysLink />}- >- {isUnsupported(error) ? "This version of the app can't list agents. The Cua Spaces app on macOS shows them in its own window." : error.message}- </EmptyState>- ) : isLoading && !data ? null : empty ? (- <AgentsEmpty />- ) : data ? (- <Overview data={data} onSelect={select} />- ) : null}- </>- )}- </div>- </div>- );-}--/* ---- The overview ---------------------------------------------------------- */--function Overview({ data, onSelect }: { data: AgentsData; onSelect: (s: AgentsSelection) => void }) {- const now = useNow();- const navigate = useNavigate();- const waiting = data.runs.filter(isWaiting);- const openSpace = (spaceId: string) => void navigate({ to: "/spaces/$spaceId", params: { spaceId } });- return (- <div className="flex flex-col gap-8">- {waiting.length > 0 ? (- <Block title="Waiting for you" count={waiting.length} id="waiting">- {waiting.map((r) => (- <div- key={`${r.spaceId}/${r.runId}`}- data-waiting-run={r.runId}- className="flex min-h-12 items-center gap-3 px-4 py-3"- >- <HarnessMark agent={r.agent} name={r.harnessName} />- <div className="min-w-0 flex-1">- <div className="truncate text-[14px] font-medium">{r.needsYou!.title}</div>- <div className="truncate text-[13px] text-muted-foreground">{r.needsYou!.detail}</div>- </div>- <Button onClick={() => openSpace(r.spaceId)} data-waiting-open>- Open Space- </Button>- </div>- ))}- </Block>- ) : null}-- {data.canList && data.agents.length > 0 ? (- <Block title="Running" count={data.agents.length} id="running">- {data.agents.map((a) => (- <button- key={a.name}- type="button"- data-agent-row={a.name}- onClick={() => onSelect({ agent: a.name })}- className="flex min-h-12 w-full cursor-default items-center gap-3 px-4 py-3 text-left outline-none transition-colors hover:bg-foreground/[0.04] focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-inset"- >- <HarnessMark agent={a.harness} name={a.harnessName} />- <span className="min-w-0 flex-1">- <span data-row-title className="block truncate text-[14px] font-medium">- {a.name}- </span>- <span data-row-detail className="block truncate text-[13px] text-muted-foreground">- {a.detail}- </span>- </span>- <span data-row-state className="inline-flex shrink-0 items-center gap-1.5 text-[13px] text-muted-foreground">- <StatusDot tone={agentTone(a.state)} />- {AGENT_STATE_LABEL[a.state]}- </span>- <span className="w-24 shrink-0 text-right text-[13px] text-muted-foreground" title={a.lastActivityMs ? `Last saved ${relativeTime(a.lastActivityMs, now)}` : undefined}>- {a.state === "running" ? "Now" : a.lastActivityMs ? relativeTime(a.lastActivityMs, now) : ""}- </span>- </button>- ))}- </Block>- ) : null}-- <Block title="Recent runs" count={data.runs.length} id="runs" empty={data.runs.length === 0 ? "No runs yet in your running Spaces." : null}>- {data.runs.length > 0 ? (- <div role="table" aria-label="Recent runs">- <div role="row" className="grid min-h-12 grid-cols-[minmax(0,3fr)_minmax(0,2fr)_8rem_7rem_6rem] items-center gap-4 px-4 text-[13px] text-muted-foreground">- <span role="columnheader">What it did</span>- <span role="columnheader">Space</span>- <span role="columnheader">Status</span>- <span role="columnheader">Started</span>- <span role="columnheader" />- </div>- {data.runs.map((r) => {- const live = r.status === "running";- const needs = isWaiting(r);- return (- <div- key={`${r.spaceId}/${r.runId}`}- role="row"- data-run-row={r.runId}- className="grid min-h-12 grid-cols-[minmax(0,3fr)_minmax(0,2fr)_8rem_7rem_6rem] items-center gap-4 border-t px-4 py-2"- >- <div role="cell" className="flex min-w-0 items-center gap-3">- <HarnessMark agent={r.agent} name={r.harnessName} />- <span className="min-w-0">- <span data-row-title className="block truncate text-[14px] font-medium">- {r.summary || r.harnessName}- </span>- <span data-row-detail className="block truncate text-[13px] text-muted-foreground">- {r.agentName ? `${r.agentName}, ${r.harnessName}` : r.harnessName}- </span>- </span>- </div>- <div role="cell" className="min-w-0 truncate text-[13px]">- {spaceLabel(r.spaceName)}- </div>- <div role="cell" data-row-state className="inline-flex items-center gap-1.5 text-[13px]">- <StatusDot tone={needs ? "paused" : runTone(r.status)} />- {needs ? "Needs you" : RUN_STATUS_LABEL[r.status]}- </div>- <div role="cell" className="text-[13px] text-muted-foreground" title={r.startedMs ? relativeTime(r.startedMs, now) : undefined}>- {live ? "Now" : r.startedMs ? relativeTime(r.startedMs, now) : ""}- </div>- <div role="cell" className="flex justify-end">- {needs ? (- <Button size="sm" onClick={() => openSpace(r.spaceId)}>- Open Space- </Button>- ) : (- <Button size="sm" variant="outline" data-run-open onClick={() => onSelect({ space: r.spaceId, run: r.runId })}>- {live ? "Watch" : "Replay"}- </Button>- )}- </div>- </div>- );- })}- </div>- ) : null}- </Block>- {data.unread.length ? (- <div className="space-y-1">- {data.unread.map((u) => (- <p key={u.spaceId} className="text-xs text-muted-foreground">- Couldn't read runs in {spaceLabel(u.spaceName)}: {u.message}- </p>- ))}- </div>- ) : null}- </div>- );-}--/** A titled card: 32px between blocks, rows of at least 48px inside. */-function Block({ title, count, id, children, empty }: { title: string; count: number; id: string; children?: React.ReactNode; empty?: string | null }) {- return (- <section data-agents-section={id}>- <h2 className="mb-3 flex items-center gap-2 text-[15px] font-semibold">- {title}- <span className="text-[13px] font-normal tabular-nums text-muted-foreground">{count}</span>- </h2>- <div className="divide-y overflow-hidden rounded-xl border bg-card shadow-xs">- {empty ? <p className="px-4 py-3 text-[13px] text-muted-foreground">{empty}</p> : children}- </div>- </section>- );-}--const TONE_DOT: Record<Tone, string> = {- live: "bg-success",- quiet: "bg-muted-foreground/40",- paused: "bg-warning",- problem: "bg-destructive",-};--function StatusDot({ tone, className }: { tone: Tone; className?: string }) {- return (- <span className={cn("relative inline-flex size-1.5 shrink-0 rounded-full", TONE_DOT[tone], className)} aria-hidden>- {tone === "live" ? <span className="absolute inset-0 animate-ping rounded-full bg-success/60" /> : null}- </span>- );-}--/* ---- The detail ------------------------------------------------------------- */--function AgentDetail({ agent, run, runRef }: { agent: AgentSummary | null; run: AgentRunSummary | null; runRef: { spaceId: string; runId: string } | null }) {- const { pauseAgent, resumeAgent } = useAgents();- const { openExternal } = useSession();- const timeline = useAgentTimeline(runRef);- const detail = useAgentDetail(agent?.record ?? null);- const now = useNow();- const [busy, setBusy] = useState(false);- // The run's conversation, or one of the core's tabs (Memory, Routines, Access).- const [pane, setPane] = useState<"run" | AgentTab>("run");-- const harness = agent?.harnessName ?? run?.harnessName ?? "";- const space = spaceLabel(agent?.spaceName ?? run?.spaceName ?? "");- const status = timeline.status ?? run?.status ?? null;- const title = agent?.name ?? run?.summary ?? harness;- const turn = Math.max(run?.turn ?? 0, timeline.items[timeline.items.length - 1]?.turn ?? 0);- const subtitle = [- `${harness} in ${space}`,- agent && run?.summary ? run.summary : null,- turn ? `Turn ${turn}` : null,- run?.startedMs ? `started ${relativeTime(run.startedMs, now)}` : null,- ]- .filter(Boolean)- .join(" · ");-- const act = () => {- if (!agent) return;- setBusy(true);- (agent.state === "paused" ? resumeAgent(agent.name) : pauseAgent(agent.name))- .catch((e: unknown) => toast(`Couldn't ${agent.actionLabel.toLowerCase()} ${agent.name}`, { description: e instanceof Error ? e.message : String(e) }))- .finally(() => setBusy(false));- };-- return (- <>- <header className="flex items-center gap-3 border-b bg-card px-5 py-3">- <HarnessMark agent={agent?.harness ?? run?.agent ?? ""} name={harness} large />- <div className="min-w-0 flex-1">- <h2 className="truncate text-[14px] font-semibold">{title}</h2>- <p className="truncate text-xs text-muted-foreground" title={subtitle}>- {subtitle}- </p>- </div>- {agent ? (- <span className="inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">- <StatusDot tone={agentTone(agent.state)} />- {AGENT_STATE_LABEL[agent.state]}- </span>- ) : status ? (- <span className="inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">- <StatusDot tone={runTone(status)} />- {RUN_STATUS_LABEL[status]}- </span>- ) : null}- {agent ? (- <Button size="sm" variant="outline" disabled={busy} onClick={act}>- {busy ? (agent.state === "paused" ? "Resuming…" : "Pausing…") : agent.actionLabel}- </Button>- ) : null}- </header>- {agent?.lastError ? (- <div className="flex items-center gap-3 border-b bg-destructive/5 px-5 py-2" data-agent-last-error>- <p className="min-w-0 flex-1 text-xs text-destructive">{agent.lastError}</p>- {needsAgentKey(agent.lastError) ? <AgentKeysLink size="sm" /> : null}- </div>- ) : null}- {detail.view ? (- <AgentTabs- tabs={[{ tab: "run", label: "Conversation" }, ...detail.view.tabs]}- selected={pane}- onSelect={(tab) => {- setPane(tab);- if (tab !== "run") detail.act({ type: "set-tab", tab });- }}- />- ) : null}- {pane !== "run" && detail.view ? (- <AgentPanel tab={pane} detail={detail} />- ) : (- <DetailBody agent={agent} run={run} hasRun={runRef !== null} timeline={timeline} onOpenLink={(url) => void openExternal(url)} />- )}- </>- );-}--function AgentTabs({- tabs,- selected,- onSelect,-}: {- tabs: { tab: "run" | AgentTab; label: string }[];- selected: "run" | AgentTab;- onSelect: (tab: "run" | AgentTab) => void;-}) {- return (- <div role="tablist" aria-label="Agent" className="flex shrink-0 gap-1 border-b bg-card px-4">- {tabs.map((t) => (- <button- key={t.tab}- type="button"- role="tab"- aria-selected={selected === t.tab}- onClick={() => onSelect(t.tab)}- data-agent-tab={t.tab}- className={cn(- "-mb-px cursor-default border-b-2 border-transparent px-2 py-2 text-xs font-medium text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:text-foreground",- selected === t.tab && "border-foreground text-foreground",- )}- >- {t.label}- </button>- ))}- </div>- );-}--function DetailBody({- agent,- run,- hasRun,- timeline,- onOpenLink,-}: {- agent: AgentSummary | null;- run: AgentRunSummary | null;- hasRun: boolean;- timeline: AgentTimeline;- onOpenLink: (url: string) => void;-}) {- if (!hasRun) {- return (- <Centered title={agent?.state === "paused" ? `${agent.name} is paused` : "No runs yet"}>- {agent?.state === "paused"- ? `Its home is saved. Resume it to let it work in ${spaceLabel(agent.spaceName)} again.`- : `Runs show up here once ${agent?.name ?? "this agent"} starts working.`}- </Centered>- );- }- if (timeline.unsupported) {- return (- <Centered title="The conversation isn't available here">- This version of the app can list runs but can't read what they wrote. {run?.reason ? `The run is ${run.status}: ${run.reason}.` : null}- </Centered>- );- }- if (timeline.error && timeline.items.length === 0) {- return <Centered title="Couldn't read this run">{timeline.error.message}</Centered>;- }- if (timeline.isLoading && timeline.items.length === 0) return <div className="flex-1" />;- return <Timeline className="flex-1" timeline={timeline} onOpenLink={onOpenLink} footer={<RunFooter timeline={timeline} run={run} />} />;-}--function RunFooter({ timeline, run }: { timeline: AgentTimeline; run: AgentRunSummary | null }) {- const status = timeline.status ?? run?.status;- if (status === "running") {- const doing = timeline.phase === "responding" ? "Writing" : timeline.phase === "tool" ? "Using tools" : "Working";- return (- <p className="flex items-center gap-2 text-xs text-muted-foreground" role="status">- <StatusDot tone="live" />- {doing}- </p>- );- }- if (status === "failed" || status === "crashed") {- return (- <p className="text-xs text-destructive" role="status">- {RUN_STATUS_LABEL[status]}- {run?.reason ? `: ${run.reason}` : null}- </p>- );- }- if (status === "idle") {- return <p className="text-xs text-muted-foreground">Waiting for a follow-up.</p>;- }- return null;-}--function Centered({ title, children }: { title: string; children: React.ReactNode }) {- return (- <div className="flex flex-1 flex-col items-center justify-center px-8 text-center">- <h3 className="text-[14px] font-semibold">{title}</h3>- <p className="mt-1.5 max-w-sm text-[13px] text-muted-foreground">{children}</p>- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/routes/keyvault/index.tsx b/apps/cua-spaces-web/src/legacy/routes/keyvault/index.tsxdeleted file mode 100644index 44eaf38f5c..0000000000--- a/apps/cua-spaces-web/src/legacy/routes/keyvault/index.tsx+++ /dev/null@@ -1,17 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { getRouteApi } from "@tanstack/react-router";--import { KeyvaultPage } from "@/legacy/components/keyvault/keyvault-page";---const Route = getRouteApi("/keyvault/");--/** Public's page before the redesign (`spaces_redesign` off); its search is the real route's. */-export const LegacyKeyvaultPage = KeyvaultRoute;--function KeyvaultRoute() {- const { view, focus } = Route.useSearch();- return <KeyvaultPage initialView={view} focus={focus ?? null} />;-}diff --git a/apps/cua-spaces-web/src/legacy/routes/notifications/index.tsx b/apps/cua-spaces-web/src/legacy/routes/notifications/index.tsxdeleted file mode 100644index 03e14013e0..0000000000--- a/apps/cua-spaces-web/src/legacy/routes/notifications/index.tsx+++ /dev/null@@ -1,117 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { Link } from "@tanstack/react-router";-import { BellIcon } from "lucide-react";-import { useState } from "react";--import { useNotifications, type NotificationInput, type NotificationLine } from "@/bridge";-import { CuaKey } from "@/components/cua-key";-import { EmptyState, Page, PageHeader } from "@/legacy/components/page";-import { Button } from "@/components/ui/button";-import { toastError } from "@/components/ui/toast";-import { cn } from "@/lib/utils";--/** Public's page before the redesign (`spaces_redesign` off). */-export const LegacyNotificationsPage = NotificationsPage;--/**- * Notifications: the daemon's feed, one line each, newest first, unread in- * bold, and Mark all read while any is unread. Each line is the app core's- * `notifications::view`, as in the SwiftUI app's `NotificationsPageView`.- * Clicking a line opens it in place (the whole title and body, and Open- * Space when it is about one) and marks it read; clicking again closes it.- */-function NotificationsPage() {- const { data, unsupported, error, markAllRead, markRead } = useNotifications();- const view = data?.view;- const [open, setOpen] = useState<ReadonlySet<string>>(() => new Set());- const toggle = (row: NotificationLine) => {- const opening = !open.has(row.id);- setOpen((was) => {- const next = new Set(was);- if (opening) next.add(row.id);- else next.delete(row.id);- return next;- });- // Reading it is the point; a host that can't mark one read just leaves it bold.- if (opening && row.on) void markRead(row.id).catch(() => undefined);- };- return (- <Page className="max-w-3xl">- <PageHeader- title={view?.title ?? "Notifications"}- actions={- view?.markAllLabel ? (- <Button variant="outline" size="sm" onClick={() => void markAllRead().catch(toastError("Couldn't mark them read"))} data-mark-all>- {view.markAllLabel}- </Button>- ) : null- }- />- {unsupported ? (- <EmptyState icon={<BellIcon />} title="Notifications">- Notifications are not available in this app yet.- </EmptyState>- ) : error && !data ? (- <EmptyState icon={<BellIcon />} title="Couldn't read notifications">- {error.message}- </EmptyState>- ) : !view ? null : view.rows.length === 0 ? (- <EmptyState icon={<BellIcon />} title={view.emptyText} />- ) : (- <div className="divide-y overflow-hidden rounded-xl border bg-card shadow-xs" data-notifications>- {view.rows.map((row) => (- <NotificationRow- key={row.id}- row={row}- entry={data?.feed.find((n) => n.id === row.id)}- open={open.has(row.id)}- onToggle={() => toggle(row)}- />- ))}- </div>- )}- </Page>- );-}--function NotificationRow({ row, entry, open, onToggle }: { row: NotificationLine; entry: NotificationInput | undefined; open: boolean; onToggle: () => void }) {- const detailId = `notification-${row.id}`;- const body = entry?.body.trim() ?? "";- return (- <div data-notification={row.id} data-unread={String(Boolean(row.on))} data-open={String(open)}>- <button- type="button"- aria-expanded={open}- aria-controls={open ? detailId : undefined}- onClick={onToggle}- className="flex min-h-11 w-full cursor-default items-center gap-3 px-4 py-2.5 text-left outline-none hover:bg-accent/50 focus-visible:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-inset"- data-notification-toggle- >- <span className={cn("size-1.5 shrink-0 rounded-full", row.on ? "bg-brand" : "bg-transparent")} aria-hidden />- <CuaKey size={20} />- <span className={cn("min-w-0 flex-1 text-[13px]", open ? "break-words" : "truncate", row.on && "font-semibold")} data-notification-text>- {open ? (entry?.title ?? row.text) : row.text}- </span>- <span className={cn("shrink-0 text-xs text-muted-foreground tabular-nums", open && "self-start pt-0.5")} data-notification-time>- {row.trailing}- </span>- </button>- {open ? (- <div id={detailId} className="space-y-2.5 pr-4 pb-3 pl-[4.125rem]" data-notification-detail>- {entry && body ? (- <p className="whitespace-pre-wrap break-words text-[13px] text-muted-foreground" data-notification-body>- {body}- </p>- ) : null}- {entry?.space ? (- <Button variant="outline" size="sm" render={<Link to="/spaces/$spaceId" params={{ spaceId: entry.space }} />} data-notification-open-space>- Open Space- </Button>- ) : null}- </div>- ) : null}- </div>- );-}diff --git a/apps/cua-spaces-web/src/legacy/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/legacy/routes/spaces/$spaceId.tsxdeleted file mode 100644index 96dcfb9b0a..0000000000--- a/apps/cua-spaces-web/src/legacy/routes/spaces/$spaceId.tsx+++ /dev/null@@ -1,554 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { getRouteApi, Link, useNavigate } from "@tanstack/react-router";-import { ArrowDownCircleIcon, ChevronLeftIcon, MonitorIcon, PictureInPicture2Icon, PlayIcon, SquareIcon, Trash2Icon, UserPlusIcon } from "lucide-react";-import { useEffect, useRef, useState, type ReactNode } from "react";--import { hostResources, runCreateFix, spaceResources, useBridge, useResources, useDevices, useExperiments, useMachines, useSession, useShareSheet, useSpaceDetail, useSpaceFiles, useSpaces, useTeleport, type CreateReport, type Machine, type ResourcesSnapshot, type Space, type StreamRow } from "@/bridge";-import { DiagnosticReportDialog } from "@/legacy/components/diagnostic-report-dialog";-import { OsIcon } from "@/components/os-icon";-import { EmptyState, Page } from "@/legacy/components/page";-import { AgentsSection } from "@/components/space-detail/agents-section";-import { DropWell } from "@/components/space-detail/drop-well";-import { FactList } from "@/legacy/components/space-detail/facts";-import { SpaceResourcesPanel } from "@/legacy/components/resources/space-resources-panel";-import { systemName } from "@/lib/resources";-import { StreamSection } from "@/components/space-detail/stream-section";-import { StreamSurface } from "@/legacy/components/space-detail/stream-surface";-import { StateLabel } from "@/components/state-dot";-import { ConfirmDialog } from "@/components/ui/alert-dialog";-import { Button } from "@/components/ui/button";-import { toast } from "@/components/ui/toast";-import { thisComputerText } from "@/lib/host-labels";-import { useSpaceVolumeError } from "@/lib/space-volume";-import { volumeUnavailableNote } from "@/lib/volume-notes";-import { canDelete, canPower, createError, createProgress, machineName, powerLabel, powerPending, spacePlace, spaceState } from "@/lib/spaces";--const Route = getRouteApi("/spaces/$spaceId");--/** Public's page before the redesign (`spaces_redesign` off); its search is the real route's. */-export const LegacySpacePage = SpaceDetailPage;--type Confirm = "stop" | "delete" | null;--const message = (e: unknown) => (e instanceof Error ? e.message : String(e));--function SpaceDetailPage() {- const { spaceId } = Route.useParams();- const { dropped } = Route.useSearch();- const navigate = useNavigate();- const {- data: spaces,- isLoading,- error,- startSpace,- stopSpace,- deleteSpace,- openSpace,- dismissCreate,- retryCreate,- canRetryCreate,- createdId,- createReport,- sendCreateReport,- } = useSpaces();- // The failed create's diagnostic report, while its review sheet is open.- const [report, setReport] = useState<CreateReport | null>(null);- const [reportOpen, setReportOpen] = useState(false);- const { data: machines = [] } = useMachines();- const resources = useResources();- const [confirm, setConfirm] = useState<Confirm>(null);- const teleport = useTeleport();- const sharing = useShareSheet();- const { data: session, openExternal } = useSession();- const { core } = useBridge();- const space = spaces?.find((s) => s.id === spaceId);- // Apps and files dropped on this Space's notch tile: the same as a drop on the well (an app opens Teleport at it), once.- const files = useSpaceFiles(space ?? { id: spaceId, name: spaceId });- const droppedOnce = useRef<string[] | null>(null);- useEffect(() => {- if (!dropped || !space || droppedOnce.current === dropped) return;- droppedOnce.current = dropped;- void files.drop(dropped);- // Off the address, so a reload does not teleport again.- void navigate({ to: "/spaces/$spaceId", params: { spaceId }, search: {}, replace: true });- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [dropped, space?.id]);- const thisMachine = machines.find((m) => m.current);- const hostArch = thisMachine?.arch ?? null;- // As this device sees it: Share only with Settings, Experiments, Sharing- // on (every action where the host has no experiments), and a machine on- // the relay greyed out while this device is not enrolled.- const exp = useExperiments();- const experiments = exp.unsupported ? undefined : (exp.data?.experiments ?? {});- const access = thisMachine?.accessNotice ?? null;- const devices = useDevices();- const { detail, stream, windowsUnsupported, pip, query, setQuery, agents, copy } = useSpaceDetail(space, hostArch, { experiments, access });- const volumeError = useSpaceVolumeError(space, space ? spaceState(space) === "running" : false);- // Open on a creating row: once the create finished and the registry lists- // the Space, its row (and this id) goes; follow it to the Space's own id.- // Only a page that showed the row follows: the address of a row that is- // already gone (Back after Remove from list) says so, and never jumps into- // another Space.- const [showed, setShowed] = useState<string | null>(null);- useEffect(() => {- if (space) setShowed(spaceId);- }, [space, spaceId]);- const created = !space && showed === spaceId ? createdId(spaceId) : undefined;- useEffect(() => {- if (created) void navigate({ to: "/spaces/$spaceId", params: { spaceId: created }, replace: true });- }, [created, navigate]);- if (created) return null;-- if (error || (!isLoading && !space)) {- return (- <Page>- <BackLink />- <EmptyState- icon={<MonitorIcon />}- title={error ? "Couldn't load this Space" : "This Space isn't here"}- action={- <Button variant="outline" render={<Link to="/spaces" />}>- Back to Spaces- </Button>- }- >- {error ? error.message : "It may have been deleted, or it runs on a computer this app can't see."}- </EmptyState>- </Page>- );- }- if (!space || !detail) return null;-- const state = spaceState(space);- const machine = machineName(machines, space);- const pending = powerPending(space);- // "Turn on" / "Turn off" (or Resume / Suspend), the SwiftUI app's words.- const turnOn = powerLabel(core, space, true);- const turnOff = powerLabel(core, space, false);-- const run = (label: string, action: () => Promise<void>) =>- action().catch((e: unknown) => toast(`Couldn't ${label} ${space.name}`, { description: message(e), type: "error" }));-- const start = () => run("start", () => startSpace(space.id));- // The core's detail actions: present only where they apply (Share follows- // Settings, Experiments), enabled only when the Space can stream and this- // device may connect.- const action = (id: string) => detail.actions.find((a) => a.id === id);- const teleportAction = action("teleport");- const shareAction = action("share");- // Signed in, not enrolled: the access line's action opens Settings,- // Devices with the enroll sheet.- const enroll = () => {- devices.startEnroll();- void navigate({ to: "/settings/devices" });- };- const teleportApp = () => run("open Teleport for", () => teleport.open(space));- const share = () => run("share", () => sharing.open(space, session?.signedIn ?? false));- const stop = () => run("stop", () => stopSpace(space.id));- // Leaving a Space that is going away: the grid takes this page's place in- // the history, so Back never returns to a page for a Space that is gone.- const leave = () => navigate({ to: "/spaces", replace: true });- // Delete, or "Remove from List" (a Space in your cloud: forget it here,- // keep it running there; `AppModel.delete(_:removeOnly:)`).- const remove = (removeOnly = false) => {- void leave();- void run(removeOnly ? "remove" : "delete", async () => {- await deleteSpace(space.id, removeOnly);- toast(removeOnly ? `Removed ${space.name} from the list` : `Deleted ${space.name}`, { type: "success" });- });- };- // A failed create only leaves the list (here and on the host). The grid- // opens first, then the row goes: this page never shows "isn't here" in- // between, and nothing else decides where the person lands.- const dismiss = () => {- void leave().then(() => run("remove", () => dismissCreate(space.id)));- };- // Try again: the same create as a new row; this page follows it.- const retry = canRetryCreate(space.id)- ? () => {- const next = retryCreate(space.id);- if (next) void navigate({ to: "/spaces/$spaceId", params: { spaceId: next }, replace: true });- }- : undefined;- // Send report: the review sheet with the core's redacted report; nothing- // is sent until the person presses Send there.- const openReport = () =>- void createReport(space.id).then((r) => {- if (!r) return;- setReport(r);- setReportOpen(true);- });- // It failed the same way twice: the core's fix for that cause (copy a- // command, open the help page, or the details) instead of Try again.- const createFix = space.progress?.fix;- const fix = createFix- ? () =>- void runCreateFix(createFix, {- copy: async (text) => {- await navigator.clipboard?.writeText(text);- toast(`Copied ${text}`, { description: "Paste it in Terminal.", type: "success" });- },- openExternal: (url) => openExternal(url),- details: openReport,- }).catch((e: unknown) => toast("Couldn't do that", { description: message(e), type: "error" }))- : undefined;- // Picture in picture where the host has panels; its own window where it doesn't.- const onPip = (row: StreamRow) =>- run("open", async () => {- if ((await pip(row.id)) === "open-window") {- await openSpace(space.id);- toast(`Opening ${space.name}`, { description: "Picture in picture isn't available here, so its desktop opens in a separate window." });- }- });-- const desktopRow = stream?.rows.find((r) => r.kind === "desktop");- const display = desktopRow?.resolution?.split("×").map(Number);- // The desktop plays in its picture-in-picture panel: said here, with Bring- // it back, instead of a second stream (`SpaceScreenView`'s placeholder).- const poppedOut = desktopRow?.actions.some((a) => a.id === "pip" && a.active) ?? false;- const poppedOutState = poppedOut ? (- <div data-popped-out="" className="flex flex-col items-center gap-2">- <PictureInPicture2Icon className="size-7 text-muted-foreground" />- <p className="text-xs text-muted-foreground">Playing in a floating window</p>- <Button variant="outline" size="sm" onClick={() => void onPip(desktopRow!)}>- Bring it back- </Button>- </div>- ) : undefined;- const aspect = display?.length === 2 && display[0]! > 0 && display[1]! > 0 ? display[0]! / display[1]! : undefined;- const showStream = detail.sections.includes("Stream") && stream;- // The core's sections after Stream: Agents (where the host lists runs)- // and Teleport (the drop well), as the SwiftUI detail draws them.- const showAgents = detail.sections.includes("Agents") && !agents.unsupported;- const showTeleport = detail.sections.includes("Teleport");-- return (- <Page>- <BackLink />- <header className="mb-5 flex items-start justify-between gap-4">- <div className="flex min-w-0 items-start gap-3">- <div className="mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-lg border bg-card shadow-xs">- <OsIcon os={space.os} className="size-4.5 text-muted-foreground" />- </div>- <div className="min-w-0">- <h1 data-detail-title className="truncate text-[22px] leading-tight font-semibold tracking-[-0.01em]">{detail.title}</h1>- <p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-muted-foreground">- <span>{spacePlace(space, machine)}</span>- {pending ? <span className="text-xs">{pending}</span> : <StateLabel state={state} space={space} />}- </p>- </div>- </div>- <div className="flex shrink-0 items-center gap-2">- {teleportAction ? (- <Button variant="outline" disabled={!teleportAction.enabled} title={teleportAction.help} onClick={teleportApp}>- <ArrowDownCircleIcon /> {teleportAction.label}- </Button>- ) : null}- {shareAction ? (- <Button variant="outline" data-share-space="" disabled={!shareAction.enabled} title={shareAction.help} onClick={share}>- <UserPlusIcon /> {shareAction.label}- </Button>- ) : null}- {canPower(space) ? (- state === "stopped" ? (- <Button variant="outline" disabled={Boolean(pending)} onClick={start}>- <PlayIcon /> {turnOn}- </Button>- ) : (- <Button variant="outline" disabled={Boolean(pending)} onClick={() => setConfirm("stop")}>- <SquareIcon className="size-3.5" /> {turnOff}- </Button>- )- ) : null}- {state === "failed" ? (- <Button variant="outline" data-dismiss-create="" onClick={dismiss}>- <Trash2Icon className="text-destructive" /> Remove- </Button>- ) : null}- {canDelete(space) ? (- <Button variant="outline" aria-label={`${detail.deleteLabel} ${space.name}`} onClick={() => setConfirm("delete")}>- <Trash2Icon className="text-destructive" /> {detail.deleteLabel}- </Button>- ) : null}- </div>- </header>-- {detail.powerError ? <p className="mb-4 text-[13px] text-destructive">{detail.powerError}</p> : null}-- {detail.desktopNote ? (- // One of your machines that keeps its desktop private: why, in place- // of the desktop, then the Spaces it provides (no New Space button- // beside the note).- <MachineSpaces- note={detail.desktopNote}- listSpaces={Boolean(detail.newSpace)}- spaces={hostedSpaces(spaces ?? [], space.id)}- // This machine's own screen: its switches live on its Computers page.- action={- detail.isHost ? (- <Button variant="outline" size="sm" data-host-desktop-action="" render={<Link to="/machines" />}>- Open Computers- </Button>- ) : null- }- />- ) : (- <StreamSurface- spaceId={space.id}- os={space.os}- aspectRatio={aspect}- canStream={detail.canStream}- previewText={detail.previewText}- access={detail.access}- onAccessAction={enroll}- className="h-72"- >- {surfaceState(space, pending, turnOn, start, dismiss, retry, openReport, fix) ?? poppedOutState}- </StreamSurface>- )}-- <SpaceResources space={space} spaces={spaces ?? []} snapshot={resources} machines={machines} />-- <div className="mt-8 grid items-start gap-x-6 md:grid-cols-2">- <div>- <FactList title="Details" facts={detail.facts} />- {volumeError ? (- <p className="mt-3 px-1 text-[13px] text-muted-foreground" data-volume-note="" title={volumeError}>- {volumeUnavailableNote(volumeError)}- </p>- ) : null}- {showTeleport ? (- <div className="mt-7">- <DropWell- title="Teleport"- space={space}- copy={{ caption: copy?.dropCaption ?? "Drop a file or window", sendFile: copy?.sendFile ?? "Send file…", teleportApp: copy?.teleportApp ?? "Teleport an app…" }}- onTeleport={teleportApp}- />- </div>- ) : null}- </div>- <div>- {showStream ? (- <StreamSection- title="Stream"- section={stream}- query={query}- onQuery={setQuery}- onPip={(row) => void onPip(row)}- hideStatus={windowsUnsupported}- />- ) : null}- {showAgents ? (- <AgentsSection- title="Agents"- runs={agents.runs}- failed={agents.failed}- copy={{- loading: copy?.agentsLoading ?? "Looking for this Space’s agents…",- empty: copy?.agentsEmpty ?? "No agents have been started in this Space.",- failed: copy?.agentsFailed ?? "Could not read this Space’s agents.",- }}- />- ) : null}- </div>- </div>-- <ConfirmDialog- open={confirm === "stop"}- onOpenChange={(o) => !o && setConfirm(null)}- title={`${turnOff} ${space.name}?`}- description={- space.power?.control === "suspend"- ? "It's suspended in memory and picks up where it left off when you start it again."- : "It shuts down. Anything unsaved inside it is lost."- }- confirmLabel={turnOff}- destructive={space.power?.control !== "suspend"}- onConfirm={stop}- />- <ConfirmDialog- open={confirm === "delete"}- onOpenChange={(o) => !o && setConfirm(null)}- title={detail.confirm.title}- description={detail.confirm.message}- confirmLabel={detail.confirm.confirmLabel}- cancelLabel={detail.confirm.cancelLabel}- disabledReason={detail.confirm.confirmEnabled ? null : (detail.confirm.disabledReason ?? null)}- destructive- onConfirm={() => remove()}- alternative={detail.confirm.removeLabel ? { label: detail.confirm.removeLabel, onClick: () => remove(true) } : null}- />- <DiagnosticReportDialog- open={reportOpen}- onOpenChange={setReportOpen}- report={report}- onSend={(subject, parts) => sendCreateReport({ subject, parts })}- />- </Page>- );-}--/** The Spaces one of your machines provides (the core's `hosted_rows`:- * those whose host is the machine). */-function hostedSpaces(spaces: readonly Space[], machineSpaceId: string): Space[] {- if (!machineSpaceId.startsWith("relay:")) return [];- const machine = machineSpaceId.slice("relay:".length);- return spaces.filter((s) => s.host === machine);-}--/** A machine that does not share its desktop, or this machine's own- * screen (never streamed here): the core's line and its one action, then- * the Spaces it provides when it provides any. */-function MachineSpaces({ note, listSpaces, spaces, action }: { note: string; listSpaces: boolean; spaces: Space[]; action?: ReactNode }) {- return (- <section data-machine-desktop-note="">- <div className="flex items-center justify-between gap-4 rounded-xl border px-4 py-3">- <p className="text-[13px] text-muted-foreground">{note}</p>- {action}- </div>- {listSpaces ? (- <div data-machine-spaces="" className="mt-6">- <h2 className="mb-2 px-1 text-[13px] font-semibold">Spaces</h2>- {spaces.length === 0 ? (- <p className="px-1 text-[13px] text-muted-foreground">No Spaces yet</p>- ) : (- <ul className="divide-y rounded-xl border">- {spaces.map((s) => (- <li key={s.id}>- <Link- to="/spaces/$spaceId"- params={{ spaceId: s.id }}- className="flex h-10 items-center gap-2.5 px-4 text-[13px] outline-none hover:bg-muted/60 focus-visible:bg-muted/60"- >- <OsIcon os={s.os} className="size-3.5 shrink-0 text-muted-foreground" />- <span className="min-w-0 flex-1 truncate">{s.name}</span>- <StateLabel state={spaceState(s)} space={s} />- </Link>- </li>- ))}- </ul>- )}- </div>- ) : null}- </section>- );-}--function BackLink() {- return (- <Link- to="/spaces"- className="mb-4 -ml-1 inline-flex h-6 items-center gap-0.5 rounded-md pr-1.5 text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"- >- <ChevronLeftIcon className="size-3.5" /> Spaces- </Link>- );-}--/** What replaces the stream while there is no desktop to show: a create's- * progress, a delete, a stopped Space. Undefined: the stream surface. */-function surfaceState(- space: Space,- pending: string | null,- startLabel: string,- onStart: () => void,- onDismiss: () => void,- onRetry?: () => void,- onReport?: () => void,- onFix?: () => void,-): ReactNode {- const state = spaceState(space);- if (state === "failed") {- // The same failure twice: its fix replaces a plain Try again.- const fix = space.progress?.fix;- return (- <>- <p className="text-[13px] font-medium">Couldn't create this Space</p>- <p data-create-error="" className="mt-2 max-w-md text-center text-xs text-destructive">- {createError(space) || "No reason was reported."}- </p>- {fix ? (- <p data-create-fix="" className="mt-2 max-w-md text-center text-xs text-muted-foreground">- {fix.text}- </p>- ) : null}- <div className="mt-4 flex flex-wrap justify-center gap-2">- {fix && onFix ? (- <Button data-create-fix-button="" onClick={onFix}>- {fix.label}- </Button>- ) : onRetry ? (- <Button onClick={onRetry}>Try again</Button>- ) : null}- <Button variant="outline" onClick={onDismiss}>- Remove from list- </Button>- {onReport && fix?.action !== "details" ? (- <Button variant="outline" data-send-report="" onClick={onReport}>- Send a report…- </Button>- ) : null}- </div>- </>- );- }- if (state === "creating") {- return (- <>- <p className="text-[13px] font-medium">{space.progress?.label ?? "Creating…"}</p>- <div className="mt-3 h-1 w-56 overflow-hidden rounded-full bg-foreground/10">- <div className="h-full rounded-full bg-brand transition-[width]" style={{ width: `${Math.round(createProgress(space) * 100)}%` }} />- </div>- {space.progress?.transfer ? <p className="mt-2 text-xs text-muted-foreground tabular-nums">{space.progress.transfer}</p> : null}- {space.progress?.error ? <p className="mt-2 text-xs text-destructive">{space.progress.error}</p> : null}- </>- );- }- if (state === "deleting") return <p className="text-[13px] text-muted-foreground">Deleting…</p>;- if (state === "stopped") {- return (- <>- <OsIcon os={space.os} className="mb-4 size-8 text-muted-foreground/30" />- <p className="text-[13px] text-muted-foreground">- {canPower(space) ? "Start this Space to open its desktop." : "This Space is stopped, and it can't be started from this app."}- </p>- {canPower(space) ? (- <Button className="mt-4" variant="outline" disabled={Boolean(pending)} onClick={onStart}>- <PlayIcon /> {pending ?? startLabel}- </Button>- ) : null}- </>- );- }- return undefined;-}--/** Processor, memory and disk for this Space, when its computer sends them. */-function SpaceResources({ space, spaces, snapshot, machines }: { space: Space; spaces: Space[]; snapshot: ResourcesSnapshot | null; machines: Machine[] }) {- const mine = spaceResources(snapshot, space.id);- const state = spaceState(space);- if (!mine || (state !== "running" && state !== "stopped")) return null;- const local = space.provider === "local";- const machine = local ? machines.find((m) => m.current) : machines.find((m) => m.id === space.host || m.spaceIds.includes(space.id));- const host = hostResources(snapshot, machine);- const computer = local ? thisComputerText() : (machine?.name ?? space.hostName ?? "its computer");- // The Spaces on the same computer, with the numbers it sent, for how it fits.- const sameComputer = (s: Space) => (local ? s.provider === "local" : s.host === space.host);- const onComputer = spaces.flatMap((s) => {- const r = sameComputer(s) ? spaceResources(snapshot, s.id) : null;- return r ? [r] : [];- });- return (- <SpaceResourcesPanel- space={mine}- name={space.name}- host={host}- computer={computer}- spaces={onComputer}- baseName={systemName(space.osPrettyName)}- />- );-}diff --git a/apps/cua-spaces-web/src/legacy/routes/spaces/index.tsx b/apps/cua-spaces-web/src/legacy/routes/spaces/index.tsxdeleted file mode 100644index ddc33a8216..0000000000--- a/apps/cua-spaces-web/src/legacy/routes/spaces/index.tsx+++ /dev/null@@ -1,455 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { getRouteApi, Link, useNavigate } from "@tanstack/react-router";-import { ArrowDownCircleIcon, KeyRoundIcon, LoaderCircleIcon, MonitorIcon, PlusIcon, PowerIcon, SearchIcon } from "lucide-react";-import { useEffect, useRef, useState, type DragEvent } from "react";--import { emptyHome, listView, spaceResources, type CreatingElsewhere, useAgents, useBridge, useChecklist, useResources, useFirstSpaceOffers, useMachines, useNewSpaceWizard, useSpaceAccess, useSpaceFiles, useSpaces, useSpaceThumbnail, useWindowDropTarget, type Space } from "@/bridge";-import { EmptyHome } from "@/legacy/components/empty-home";-import { RunAgentDialog } from "@/legacy/components/agents/run-agent-dialog";-import { SpaceReadyCard, useAgentOffer } from "@/legacy/components/space-ready-card";-import { useFirstRunStep, useFirstSpaceMilestones } from "@/components/first-run-guide";-import { OsIcon } from "@/components/os-icon";-import { EmptyState, Page, PageHeader } from "@/legacy/components/page";-import { ComputerWarnings } from "@/legacy/components/resources/computer-resources";-import { SpaceCanvas } from "@/components/space-canvas";-import { StateLabel } from "@/components/state-dot";-import { useTileVideo } from "@/components/video/tile-video";-import { useNewSpace } from "@/hooks/use-new-space";-import { useInView } from "@/hooks/use-in-view";-import { useQuiet } from "@/hooks/use-quiet";-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, creatingElsewhereLine, creatingElsewherePercent, creatingElsewherePlace, elsewhereOs, machineName, matchesQuery, powerButton, powerError, realSpaces, spacePlace, spaceState, visibleSpaces, type SpaceFilter } from "@/lib/spaces";--const Route = getRouteApi("/spaces/");--/** Public's page before the redesign (`spaces_redesign` off); its search is the real route's. */-export const LegacySpacesPage = SpacesPage;--const FILTERS: { value: SpaceFilter; label: string }[] = [- { value: "all", label: "All" },- { value: "running", label: "Running" },- { value: "stopped", label: "Stopped" },- { value: "creating", label: "Creating" },-];--function SpacesPage() {- const { data: all = [], isLoading, error, listNotice, listStatus, creatingElsewhere } = useSpaces();- // Machines' own desktops are on Machines, not here.- const spaces = realSpaces(all);- const { data: machines = [] } = useMachines();- const { sort } = Route.useSearch();- const resources = useResources();- 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.- useFirstSpaceOffers();- const { core } = useBridge();- const { env } = useNewSpaceWizard();- const home = emptyHome(core, env.hostArch);- const visible = visibleSpaces(spaces, filter, (s) => matchesQuery(core, s, machineName(machines, s), query));- const onDisk = (s: Space) => spaceResources(resources, s.id)?.diskOnHost?.bytes ?? -1;- const shown = sort === "size" ? [...visible].sort((a, b) => onDisk(b) - onDisk(a)) : visible;- // Spaces your other computers are creating (CUA-2349): first in the grid, until they are ready.- const elsewhere =- filter === "all" || filter === "creating"- ? creatingElsewhere.filter((c) => matchesQuery(core, { id: `${c.machineId}/${c.name}`, name: c.name, detail: creatingElsewhereLine(c) }, c.machineName, query))- : [];- const access = useSpaceAccess(spaces);- const running = spaces.filter((s) => spaceState(s) === "running").length;- // After the first run's Finish later, its to-do list stands in for the checklist.- // The first Space is ready and no agent has worked in it yet: one action, "Run an agent here".- const { state: checklist } = useChecklist();- const { data: agents, isLoading: agentsLoading } = useAgents();- const readySpace = spaces.find((s) => spaceState(s) === "running");- const agentRan = checklist.done.run_agent || (agents?.runs.length ?? 0) > 0 || (agents?.agents.length ?? 0) > 0;- // Only once the agents are read: before that "no agent ran" isn't known, and the offer would show (and be- // counted as shown) for a moment on a computer whose agents already work.- const offer = useAgentOffer(Boolean(readySpace) && !agentsLoading && !agentRan);- const runHere = readySpace && !agentRan && offer.visible ? readySpace : undefined;- const [runOpen, setRunOpen] = useState(false);- // The core decides: "Create your first Space" only for a complete list with no Space. A daemon still- // starting (an app update) or computers still answering show what is known and one quiet line instead.- const view = listView(core, listStatus, spaces.length);- // Never read, and the host says why: "Spaces could not be loaded" (the empty home's unread title).- const unread = !listStatus.loaded && Boolean(listNotice);- const empty = !error && !isLoading && (view.empty || unread) && creatingElsewhere.length === 0;- // No Spaces yet (or the list could not be read): the SwiftUI app's empty home, as the first-run guide.- const guide = empty && home && home.tiles.length > 0 ? home : null;- const reachingLine = error || unread ? null : view.reachingLine;- // The suggested task's request, while the run dialog was opened from it.- const [runPrompt, setRunPrompt] = useState<string | undefined>();- const firstRunStep = useFirstRunStep();- useFirstSpaceMilestones(spaces);- const navigate = useNavigate();- // The cards above the list (ready, checklist, computers) and the list come from separate host reads. Draw them- // together once those have answered, not one by one with the page jumping at each (CUA-1951).- const settled = useQuiet(- [isLoading, listStatus.loaded, all.length, machines.length, Object.keys(checklist.done).length, checklist.dismissed, agents?.runs.length, agents?.agents.length, resources ? 1 : 0].join("|"),- );-- return (- <Page>- <PageHeader- title="Spaces"- description={isLoading || !listStatus.loaded ? "Loading Spaces…" : `${plural(spaces.length, "Space")} on ${plural(machines.length, "computer")}, ${running} running`}- actions={- <Button onClick={newSpace}>- <PlusIcon /> New Space- </Button>- }- />- {settled ? (- <>- {runHere ? <SpaceReadyCard- space={runHere}- onRun={(task) => {- offer.clicked();- firstRunStep("task_started");- setRunPrompt(task.prompt);- setRunOpen(true);- }}- onDismiss={offer.dismiss}- /> : null}- {readySpace ? (- <>- <RunAgentDialog open={runOpen} space={readySpace} prompt={runPrompt} onOpenChange={setRunOpen} onManual={() => void navigate({ to: "/settings/connectors", search: {} })} onConnected={offer.completed} />- </>- ) : null}- <ComputerWarnings snapshot={resources} machines={machines} />- {sort === "size" ? (- <p data-sorted-by-size="" className="mb-3 flex items-center gap-2 px-1 text-xs text-muted-foreground">- Biggest first, by how much space each one uses on its computer.- <Link to="/spaces" search={{}} className="font-medium text-foreground underline-offset-2 hover:underline">- Show the usual order- </Link>- </p>- ) : null}- <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>- {/* The empty home and the "Reaching N computers…" line take the grid's place, under the warnings and the- filters. */}- {error ? (- <EmptyState icon={<MonitorIcon />} title="Couldn't load Spaces">- {error.message}- </EmptyState>- ) : isLoading ? null : shown.length + elsewhere.length > 0 ? (- <ul className="grid grid-cols-[repeat(auto-fill,minmax(232px,1fr))] gap-4">- {/* Being created, first: as this computer's own creates sort. */}- {elsewhere.map((c) => (- <li key={`elsewhere:${c.machineId}/${c.name}`}>- <CreatingElsewhereTile creating={c} />- </li>- ))}- {shown.map((space) => (- // Off-screen tiles skip layout and paint until they scroll in.- <li key={space.id} className="[content-visibility:auto] [contain-intrinsic-size:auto_232px]">- <SpaceTile space={space} machine={machineName(machines, space)} accessKey={access.signedIn.has(space.id) ? access.accessKey(space.id) : undefined} />- </li>- ))}- </ul>- ) : guide ? (- <EmptyHome home={guide} unread={Boolean(listNotice)} />- ) : spaces.length === 0 && !empty ? null : spaces.length === 0 ? (- <EmptyState- icon={<MonitorIcon />}- title="No Spaces yet"- action={- <Button onClick={newSpace}>- <PlusIcon /> New Space- </Button>- }- >- Create one on {thisComputerText()}.- </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.- </EmptyState>- ) : null}- {reachingLine && !isLoading ? (- <p data-spaces-reaching="" role="status" className={cn("px-1 text-xs text-muted-foreground", spaces.length > 0 ? "mt-4" : "py-6 text-center")}>- {reachingLine}- </p>- ) : null}- </>- ) : null}- </Page>- );-}--function SpaceTile({ space, machine, accessKey }: { space: Space; machine: string; accessKey?: string | null }) {- const drop = useTileDrop(space);- // A real window dragged over this tile (the host hit-tests the tiles' boxes and says which; macOS only).- const windowOver = useWindowDropTarget() === space.id;- return (- <div- className="group/tile relative"- data-tile-drop={drop.over ?? undefined}- data-drop-status={drop.status?.kind}- data-window-drop={space.id}- data-window-over={windowOver || undefined}- {...drop.handlers}- >- <SpaceLink space={space} machine={machine} windowOver={windowOver} />- {drop.over ? <DropOverlay space={space} accepts={drop.over === "accept"} /> : null}- {/* A drop on the tile still going in: the core's "Sending …" line. */}- {drop.status?.kind === "working" && !drop.over ? (- <div className="pointer-events-none absolute top-3 left-3 flex max-w-[60%] items-center gap-1.5 rounded-full border bg-card/90 px-2 py-0.5 text-2xs font-medium text-muted-foreground shadow-xs backdrop-blur-sm">- <LoaderCircleIcon className="size-3 shrink-0 animate-spin" aria-hidden />- <span className="truncate">{drop.status.text}</span>- </div>- ) : null}- {/* Over the thumbnail, as the SwiftUI sidebar row ends: "Signed in", then power. */}- <div className="absolute top-3 right-3 flex items-center gap-1.5">- {/* A live Keyvault sign-in is in this Space: the badge opens Access with its row brought forward. */}- {accessKey !== undefined ? (- <Link- to="/keyvault"- search={{ view: "access", focus: accessKey ?? undefined }}- data-signed-in={space.id}- title="A Keyvault sign-in is live in this Space. Open Access."- className="inline-flex items-center gap-1 rounded-full border bg-card/90 px-2 py-0.5 text-2xs font-medium text-muted-foreground shadow-xs outline-none backdrop-blur-sm hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"- >- <KeyRoundIcon className="size-3" /> Signed in- </Link>- ) : null}- <TilePower space={space} />- </div>- </div>- );-}--/**- * Files dropped from Finder on a running Space's tile go into that Space,- * as a drop on its page's well does (`useSpaceFiles`: the host reads the- * paths from the drop itself; an app bundle opens Teleport at that app).- * While files are over the tile it says where they go; what the drop did- * shows on the tile and in a toast.- */-function useTileDrop(space: Space) {- const files = useSpaceFiles(space);- const [over, setOver] = useState<"accept" | "refuse" | null>(null);- const accepts = spaceState(space) === "running";- const status = files.status;- useEffect(() => {- if (!status) return;- const group = `tile-drop:${space.id}`;- if (status.kind === "working") toast(status.text, { group });- else if (status.kind === "done") toast(`Sent to ${space.name}`, { description: status.text, type: "success", group });- else toast(`Couldn't send to ${space.name}`, { description: status.text, type: "error", group });- }, [status, space.id, space.name]);- const carriesFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes("Files");- const onDragOver = (e: DragEvent) => {- if (!carriesFiles(e)) return;- // Always handled here, so a drop on a tile never reaches the window.- e.preventDefault();- e.dataTransfer.dropEffect = accepts ? "copy" : "none";- setOver(accepts ? "accept" : "refuse");- };- const onDragLeave = (e: DragEvent) => {- // Leaving for one of the tile's own children is still over the tile.- if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;- setOver(null);- };- const onDrop = (e: DragEvent) => {- if (!carriesFiles(e)) return;- e.preventDefault();- setOver(null);- if (!accepts) return;- const names = Array.from(e.dataTransfer.files).map((f) => f.name);- if (names.length) void files.drop(names);- };- return { over, status, handlers: { onDragEnter: onDragOver, onDragOver, onDragLeave, onDrop } };-}--/** Over a tile while files are dragged on it: where they go, or why they can't. */-function DropOverlay({ space, accepts }: { space: Space; accepts: boolean }) {- return (- <div- aria-hidden- className={cn(- "pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-1.5 rounded-xl border-2 text-center text-[13px] backdrop-blur-[2px]",- accepts ? "border-brand bg-brand/15 text-foreground" : "border-dashed border-border bg-card/80 text-muted-foreground",- )}- >- {accepts ? <ArrowDownCircleIcon className="size-6 text-brand" strokeWidth={1.5} /> : null}- <span className="max-w-[85%] truncate font-medium">{accepts ? `Send to ${space.name}` : `${space.name} isn't running`}</span>- </div>- );-}--/**- * The core's power button, while the pointer is on the tile or focus is in- * it, and always while it runs (the SwiftUI sidebar row's, which shows on- * hover, on the selected row and while busy).- */-function TilePower({ space }: { space: Space }) {- const { core } = useBridge();- const { startSpace, stopSpace } = useSpaces();- const button = powerButton(core, space);- if (!button) return null;- const press = () => {- const [act, word] = button.turnOn ? [startSpace, "start"] : [stopSpace, "stop"];- void act(space.id).catch(toastError(`Couldn't ${word} ${space.name}`));- };- return (- <button- type="button"- data-tile-power={button.turnOn ? "on" : "off"}- data-busy={button.busy || undefined}- disabled={button.busy}- title={button.help}- aria-label={`${button.help} ${space.name}`}- onClick={press}- className={cn(- "inline-flex size-6 items-center justify-center rounded-full border bg-card/90 text-muted-foreground shadow-xs outline-none backdrop-blur-sm hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 disabled:cursor-default",- !button.busy && "opacity-0 group-focus-within/tile:opacity-100 group-hover/tile:opacity-100",- )}- >- {button.busy ? <LoaderCircleIcon className="size-3 animate-spin" aria-hidden /> : <PowerIcon className="size-3" aria-hidden />}- </button>- );-}--function SpaceLink({ space, machine, windowOver = false }: { space: Space; machine: string; windowOver?: boolean }) {- return (- <Link- to="/spaces/$spaceId"- params={{ spaceId: space.id }}- data-space-id={space.id}- data-state={spaceState(space)}- className={cn(- "group block w-full cursor-default rounded-xl border bg-card p-1.5 text-left shadow-xs outline-none transition-[box-shadow,border-color] hover:border-foreground/15 hover:shadow-sm focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/25",- windowOver && "border-brand ring-3 ring-brand/25",- )}- >- <Thumbnail space={space} />- <div className="flex items-start gap-2.5 px-1.5 pt-2.5 pb-1">- <OsIcon os={space.os} className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />- <div className="min-w-0 flex-1">- <div className="truncate text-[13px] font-medium">{space.name}</div>- {/* Being created: the core's pending line ("This Mac · Downloading"), as the SwiftUI row says it, naming this computer by its system. */}- <div className="mt-0.5 truncate text-xs text-muted-foreground">- {spaceState(space) === "creating" && space.detail ? creatingLine(space.detail) : spacePlace(space, machine)}- </div>- {/* Downloading: how far, how fast, how long is left. */}- {spaceState(space) === "creating" && space.progress?.transfer ? (- <div data-create-transfer="" className="mt-0.5 truncate text-xs tabular-nums text-muted-foreground">- {space.progress.transfer}- </div>- ) : null}- {createError(space) ? (- <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" />- </div>- {/* What it was given and uses now, when its computer says. */}- </Link>- );-}--/**- * A Space another of your computers is creating (CUA-2349): the same tile- * as one this computer creates, with "Creating macOS on Mac mini… 40%" from- * that computer's own report. Nothing to open yet; once it is ready it is a- * Space like any other (or that computer's count, when its Spaces are not- * shared).- */-function CreatingElsewhereTile({ creating }: { creating: CreatingElsewhere }) {- const os = elsewhereOs(creating);- const line = creatingElsewhereLine(creating);- return (- <div data-creating-elsewhere={creating.machineId} data-state="creating" role="group" aria-label={`${creating.name}: ${line}`} className="block w-full rounded-xl border bg-card p-1.5 text-left shadow-xs">- <SpaceCanvas>- <OsIcon os={os} className="size-6 text-muted-foreground/30" />- <div className="absolute inset-x-3 bottom-3">- <div className="h-1 overflow-hidden rounded-full bg-foreground/10">- <div data-create-progress className="h-full rounded-full bg-brand transition-[width] duration-500" style={{ width: `${Math.min(100, Math.max(0, creating.percent))}%` }} />- </div>- </div>- </SpaceCanvas>- <div className="flex items-start gap-2.5 px-1.5 pt-2.5 pb-1">- <OsIcon os={os} className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />- <div className="min-w-0 flex-1">- <div className="truncate text-[13px] font-medium">{creating.name}</div>- <div className="mt-0.5 truncate text-xs text-muted-foreground" title={line}>- {creatingElsewherePlace(creating)}- </div>- </div>- {/* How far, where this computer's own creates say "Creating". */}- <span data-state-label="creating" className="mt-px inline-flex shrink-0 items-center gap-1.5 text-xs tabular-nums text-muted-foreground">- <span className="size-1.5 animate-pulse rounded-full bg-brand" aria-hidden />- {creatingElsewherePercent(creating)}- </span>- </div>- </div>- );-}--function Thumbnail({ space }: { space: Space }) {- const state = spaceState(space);- const ref = useRef<HTMLDivElement | null>(null);- // Pictures and live video only for the tiles on screen (or close to it).- const inView = useInView(ref);- const video = useTileVideo(ref, space, inView);- // Its latest capture (the notch's image), until live video draws over it.- const thumbnail = useSpaceThumbnail(space.id, inView && (state === "running" || state === "stopped"));- return (- <SpaceCanvas ref={ref} dim={state === "stopped"} streamState={video?.phase}>- {thumbnail ? (- <img data-tile-thumbnail="" src={thumbnail} alt="" aria-hidden className="absolute inset-0 size-full object-cover" />- ) : (- <OsIcon os={space.os} className="size-6 text-muted-foreground/30" />- )}- {state === "creating" ? (- <div className="absolute inset-x-3 bottom-3">- <div className="h-1 overflow-hidden rounded-full bg-foreground/10">- <div data-create-progress className="h-full rounded-full bg-brand" style={{ width: `${Math.round(createProgress(space) * 100)}%` }} />- </div>- </div>- ) : null}- </SpaceCanvas>- );-}diff --git a/apps/cua-spaces-web/src/legacy/routes/volume/index.tsx b/apps/cua-spaces-web/src/legacy/routes/volume/index.tsxdeleted file mode 100644index a731b49e7b..0000000000--- a/apps/cua-spaces-web/src/legacy/routes/volume/index.tsx+++ /dev/null@@ -1,218 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { HardDriveIcon } from "lucide-react";-import type { ReactNode } from "react";--import { useExperimentFlags, useVolume, useVolumePins, type ConflictView, type DriveAction, type LineView } from "@/bridge";-import { EmptyState, Page, PageHeader } from "@/legacy/components/page";-import { StorageSection } from "@/components/settings/storage-section";-import { Button } from "@/components/ui/button";-import { cn } from "@/lib/utils";-import { volumeUnavailableNote } from "@/lib/volume-notes";--/** Public's page before the redesign (`spaces_redesign` off). */-export const LegacyVolumePage = VolumePage;--/**- * Volume, as the SwiftUI app's `DrivePageView` lays it out: Open in Finder- * and where it is mounted, the access agents ask for, the grants in force,- * sync per device and conflicts. Not a file browser: Finder is. Every line- * and label is the core's (`drive.view`); shown only with the Cua Volume- * experiment on.- */-function VolumePage() {- const experiments = useExperimentFlags();- const pinned = Boolean(useVolumePins().volume);- if (!pinned && experiments && !experiments.cuaVolume) {- return (- <Page className="max-w-3xl">- <PageHeader title="Volume" />- <EmptyState icon={<HardDriveIcon />} title="Cua Volume is off">- It's an experiment for now. Turn it on in Settings, Advanced.- </EmptyState>- </Page>- );- }- return <VolumeBody />;-}--function VolumeBody() {- const { view, unsupported, act, spaceErrors } = useVolume();-- if (!view) return <div className="h-full" aria-busy="true" />;- if (unsupported) {- return (- <Page className="max-w-3xl">- <PageHeader title={view.title} />- <EmptyState icon={<HardDriveIcon />} title="Not available here">- This window can't reach Cua Volume yet. Open it from the Cua Spaces app.- </EmptyState>- </Page>- );- }-- const send = (a: DriveAction) => act(a);- return (- <Page className="max-w-3xl">- <PageHeader title={view.title} />- <div data-drive-page="" data-busy={view.busy ? "true" : undefined}>- {view.openLabel ? (- <Section>- <div className="flex items-center gap-4 px-4 py-3">- <p className="min-w-0 flex-1 truncate text-[13px] text-muted-foreground" title={view.mountPath ?? view.mountLine ?? undefined} data-drive-mount-line="">- {view.mountLine}- </p>- <Button- disabled={view.busy}- data-drive-open=""- data-path={view.mountPath ?? ""}- onClick={() => send({ type: "open-volume", mounted: view.mountPath ?? null })}- >- {view.openLabel}- </Button>- </div>- </Section>- ) : null}-- {view.requests.length > 0 ? (- <Section title={view.requestsTitle} kind="requests">- {view.requests.map((l) => (- <Line- key={l.id}- line={l}- busy={view.busy}- onAction={() => send({ type: "approve", id: l.id })}- onSecondary={() => send({ type: "deny", id: l.id })}- primary- />- ))}- </Section>- ) : null}-- <Section title={view.grantsTitle} kind="grants">- {view.grants.length === 0 ? (- <p className="px-4 py-3 text-[13px] text-muted-foreground" data-drive-grants-empty="">- {view.grantsEmpty}- </p>- ) : (- view.grants.map((l) => <Line key={l.id} line={l} busy={view.busy} onAction={() => send({ type: "revoke", id: l.id })} />)- )}- </Section>-- {spaceErrors.length > 0 ? (- <Section title="Spaces without Cua Volume" kind="space-errors">- {spaceErrors.map((e) => (- <div key={e.space} className="px-4 py-2.5" data-drive-space-error={e.space}>- <p className="truncate text-[13px] font-medium">{e.space}</p>- <p className="mt-0.5 text-xs text-muted-foreground" title={e.error}>- {volumeUnavailableNote(e.error)}- </p>- </div>- ))}- </Section>- ) : null}-- {view.devices.length > 0 || view.syncNote ? (- <Section title={view.devicesTitle} kind="devices">- {view.devices.map((l) => (- <Line key={l.id} line={l} busy={view.busy} />- ))}- {view.syncNote ? (- <p- className={cn("truncate px-4 py-2.5 text-xs", view.syncError ? "text-destructive" : "text-muted-foreground")}- title={view.syncNote}- data-drive-sync-note=""- data-error={view.syncError ? "true" : "false"}- >- {view.syncNote}- </p>- ) : null}- </Section>- ) : null}-- {view.conflicts.length > 0 ? (- <Section title={view.conflictsTitle} kind="conflicts">- {view.conflicts.map((c) => (- <Conflict- key={c.path}- conflict={c}- busy={view.busy}- onOpen={(path) => send({ type: "reveal", path })}- onResolve={() => send({ type: "resolve", path: c.path })}- />- ))}- </Section>- ) : null}-- {view.error ? (- <p className="px-1 text-[13px] text-destructive" role="alert" data-drive-error="">- {view.error}- </p>- ) : null}-- <StorageSection />- </div>- </Page>- );-}--function Section({ title, kind, children }: { title?: string; kind?: string; children: ReactNode }) {- return (- <section className="mb-6" data-drive-section={kind}>- {title ? (- <h2 className="mb-2 px-1 text-xs font-semibold text-muted-foreground" data-drive-section-title="">- {title}- </h2>- ) : null}- <div className="divide-y overflow-hidden rounded-xl border bg-card shadow-xs">{children}</div>- </section>- );-}--/** A `LineView`: its text, a muted trailing part, and up to two buttons. */-function Line({ line, busy, onAction, onSecondary, primary }: { line: LineView; busy: boolean; onAction?: () => void; onSecondary?: () => void; primary?: boolean }) {- return (- <div className="flex min-h-11 items-center gap-4 px-4 py-2" data-drive-line={line.id}>- <span className="min-w-0 flex-1 truncate text-[13px]" title={line.text} data-line-text="">- {line.text}- </span>- {line.trailing ? (- <span className="max-w-[40%] shrink-0 truncate text-xs text-muted-foreground" title={line.trailing} data-line-trailing="">- {line.trailing}- </span>- ) : null}- {line.secondaryLabel && onSecondary ? (- <Button variant="ghost" size="sm" disabled={busy} onClick={onSecondary} data-line-secondary="">- {line.secondaryLabel}- </Button>- ) : null}- {line.actionLabel && onAction ? (- <Button variant={primary ? "default" : "outline"} size="sm" disabled={busy} onClick={onAction} data-line-action="">- {line.actionLabel}- </Button>- ) : null}- </div>- );-}--function Conflict({ conflict: c, busy, onOpen, onResolve }: { conflict: ConflictView; busy: boolean; onOpen: (path: string) => void; onResolve: () => void }) {- return (- <div className="flex min-h-11 items-center gap-3 px-4 py-2" data-drive-conflict={c.path}>- <span className="min-w-0 flex-1 truncate text-[13px]" title={c.text} data-line-text="">- {c.text}- </span>- <span className="shrink-0 truncate text-xs text-muted-foreground" data-line-trailing="">- {c.trailing}- </span>- {c.openLabel && c.reveal ? (- <Button variant="ghost" size="sm" disabled={busy} title={c.reveal} data-conflict-open={c.reveal} onClick={() => onOpen(c.reveal!)}>- {c.openLabel}- </Button>- ) : null}- <Button variant="outline" size="sm" disabled={busy} onClick={onResolve} data-conflict-resolve="">- {c.resolveLabel}- </Button>- </div>- );-}diff --git a/apps/cua-spaces-web/src/lib/ask-first.test.ts b/apps/cua-spaces-web/src/lib/ask-first.test.tsindex 1b192a570e..be4a63ddf1 100644--- a/apps/cua-spaces-web/src/lib/ask-first.test.ts+++ b/apps/cua-spaces-web/src/lib/ask-first.test.ts@@ -93,7 +93,7 @@ describe("Ask-first tasks", () => {});const row = (id: string, more: Partial<Space> = {}): Space => ({ id, name: id, os: "linux", status: "running", detail: "", lastUsedAt: 0, scene: "linux-terminal", ...more });-const thisMac = row("this-mac", { name: "This computer", os: "macos", status: "local", provider: "local" });+const thisMac = row("this-mac", { name: "This machine", os: "macos", status: "local", provider: "local" });const LINUX: NewKind = { os: "linux", note: "Free.", blocked: null };const MAC: NewKind = { os: "macos", note: "Free.", blocked: null };const shared = { configured: true, mode: "relay" as const, machineId: "m-ada-mbp", sharing: true, shareDesktop: true };diff --git a/apps/cua-spaces-web/src/lib/ask-first.ts b/apps/cua-spaces-web/src/lib/ask-first.tsindex c7cb29cb37..5b1811156f 100644--- a/apps/cua-spaces-web/src/lib/ask-first.ts+++ b/apps/cua-spaces-web/src/lib/ask-first.ts@@ -46,7 +46,7 @@ export interface AskTask {lastStatus: AgentRunStatus | null;/** It runs on this Mac itself (its own Space id is in `spaceId`): nothing to throw away. */onHost?: boolean;- /** Started in its Space's thread (the redesign): the job is the Space's first message, @mentioning the agent. */+ /** Started in its Space's thread: the job is the Space's first message, @mentioning the agent. */inSpace?: boolean;}@@ -320,7 +320,7 @@ export function startErrorView(raw: string, agent: string): StartErrorView {};// A task from before this Mac was turned into its own Space id: trying again now works.if (e.includes(`"${THIS_MAC_ID}"`))- return { title: "Couldn't start on this Mac", body: "Try again to start it on this Mac, or pick another computer.", action: "retry", retry: true };+ return { title: "Couldn't start on this Mac", body: "Try again to start it on this Mac, or pick another machine.", action: "retry", retry: true };if (/cloud has ended/.test(e))return { title: "That computer is no longer available", body: "Cua Cloud has ended. Pick a computer on this Mac instead.", action: "change-computer", retry: false };if (/more than one|ambiguous/.test(e))@@ -333,7 +333,7 @@ export function startErrorView(raw: string, agent: string): StartErrorView {return { title: "Couldn't reach that computer", body: "Check it's on, then try again. Or pick another one.", action: "retry", retry: true };if (/disk|space left|no room|memory|quota|limit/.test(e))return { title: "This Mac doesn't have room for a new computer", body: "Free some disk space or turn off a computer you're not using, then try again.", action: "retry", retry: true };- return { title: `${agent} couldn't start`, body: "Something went wrong. Try again, or pick another computer.", action: "retry", retry: true };+ return { title: `${agent} couldn't start`, body: "Something went wrong. Try again, or pick another machine.", action: "retry", retry: true };}/** Where a task stands, in the words Home and the thread use. */@@ -380,7 +380,7 @@ export const SUGGESTIONS: { title: string; detail: string; os: SpaceOs; prompt:title: "Run my project's tests on a clean Linux computer",detail: "Find out if it works on a computer that has never seen your code.",os: "linux",- prompt: "Copy my project onto this computer, install what it needs and run its tests. Tell me what passed and what failed: ",+ prompt: "Copy my project onto this machine, install what it needs and run its tests. Tell me what passed and what failed: ",},{title: "Try a pull request before merging",diff --git a/apps/cua-spaces-web/src/lib/cli-commands.test.ts b/apps/cua-spaces-web/src/lib/cli-commands.test.tsindex 16a8a97ff1..73bc5baa9a 100644--- a/apps/cua-spaces-web/src/lib/cli-commands.test.ts+++ b/apps/cua-spaces-web/src/lib/cli-commands.test.ts@@ -69,12 +69,12 @@ describe("New Space's create", () => {});describe("opening the Space", () => {- it("is `sb view NAME` for a named Space on this computer", () => {+ it("is `sb view NAME` for a named Space on this machine", () => {expect(openCommand(STABLE, { ...linux, name: "dev" })).toBe("cua sb view dev");expect(openCommand(LOCAL, { ...linux, name: "my space" })).toBe("cua-local sb view 'my space'");});- it("is not offered without a name, or for another computer's Space", () => {+ it("is not offered without a name, or for another machine's Space", () => {expect(openCommand(STABLE, linux)).toBeNull();expect(openCommand(STABLE, { ...linux, name: "dev", on: "host:abc" })).toBeNull();});diff --git a/apps/cua-spaces-web/src/lib/design-baseline.json b/apps/cua-spaces-web/src/lib/design-baseline.jsonindex 5323861f4b..c43a224126 100644--- a/apps/cua-spaces-web/src/lib/design-baseline.json+++ b/apps/cua-spaces-web/src/lib/design-baseline.json@@ -24,6 +24,10 @@"components/agents/key-sheet.tsx": {"partial-line": 1},+ "components/agents/other-machine-block.tsx": {+ "outlined-box": 1,+ "partial-line": 1+ },"components/agents/run-agent-dialog.tsx": {"partial-line": 1,"outlined-box": 1@@ -33,15 +37,13 @@"partial-line": 1},"components/ask-first/ask-box.tsx": {- "dot-chain": 1,"outlined-box": 6,"radius": 5,"partial-line": 1},"components/ask-first/home.tsx": {- "radius": 5,- "outlined-box": 4,- "partial-line": 1+ "radius": 1,+ "outlined-box": 1},"components/ask-first/task-view.tsx": {"partial-line": 5,@@ -60,6 +62,10 @@"components/keyvault/options-dialog.tsx": {"partial-line": 1},+ "components/machines/account-parts.tsx": {+ "partial-line": 8,+ "outlined-box": 2+ },"components/markdown.tsx": {"partial-line": 2,"outlined-box": 1,@@ -92,6 +98,7 @@},"components/shell/sidebar.tsx": {"partial-line": 3,+ "pill": 1,"outlined-box": 1,"radius": 1},@@ -143,6 +150,9 @@"partial-line": 1,"radius": 1},+ "components/space-thread/thread-view.tsx": {+ "partial-line": 1+ },"components/spaces/selection.tsx": {"radius": 2},@@ -176,7 +186,7 @@"partial-line": 13},"routes/onboarding/index.tsx": {- "pill": 13,+ "pill": 14,"outlined-box": 7,"partial-line": 2,"radius": 5@@ -184,10 +194,6 @@"routes/settings/about.tsx": {"partial-line": 1},- "routes/settings/devices.tsx": {- "outlined-box": 3,- "partial-line": 3- },"routes/settings/route.tsx": {"radius": 1},diff --git a/apps/cua-spaces-web/src/lib/devices.test.ts b/apps/cua-spaces-web/src/lib/devices.test.tsindex d3ea09a636..516c5ea1f7 100644--- a/apps/cua-spaces-web/src/lib/devices.test.ts+++ b/apps/cua-spaces-web/src/lib/devices.test.ts@@ -3,21 +3,10 @@import { describe, expect, it } from "vitest";-import { devicesPageState, shellDevicesBanner } from "./devices";--describe("devicesPageState", () => {- it("never leaves the Devices tab blank", () => {- expect(devicesPageState({ error: null, data: undefined }, true)).toBe("loading");- expect(devicesPageState({ error: new Error("relay timed out"), data: undefined }, true)).toBe("error");- expect(devicesPageState({ error: null, data: { view: null } }, true)).toBe("no-view");- expect(devicesPageState({ error: null, data: { view: {} } }, true)).toBe("ready");- expect(devicesPageState({ error: null, data: undefined }, false)).toBe("signed-out");- expect(devicesPageState({ unsupported: true, error: null }, true)).toBe("unsupported");- });-});+import { shellDevicesBanner } from "./devices";describe("shellDevicesBanner", () => {- const banner = { tone: "warning" as const, text: "Enroll this device within 3 days to keep reaching your machines.", action: "enroll" as const, actionLabel: "Enroll…" };+ const banner = { tone: "warning" as const, text: "Trust this machine within 3 days to keep reaching your machines.", action: "enroll" as const, actionLabel: "Trust this machine" };const read = (input: { devices?: { id: string; state: string }[]; readError?: string | null }) => ({ input, view: { banner } });it("shows the core's bar once signed in and read", () => {diff --git a/apps/cua-spaces-web/src/lib/devices.ts b/apps/cua-spaces-web/src/lib/devices.tsindex 1e000f0cd6..af52ab0ecd 100644--- a/apps/cua-spaces-web/src/lib/devices.ts+++ b/apps/cua-spaces-web/src/lib/devices.ts@@ -1,10 +1,10 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-// Words the Devices page formats itself (the core leaves dates to the shell,+// Words the Machines page formats itself (the core leaves dates to the shell,// as the SwiftUI app's `DevicesModel` does).-import type { DeviceBanner, DeviceRow, DevicesInput, DevicesLabels, DevicesView, ThisDevice } from "@/bridge";+import type { DeviceBanner, DevicesInput, DevicesView } from "@/bridge";/** "Oct 27, 2026" (a medium date, no time). */export function dateText(secs: number, locale?: string): string {@@ -24,55 +24,12 @@ export function relativeText(secs: number, nowSecs: number, locale?: string): streturn f.format(Math.round(diff / (365 * 86_400)), "year");}-/** "Enrolled until Oct 27, 2026" (`DevicesModel.thisDeviceText`). */-export function thisDeviceText(t: ThisDevice, locale?: string): string {- return t.at === null ? t.title : `${t.title} ${dateText(t.at, locale)}`;-}--/** A row's second line: platform and state, then when it was last seen (`DevicesModel.rowDetail`). */-export function rowDetail(r: DeviceRow, labels: DevicesLabels, nowSecs: number, locale?: string): string {- return r.lastSeen === null ? r.detail : `${r.detail} · ${labels.lastSeen} ${relativeText(r.lastSeen, nowSecs, locale)}`;-}--export type DeviceKind = "laptop" | "desktop" | "phone" | "unknown";--/** Which icon a platform gets (`DevicesSettingsView.symbol`). */-export function deviceKind(platform: string): DeviceKind {- switch (platform) {- case "macOS":- return "laptop";- case "Windows":- case "Linux":- case "FreeBSD":- return "desktop";- case "iOS":- case "Android":- return "phone";- default:- return "unknown";- }-}--/** What the Devices tab draws: never nothing (a slow relay read once left it blank). */-export type DevicesPageState = "unsupported" | "signed-out" | "error" | "loading" | "no-view" | "ready";--export function devicesPageState(- r: { unsupported?: boolean; error: Error | null; data?: { view: unknown } | undefined },- signedIn: boolean | undefined,-): DevicesPageState {- if (r.unsupported) return "unsupported";- if (signedIn === false) return "signed-out";- if (r.error && !r.data) return "error";- if (!r.data) return "loading";- return r.data.view ? "ready" : "no-view";-}-/*** The bar above every page when this device needs enrolling or re-verifying* (`DevicesModel.banner` in the SwiftUI app): signed in, and only once the* relay was read. A first read the relay refused leaves no list behind (the* hosts send an empty one with `readError`), and the SwiftUI app shows no- * bar then either; Settings, Devices says why.+ * bar then either; This machine's page in Machines says why.*/export function shellDevicesBanner(data: { input: Pick<DevicesInput, "devices" | "readError">; view: Pick<DevicesView, "banner"> | null } | undefined,diff --git a/apps/cua-spaces-web/src/lib/host-labels.test.ts b/apps/cua-spaces-web/src/lib/host-labels.test.tsindex f3d9306383..76c77674c3 100644--- a/apps/cua-spaces-web/src/lib/host-labels.test.ts+++ b/apps/cua-spaces-web/src/lib/host-labels.test.ts@@ -32,7 +32,7 @@ describe("host labels", () => {expect(showsMacShellSettings("Linux x86_64")).toBe(false);});- it("names this computer in a Space being created here", () => {+ it("names this machine in a Space being created here", () => {const line = "This Mac \u00b7 Downloading image\u2026";expect(creatingLine(line, "darwin")).toBe(line);expect(creatingLine(line, "linux")).toBe("This machine \u00b7 Downloading image\u2026");@@ -42,7 +42,7 @@ describe("host labels", () => {expect(creatingLine("This Mac can't reach its new VM", "linux")).toBe("This Mac can't reach its new VM");});- it("names this computer in what leaves it on teleport", () => {+ it("names this machine in what leaves it on teleport", () => {expect(leavesLine("191 KB leaves this Mac", "darwin")).toBe("191 KB leaves this Mac");expect(leavesLine("191 KB leaves this Mac", "win32")).toBe("191 KB leaves this PC");expect(leavesLine("191 KB leaves this Mac", "linux")).toBe("191 KB leaves this machine");diff --git a/apps/cua-spaces-web/src/lib/machines-account.ts b/apps/cua-spaces-web/src/lib/machines-account.tsnew file mode 100644index 0000000000..f6ffc301ea--- /dev/null+++ b/apps/cua-spaces-web/src/lib/machines-account.ts@@ -0,0 +1,12 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import type { AccessLine } from "@/bridge";++/** Newest access lines one machine's page shows (`machines_account::RECENT_PER_MACHINE`). */+export const RECENT_PER_MACHINE = 5;++/** Who reached one machine, newest first: the lines for its id, or (a machine that only signed in) its sign-in's. */+export function accessFor(lines: readonly AccessLine[], machine: string, device: string | null): AccessLine[] {+ return lines.filter((l) => l.machine === machine || (device !== null && l.device === device && l.machine === null)).slice(0, RECENT_PER_MACHINE);+}diff --git a/apps/cua-spaces-web/src/lib/machines.test.ts b/apps/cua-spaces-web/src/lib/machines.test.tsindex 541dcfa65d..a3d07a667e 100644--- a/apps/cua-spaces-web/src/lib/machines.test.ts+++ b/apps/cua-spaces-web/src/lib/machines.test.ts@@ -37,13 +37,13 @@ describe("machines", () => {expect(connectionLabel(machine({}))).toBe("Cua relay");expect(connectionLabel(machine({ connection: "direct" }))).toBe("Direct");expect(connectionLabel(machine({ connection: null, current: true }))).toBe("Not set up for access");- expect(machineSubtitle(machine({ model: "Mac mini" }))).toBe("Mac mini · Cua relay");- expect(machineSubtitle(machine({ os: "windows", connection: "direct" }))).toBe("Windows · Direct");+ expect(machineSubtitle(machine({ model: "Mac mini" }))).toBe("Mac mini, Cua relay");+ expect(machineSubtitle(machine({ os: "windows", connection: "direct" }))).toBe("Windows, Direct");});- it("labels a signed-in device apart from a machine's connection", () => {- expect(connectionLabel(machine({ connection: null, device: true }))).toBe("Signed-in device, not shared");- expect(machineSubtitle(machine({ os: "windows", connection: null, device: true }))).toBe("Windows · Signed-in device, not shared");+ it("labels a signed-in machine apart from a machine's connection", () => {+ expect(connectionLabel(machine({ connection: null, device: true }))).toBe("Signed in, not sharing");+ expect(machineSubtitle(machine({ os: "windows", connection: null, device: true }))).toBe("Windows, Signed in, not sharing");expect(connectionLabel(machine({ connection: "relay", device: true }))).toBe("Cua relay");expect(connectionLabel(machine({ connection: null, current: true }))).toBe("Not set up for access");expect(connectionLabel(machine({ connection: null, current: false }))).toBe("Unknown");diff --git a/apps/cua-spaces-web/src/lib/machines.ts b/apps/cua-spaces-web/src/lib/machines.tsindex 8224a3540a..0060c82671 100644--- a/apps/cua-spaces-web/src/lib/machines.ts+++ b/apps/cua-spaces-web/src/lib/machines.ts@@ -27,10 +27,10 @@ export const CONNECTION_LABEL: Record<"relay" | "direct", string> = {direct: "Direct",};-/** A row that is only a signed-in device (`machines_view::DEVICE_LINE`). */-export const DEVICE_LINE = "Signed-in device, not shared";+/** A row that is only a signed-in machine (`machines_view::DEVICE_LINE`). */+export const DEVICE_LINE = "Signed in, not sharing";-/** How other devices reach it, in words. */+/** How other machines reach it, in words. */export function connectionLabel(m: Pick<Machine, "connection" | "current"> & Pick<Partial<Machine>, "device">): string {if (m.connection) return CONNECTION_LABEL[m.connection];if (m.device) return DEVICE_LINE;@@ -39,7 +39,7 @@ export function connectionLabel(m: Pick<Machine, "connection" | "current"> & Pic/** The list row's second line: OS, then how it is reached. */export function machineSubtitle(m: Pick<Machine, "os" | "connection" | "current" | "model"> & Pick<Partial<Machine>, "device">): string {- return [m.model ?? osName(m), connectionLabel(m)].join(" · ");+ return [m.model ?? osName(m), connectionLabel(m)].join(", ");}/** The core's word for a machine its owner stopped sharingdiff --git a/apps/cua-spaces-web/src/lib/other-machine.test.ts b/apps/cua-spaces-web/src/lib/other-machine.test.tsnew file mode 100644index 0000000000..826bcb10e5--- /dev/null+++ b/apps/cua-spaces-web/src/lib/other-machine.test.ts@@ -0,0 +1,26 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { describe, expect, it } from "vitest";++import { desktopSpace, otherMachineCommand, otherMachinePrompt, OTHER_MACHINE_PERMISSIONS, OTHER_MACHINE_RELOAD } from "./other-machine";++describe("an agent on another machine", () => {+ it("signs in to the same account, then sets up the agent", () => {+ expect(otherMachineCommand("hermes")).toBe("cua auth login\ncua agents setup --agents hermes --yes");+ expect(otherMachineCommand("claude-code")).toBe("cua auth login\ncua agents setup --agents claude --yes");+ });++ it("names this machine's desktop Space by its relay id", () => {+ expect(desktopSpace("0123abcd")).toBe("relay:0123abcd");+ expect(otherMachinePrompt("Ada's Mac", "0123abcd")).toContain('space="relay:0123abcd"');+ // Before this machine is set up for access, the agent is told how to find it instead.+ expect(otherMachinePrompt("Ada's Mac", undefined)).toContain("list_spaces");+ });++ it("says what the machine must allow and that the agent needs a restart", () => {+ expect(OTHER_MACHINE_PERMISSIONS).toMatch(/share its desktop/);+ expect(OTHER_MACHINE_RELOAD).toMatch(/Restart the agent/);+ for (const text of [OTHER_MACHINE_PERMISSIONS, OTHER_MACHINE_RELOAD]) expect(text).not.toMatch(/·|device/i);+ });+});diff --git a/apps/cua-spaces-web/src/lib/other-machine.ts b/apps/cua-spaces-web/src/lib/other-machine.tsnew file mode 100644index 0000000000..bd48ab5ed8--- /dev/null+++ b/apps/cua-spaces-web/src/lib/other-machine.ts@@ -0,0 +1,33 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * What a person gives an agent on another machine so it can use this one: the host to name, the+ * exact commands, the permissions and the reload note. One place, so the Connect dialog and the+ * first run say the same thing.+ */++/** The Space an agent on another machine names to use this machine's desktop (`relay:<machine id>`). */+export const desktopSpace = (relayId: string) => `relay:${relayId}`;++/** The agent ids `cua agents setup --agents` takes, by the ids the app uses. */+const SETUP_ID = { "claude-code": "claude", codex: "codex", hermes: "hermes", openclaw: "openclaw" } as const;++/** The commands for `agent`, run on the other machine (not this one): the same account, then Cua's server and skills in the agent. */+export function otherMachineCommand(agent: keyof typeof SETUP_ID): string {+ return `cua auth login\ncua agents setup --agents ${SETUP_ID[agent]} --yes`;+}++/** What to tell the agent once it has the server: which machine, which Space. */+export function otherMachinePrompt(name: string, relayId: string | undefined): string {+ return relayId+ ? `Use Cua to control "${name}": take a screenshot with computer_screenshot and space="${desktopSpace(relayId)}".`+ : `Use Cua to control "${name}": list the machines with list_spaces and use its Space.`;+}++/** The permissions line: what the machine must allow, and how to give the agent less. */+export const OTHER_MACHINE_PERMISSIONS =+ "This machine has to share its desktop (its page in Machines, Let other machines control this desktop) and be online. The agent gets every Cua tool by default; add --permissions computer:all to cua mcp to give it only the computer tools.";++/** Why a reload is needed. */+export const OTHER_MACHINE_RELOAD = "Restart the agent after adding the server so it loads the tools.";diff --git a/apps/cua-spaces-web/src/lib/resources.test.ts b/apps/cua-spaces-web/src/lib/resources.test.tsindex 758612ea92..2294ad87cb 100644--- a/apps/cua-spaces-web/src/lib/resources.test.ts+++ b/apps/cua-spaces-web/src/lib/resources.test.ts@@ -134,7 +134,7 @@ describe("meters", () => {expect(systemName(undefined)).toBeNull();});- it("says how old another computer's summary is", () => {+ it("says how old another machine's summary is", () => {expect(updatedAgo(0, 30_000)).toBe("just now");expect(updatedAgo(0, 2 * 60_000)).toBe("2 min ago");expect(updatedAgo(0, 3 * 3_600_000)).toBe("3 hours ago");diff --git a/apps/cua-spaces-web/src/lib/settings-copy.test.ts b/apps/cua-spaces-web/src/lib/settings-copy.test.tsindex b7108ff431..1e1d9cf3e9 100644--- a/apps/cua-spaces-web/src/lib/settings-copy.test.ts+++ b/apps/cua-spaces-web/src/lib/settings-copy.test.ts@@ -3,38 +3,14 @@import { describe, expect, it } from "vitest";-import { plainDevice, plainDeviceSentence, plainKeysIntro } from "./settings-copy";+import { lastChecked, plainStorage } from "./settings-copy";-describe("plainDevice", () => {- it.each([- ["Enroll…", "Trust this machine"],- ["Enrolled until Nov 18, 2026", "Trusted until Nov 18, 2026"],- ["Re-verification due", "Needs a quick check"],- ["macOS · Enrolled · re-verify in 24 days", "macOS · Trusted · check again in 24 days"],- ["Revoke…", "Remove"],- ["This Device", "This machine"],- ["Your Devices", "Your machines"],- ["Recent Access", "Recent activity"],- ["New Computers", "Machines waiting for you"],- ["Rename", "Rename"],- ])("%s as %s", (from, to) => expect(plainDevice(from)).toBe(to));-});--describe("plainDeviceSentence", () => {- it("rewrites a banner and a dialog", () => {- expect(plainDeviceSentence("Enroll this device to reach your machines.")).toBe("Trust this machine to reach your machines.");- expect(plainDeviceSentence("This device will no longer list or reach your machines until you enroll it again.")).toBe(- "This machine will no longer list or reach your machines until you trust it again.",- );- expect(plainDeviceSentence("An unenrolled device opened mac-mini")).toBe("An untrusted device opened mac-mini");+describe("settings copy", () => {+ it("says last checked", () => {+ expect(lastChecked("Last check: 2 minutes ago")).toBe("Last checked 2 minutes ago");});-});-describe("plainKeysIntro", () => {- it("says account key, and keeps the system's words about where keys stay", () => {- const core = "Agents in your Spaces need a provider key to run. Keys stay on this PC in Windows Credential Manager, and each one is only given to the agents that use it.";- expect(plainKeysIntro(core)).toBe(- "Agents in your Spaces need an account key from their AI company to run. Keys stay on this PC in Windows Credential Manager, and each one is only given to the agents that use it.",- );+ it("calls S3-compatible storage your own storage", () => {+ expect(plainStorage("S3-compatible bucket")).toBe("Your own storage (S3)");});});diff --git a/apps/cua-spaces-web/src/lib/settings-copy.ts b/apps/cua-spaces-web/src/lib/settings-copy.tsindex 9cae4a4d3a..20235d440b 100644--- a/apps/cua-spaces-web/src/lib/settings-copy.ts+++ b/apps/cua-spaces-web/src/lib/settings-copy.ts@@ -2,70 +2,9 @@// Copyright (c) 2026 Cua AI, Inc./**- * Plain words for Settings. The app core still sends the old labels- * (`enrolled`, `revoke`, `re-verify`); the Settings pages show these instead,- * so a high-schooler can read them. One list, one place to change a word.+ * Plain words for Settings: the few labels the pages say in their own words.*/-const DEVICE_WORDS: readonly [RegExp, string][] = [- [/^Enroll…?$/, "Trust this machine"],- [/^Enroll This Mac…?$/, "Trust this machine"],- [/^Re-verify This Mac…?$/, "Trust this machine"],- [/^Enrolled until\b/, "Trusted until"],- [/^Enrolled$/, "Trusted"],- [/^Needs enrollment\b/, "Not trusted yet"],- [/^Re-verification due$/, "Needs a quick check"],- [/^Revoked$/, "Removed"],- [/\bre-verify in\b/, "check again in"],- [/\bRe-verification due\b/, "Needs a quick check"],- [/\bEnrolled\b/, "Trusted"],- [/^Revoke…?$/, "Remove"],- [/^Revoke$/, "Remove"],- [/^This Device$/, "This machine"],- [/^Your Devices$/, "Your machines"],- [/^Recent Access$/, "Recent activity"],- [/^No access yet$/, "No activity yet"],- [/^New Computers$/, "Machines waiting for you"],-];--/** One Devices label or detail line in plain words; anything it does not know stays as it is. */-export function plainDevice(text: string): string {- return DEVICE_WORDS.reduce((out, [from, to]) => out.replace(from, to), text);-}--const SENTENCE_WORDS: readonly [RegExp, string][] = [- [/\bunenrolled\b/g, "untrusted"],- [/\bEnroll\b/g, "Trust"],- [/\benroll\b/g, "trust"],- [/\benrolled\b/g, "trusted"],- [/\bEnrolled\b/g, "Trusted"],- [/\bRe-verification is due\b/g, "It needs a quick check"],- [/\bRe-verify\b/g, "Check"],- [/\bre-verify\b/g, "check"],- [/\bRevoke\b/g, "Remove"],- [/\brevoke\b/g, "remove"],- [/\brevoked\b/g, "removed"],- [/\bThis Device\b/g, "This machine"],- [/\bThis device\b/g, "This machine"],- [/\bthis device\b/g, "this machine"],-];--/** A whole sentence (a banner, a dialog, an activity line) in plain words. */-export function plainDeviceSentence(text: string): string {- return SENTENCE_WORDS.reduce((out, [from, to]) => out.replace(from, to), plainDevice(text));-}--/** The keys page's line under the list, with "provider key" as "account key from their AI company". */-export function plainKeysIntro(intro: string): string {- return intro.replace("need a provider key to run.", "need an account key from their AI company to run.");-}--/** Settings, Connectors, Account keys. */-export const KEYS_TITLE = "Account keys";-export const KEYS_ADD_OTHER_LABEL = "Add a key for another AI company";-export const KEYS_ADD_OTHER_BUTTON = "Add key";-export const KEYS_OTHER_HELP = "Use the name its app expects, like GEMINI_API_KEY.";-/** Launch at login, General. */export const LAUNCH_LABEL = "Start Cua Spaces when you sign in";export const LAUNCH_HELP = "Keeps your machines reachable after a restart.";diff --git a/apps/cua-spaces-web/src/lib/settings-tabs.ts b/apps/cua-spaces-web/src/lib/settings-tabs.tsindex 40cb836473..c8a678bbc2 100644--- a/apps/cua-spaces-web/src/lib/settings-tabs.ts+++ b/apps/cua-spaces-web/src/lib/settings-tabs.ts@@ -6,7 +6,6 @@ export const SETTINGS_TABS = [{ to: "/settings", label: "Account", exact: true },{ to: "/settings/general", label: "General", exact: false },{ to: "/settings/connectors", label: "Connectors", exact: false },- { to: "/settings/devices", label: "Trusted machines", exact: false },{ to: "/settings/advanced", label: "Advanced", exact: false },{ to: "/settings/about", label: "About", exact: false },] as const;diff --git a/apps/cua-spaces-web/src/lib/spaces.test.ts b/apps/cua-spaces-web/src/lib/spaces.test.tsindex 38a05fba06..ce81d96ac2 100644--- a/apps/cua-spaces-web/src/lib/spaces.test.ts+++ b/apps/cua-spaces-web/src/lib/spaces.test.ts@@ -118,7 +118,7 @@ describe("space actions", () => {describe("isMachineDesktop / realSpaces", () => {it("leaves this Mac and relay machines' own desktops out of the Spaces", () => {const rows: Space[] = [- space("this-mac", "suspended", 1, { provider: "local", name: "This computer" }),+ space("this-mac", "suspended", 1, { provider: "local", name: "This machine" }),space("local-desktop", "local", 1, { provider: "local" }),space("relay:96fedb7e1be65c3d31fa18587febde2c", "running", 1, { name: "gamma-4 Mac Studio" }),space("relay:space-ca12d6d23907f387", "running", 1, { host: "96fedb7e1be65c3d31fa18587febde2c" }),diff --git a/apps/cua-spaces-web/src/lib/spaces.ts b/apps/cua-spaces-web/src/lib/spaces.tsindex 588ffe2031..dabf510daa 100644--- a/apps/cua-spaces-web/src/lib/spaces.ts+++ b/apps/cua-spaces-web/src/lib/spaces.ts@@ -140,7 +140,7 @@ export function elsewhereOs(c: Pick<CreatingElsewhere, "os">): SpaceOs {export function creatingElsewherePlace(c: Pick<CreatingElsewhere, "os" | "machineName">): string {const os = elsewhereOs(c);const what = os === "unknown" ? "a Space" : OS_NAME[os];- return `Creating ${what} on ${c.machineName.trim() || "another computer"}…`;+ return `Creating ${what} on ${c.machineName.trim() || "another machine"}…`;}/** How far it got: "40%". */@@ -268,7 +268,7 @@ export function canDelete(space: Pick<Space, "id" | "status" | "cloudDelete">):const PROVIDER: Record<Exclude<NonNullable<Space["provider"]>, "local">, string> = {relay: "Your computer, through the Cua relay",- direct: "A computer added by address",+ direct: "A machine added by address",};/** Where it runs, in words. */diff --git a/apps/cua-spaces-web/src/routes/__root.tsx b/apps/cua-spaces-web/src/routes/__root.tsxindex 942250d419..6a996d4d18 100644--- a/apps/cua-spaces-web/src/routes/__root.tsx+++ b/apps/cua-spaces-web/src/routes/__root.tsx@@ -9,10 +9,7 @@ import { useBridge, useSavedOnboarding, useSession, useStartup } from "@/bridge"import { NewSpace } from "@/components/new-space";import { CommandPalette } from "@/components/shell/command-palette";import { DevicesBanner } from "@/components/shell/devices-banner";-import { useFlag } from "@/bridge/flags";import { Sidebar } from "@/components/shell/sidebar";-import { ChecklistTracker } from "@/legacy/components/getting-started";-import { Sidebar as LegacySidebar } from "@/legacy/components/shell/sidebar";import { PlanLimitToastAction } from "@/components/shell/plan-limit-toast-action";import { RelayAllowanceNotice } from "@/components/shell/relay-allowance-notice";import { ShareRemovalNotice } from "@/components/shell/share-removal-notice";@@ -33,8 +30,6 @@ export const Route = createRootRoute({ component: RootLayout });const StartupScreen = lazy(() => import("@/components/startup/StartupScreen").then((m) => ({ default: m.StartupScreen })));function RootLayout() {- // `spaces_redesign` off: the sidebar and the getting-started checklist as they were.- const redesign = useFlag("spaces_redesign");useThemeSync();useThemeHostSync();const { mode } = useBridge();@@ -73,7 +68,7 @@ function RootLayout() {return (<div className="flex h-full bg-chrome">- {sidebarOpen ? redesign ? <Sidebar /> : <LegacySidebar /> : null}+ {sidebarOpen ? <Sidebar /> : null}<div className="flex min-w-0 flex-1 flex-col bg-background"><TopBar /><DevicesBanner />@@ -86,7 +81,6 @@ function RootLayout() {</div><PlanLimitToastAction /><CommandPalette />- {redesign ? null : <ChecklistTracker />}<NewSpace /><SpaceSheets /><ThisMacNudges />diff --git a/apps/cua-spaces-web/src/routes/agents/index.tsx b/apps/cua-spaces-web/src/routes/agents/index.tsxindex 150b434199..44019beba6 100644--- a/apps/cua-spaces-web/src/routes/agents/index.tsx+++ b/apps/cua-spaces-web/src/routes/agents/index.tsx@@ -4,11 +4,9 @@import { createFileRoute, useNavigate } from "@tanstack/react-router";import { useEffect, useState } from "react";-import { useAgentChats, useFeatureRecorded, useSession } from "@/bridge";+import { useAgentChats, useFeatureRecorded, useKeysRecheck, useSession } from "@/bridge";import { AgentDmView, AgentList, AgentPage, AgentsEmpty, NewAgentSheet } from "@/components/agents/agent-chat";import type { AddAgentStage } from "@/components/add-agent/add-agent-sheet";-import { useFlag } from "@/bridge/flags";-import { LegacyAgentsPage } from "@/legacy/routes/agents/index";import { useAgentAttempts, useAttemptAction } from "@/hooks/use-agent-attempts";/** Which agent's DM is open, and in which of its Spaces (none: all of them). */@@ -19,11 +17,11 @@ interface ChatSearch {}export const Route = createFileRoute("/agents/")({- component: AgentsChatPageSwitch,+ component: AgentsChatPage,validateSearch: (s: Record<string, unknown>): ChatSearch => ({agent: typeof s.agent === "string" ? s.agent : undefined,space: typeof s.space === "string" ? s.space : undefined,- // The page before the redesign opens a run with `?run=`.+ // The older Agents page opened a run with `?run=`.run: typeof s.run === "string" ? s.run : undefined,}),});@@ -45,6 +43,8 @@ function useNow(ms = 30_000): number {*/function AgentsChatPage() {useFeatureRecorded("agents_page_open");+ // Opening the Agents page asks the providers whether the saved sign-ins and keys still work.+ useKeysRecheck();const search = Route.useSearch();const navigate = useNavigate({ from: "/agents/" });const { data: session } = useSession();@@ -100,8 +100,3 @@ function AgentsChatPage() {</div>);}--/** The redesign behind `spaces_redesign` (Settings → Advanced → Labs); off, the page as it was. */-function AgentsChatPageSwitch() {- return useFlag("spaces_redesign") ? <AgentsChatPage /> : <LegacyAgentsPage />;-}diff --git a/apps/cua-spaces-web/src/routes/keyvault/index.tsx b/apps/cua-spaces-web/src/routes/keyvault/index.tsxindex dba678ca47..30ebea6981 100644--- a/apps/cua-spaces-web/src/routes/keyvault/index.tsx+++ b/apps/cua-spaces-web/src/routes/keyvault/index.tsx@@ -5,13 +5,11 @@ import { createFileRoute } from "@tanstack/react-router";import type { KvCategory } from "@/bridge";import { KeyvaultPage } from "@/components/keyvault/keyvault-page";-import { useFlag } from "@/bridge/flags";-import { LegacyKeyvaultPage } from "@/legacy/routes/keyvault/index";const CATEGORIES: readonly KvCategory[] = ["all", "waiting", "access", "recent"];export const Route = createFileRoute("/keyvault/")({- component: KeyvaultRouteSwitch,+ component: KeyvaultRoute,// A Space's "Signed in" badge opens Access with that Space's row brought forward.validateSearch: (s: Record<string, unknown>): { view?: KvCategory; focus?: string } => ({view: CATEGORIES.find((c) => c === s.view),@@ -23,8 +21,3 @@ function KeyvaultRoute() {const { view, focus } = Route.useSearch();return <KeyvaultPage initialView={view} focus={focus ?? null} />;}--/** The redesign behind `spaces_redesign` (Settings → Advanced → Labs); off, the page as it was. */-function KeyvaultRouteSwitch() {- return useFlag("spaces_redesign") ? <KeyvaultRoute /> : <LegacyKeyvaultPage />;-}diff --git a/apps/cua-spaces-web/src/routes/machines/index.tsx b/apps/cua-spaces-web/src/routes/machines/index.tsxindex ccc132d411..2a1dacc5fd 100644--- a/apps/cua-spaces-web/src/routes/machines/index.tsx+++ b/apps/cua-spaces-web/src/routes/machines/index.tsx@@ -19,8 +19,11 @@ import {type MachinesViewMachine,type MachinesViewRemove,type MachinesViewToggle,+ type PendingMachine,} from "@/bridge";import { AddComputerSheet } from "@/components/add-computer-sheet";+import { EnrollSheet, PendingDetail, PendingRow, RecentAccess, TrustSection, useMachinesAccount, usePendingActions } from "@/components/machines/account-parts";+import { accessFor } from "@/lib/machines-account";import { CloudDetail, CloudDot } from "@/components/clouds/cloud-detail";import { CloudLogo } from "@/components/cloud-logo";import { UpsellPrompt } from "@/components/upsell-prompt";@@ -38,9 +41,6 @@ import { useNewSpace } from "@/hooks/use-new-space";import { showDesktop } from "@/lib/hidden-desktops";import { machineOs, selectedMachine } from "@/lib/machines";import { cn } from "@/lib/utils";-import { useFlag } from "@/bridge/flags";-import { AddMachineDialog } from "@/legacy/components/add-machine-dialog";-import { JoinWithCodeDialog } from "@/legacy/components/join-with-code-dialog";export const Route = createFileRoute("/machines/")({component: MachinesPage,@@ -56,6 +56,25 @@ export const Route = createFileRoute("/machines/")({const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));+/** The view without the sign-ins that are waiting to be added (they are the top group). */+function withoutPending(view: MachinesView, pending: readonly PendingMachine[]): MachinesView {+ const waiting = new Set(pending.flatMap((p) => (p.kind === "sign-in" && p.device ? [p.device] : [])));+ if (waiting.size === 0) return view;+ return {+ ...view,+ machines: view.machines.filter((m) => !waiting.has(m.id)),+ groups: view.groups.map((g) => ({ ...g, ids: g.ids.filter((id) => !waiting.has(id)) })).filter((g) => g.ids.length > 0),+ };+}++/** "3 machines, 2 online", and what waits. */+function summaryText(view: MachinesView | null, waiting: number): string {+ const total = view?.machines.length ?? 0;+ const online = view?.machines.filter((m) => m.online).length ?? 0;+ const base = `${total} machine${total === 1 ? "" : "s"}, ${online} online`;+ return waiting > 0 ? `${base}, ${waiting} waiting` : base;+}+/** How often the page asks the machines for their health while it is open. */const HEALTH_EVERY_MS = 60_000;@@ -68,8 +87,11 @@ const HEALTH_EVERY_MS = 60_000;* actions (open, start, stop, teleport, drop files) stay on the Space.*/function MachinesPage() {- const { data: machines = [], isLoading, error, view, checkHealth, setupGuide } = useMachines();- const redesign = useFlag("spaces_redesign");+ const { data: machines = [], isLoading, error, view: fullView, checkHealth, remove } = useMachines();+ const { account, pending, now } = useMachinesAccount();+ const actions = usePendingActions();+ // 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]);// Each machine's issues come from its own daemon: asked on opening the// page and every minute while it stays open.useEffect(() => {@@ -93,17 +115,18 @@ function MachinesPage() {const shown = view?.machines ?? [];// A cloud is selected as `cloud:<id>`; a machine by its id.const cloudPage = selectedId?.startsWith("cloud:") ? view?.clouds?.pages.find((c) => c.id === selectedId.slice(6)) : undefined;- const selected = cloudPage ? undefined : selectedMachine(shown, selectedId?.startsWith("cloud:") ? null : selectedId);+ const pendingPage = selectedId?.startsWith("pending:") ? pending.find((p) => `pending:${p.id}` === selectedId) : undefined;+ const selected = cloudPage || pendingPage ? undefined : selectedMachine(shown, selectedId?.startsWith("cloud:") || selectedId?.startsWith("pending:") ? null : selectedId);const row = (id: string) => machines.find((m) => m.id === id);return (<Page contained className="max-w-6xl"><PageHeadertitle="Machines"- description={isLoading ? "Loading machines…" : view?.machines.length ? view.summary : "Machines that can run your Spaces."}+ description={isLoading ? "Loading machines…" : view?.machines.length || pending.length ? summaryText(view, pending.length) : "Machines that can run your Spaces."}actions={<Button onClick={() => setAdding(true)} data-machines-add>- <PlusIcon /> Add a machine+ <PlusIcon /> Add machine</Button>}/>@@ -113,14 +136,19 @@ function MachinesPage() {</EmptyState>) : isLoading || (!view && machines.length > 0) ? (<LoadingState />- ) : !view || view.machines.length === 0 ? (+ ) : !view || (view.machines.length === 0 && pending.length === 0) ? (<EmptyStateicon={<ServerIcon />}- title="No machines yet"+ title="Add your first machine"action={- <Button onClick={() => setAdding(true)}>- <PlusIcon /> Add a machine- </Button>+ <div className="flex gap-2">+ <Button onClick={() => setAdding(true)} data-machines-add-this>+ <PlusIcon /> This machine+ </Button>+ <Button variant="outline" onClick={() => setAdding(true)} data-machines-add-other>+ Another machine+ </Button>+ </div>}>Set up a Mac, Linux or Windows machine and it shows here, ready to run Spaces.@@ -128,27 +156,35 @@ function MachinesPage() {) : (<div className="grid min-h-0 flex-1 grid-cols-[minmax(0,320px)_minmax(0,1fr)] grid-rows-[minmax(0,1fr)] gap-8" data-machines-split=""><div className="min-h-0 overflow-y-auto overscroll-contain pr-1 pb-10" data-machines-list-scroll="">- <MachineList view={view} rows={machines} query={query} onQuery={setQuery} selectedId={cloudPage ? `cloud:${cloudPage.id}` : (selected?.id ?? null)} onSelect={setSelectedId} />+ <MachineList+ view={view}+ rows={machines}+ query={query}+ onQuery={setQuery}+ selectedId={cloudPage ? `cloud:${cloudPage.id}` : pendingPage ? `pending:${pendingPage.id}` : (selected?.id ?? null)}+ onSelect={setSelectedId}+ pending={pending}+ pendingTitle={account?.pendingTitle ?? "Waiting for you"}+ pendingBusy={actions.busy}+ onAdd={actions.add}+ onNotMe={actions.notMe}+ /><UpsellPrompt surface="machine" active={machines.length >= 2 && machines.some((m) => m.via === "relay")} className="mt-3" /></div><div className="min-h-0 overflow-y-auto overscroll-contain pb-10" data-machines-detail-scroll="">{cloudPage ? (<CloudDetail key={cloudPage.id} page={cloudPage} onGone={() => setSelectedId(null)} />+ ) : pendingPage ? (+ <PendingDetail key={pendingPage.id} machine={pendingPage} now={now} busy={actions.busy === pendingPage.id} onAdd={() => actions.add(pendingPage)} onNotMe={() => actions.notMe(pendingPage)} />) : selected ? (<MachineDetail key={selected.id} machine={selected} row={row(selected.id)} onRemoved={() => setSelectedId(null)} />) : null}</div></div>)}- {redesign ? (- <AddComputerSheet open={adding} onOpenChange={setAdding} initialView={join !== undefined ? "enter" : "pick"} initialCode={join ?? ""} initialRelay={relay ?? null} />- ) : (- // `spaces_redesign` off: "Add a computer" and "Join with a code" as they were.- <>- <AddMachineDialog open={adding && join === undefined} onOpenChange={setAdding} guide={setupGuide} />- <JoinWithCodeDialog open={adding && join !== undefined} onOpenChange={setAdding} initialCode={join ?? ""} initialRelay={relay ?? null} />- </>- )}+ <EnrollSheet />+ {actions.notMeDialog((machine) => remove(machine, null))}+ <AddComputerSheet open={adding} onOpenChange={setAdding} initialView={join !== undefined ? "enter" : "pick"} initialCode={join ?? ""} initialRelay={relay ?? null} /></Page>);}@@ -162,6 +198,11 @@ function MachineList({onQuery,selectedId,onSelect,+ pending,+ pendingTitle,+ pendingBusy,+ onAdd,+ onNotMe,}: {view: MachinesView;rows: Machine[];@@ -169,6 +210,11 @@ function MachineList({onQuery: (q: string) => void;selectedId: string | null;onSelect: (id: string) => void;+ pending: PendingMachine[];+ pendingTitle: string;+ pendingBusy: string | null;+ onAdd: (p: PendingMachine) => void;+ onNotMe: (p: PendingMachine) => void;}) {const { remove } = useMachines();const connect = useConnectCloud();@@ -236,6 +282,16 @@ function MachineList({className="min-w-0 flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted-foreground/70"/></label>+ {pending.length > 0 ? (+ <div data-machine-group="pending" data-pending-count={pending.length}>+ <div className="px-2 pt-3.5 pb-1 text-[11px] font-semibold tracking-[0.02em] text-muted-foreground">{pendingTitle}</div>+ {pending+ .filter((p) => !q || p.name.toLowerCase().includes(q))+ .map((p) => (+ <PendingRow key={p.id} machine={p} selected={selectedId === `pending:${p.id}`} busy={pendingBusy === p.id} onSelect={() => onSelect(`pending:${p.id}`)} onAdd={() => onAdd(p)} onNotMe={() => onNotMe(p)} />+ ))}+ </div>+ ) : null}<div role="listbox" aria-label="Machines">{(view.order ?? ["clouds", ...view.groups.map((g) => g.id)]).map((section) => {if (section === "clouds") return cloudsSection;@@ -421,6 +477,7 @@ function MachineRow({function MachineDetail({ machine: m, row, onRemoved }: { machine: MachinesViewMachine; row: Machine | undefined; onRemoved: () => void }) {const { data: session } = useSession();+ const { account, now, devices } = useMachinesAccount();const host = useThisMachine(session?.identity ?? null);const { remove } = useMachines();const [detailsOpen, setDetailsOpen] = useState(false);@@ -530,32 +587,38 @@ function MachineDetail({ machine: m, row, onRemoved }: { machine: MachinesViewMa{m.current ? <ThisMachineExtras panel={row?.panel ?? null} progress={row?.hostProgress} part="alerts" /> : null}- <h3 className="mt-7 mb-2 text-xs font-semibold text-muted-foreground">{m.spacesTitle}</h3>- <div className="border-y" data-machine-spaces>- {rows.map((s, i) => (- <Link- key={s.id}- to="/spaces/$spaceId"- params={{ spaceId: s.id }}- title={`Open ${s.name}`}- data-space-row={s.id}- className={cn("flex items-center gap-2.5 py-2.5 text-[13px] outline-none hover:bg-accent/40 focus-visible:bg-accent/50", i > 0 && "border-t")}- >- <span className="truncate font-mono text-xs">{s.name}</span>- {s.label ? <span className="shrink-0 rounded bg-muted px-1.5 text-2xs text-muted-foreground">{s.label}</span> : null}- {s.os ? <span className="truncate text-muted-foreground">{s.os}</span> : null}- <span className="ml-auto flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">- <StatusDot online={s.running} className="size-[7px]" />- {s.status}- </span>- <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground/60" />- </Link>- ))}- {m.spacesEmpty ? <p className={cn("py-3.5 text-xs text-muted-foreground", rows.length > 0 && "border-t")}>{m.spacesEmpty}</p> : null}- <div className="border-t py-2.5">- <NewSpaceHere machine={m} />- </div>- </div>+ {m.spacesTitle ? (+ <>+ <h3 className="mt-7 mb-2 text-xs font-semibold text-muted-foreground">{m.spacesTitle}</h3>+ <div className="border-y" data-machine-spaces>+ {rows.map((s, i) => (+ <Link+ key={s.id}+ to="/spaces/$spaceId"+ params={{ spaceId: s.id }}+ title={`Open ${s.name}`}+ data-space-row={s.id}+ className={cn("flex items-center gap-2.5 py-2.5 text-[13px] outline-none hover:bg-accent/40 focus-visible:bg-accent/50", i > 0 && "border-t")}+ >+ <span className="truncate font-mono text-xs">{s.name}</span>+ {s.label ? <span className="shrink-0 rounded bg-muted px-1.5 text-2xs text-muted-foreground">{s.label}</span> : null}+ {s.os ? <span className="truncate text-muted-foreground">{s.os}</span> : null}+ <span className="ml-auto flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">+ <StatusDot online={s.running} className="size-[7px]" />+ {s.status}+ </span>+ <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground/60" />+ </Link>+ ))}+ {m.spacesEmpty ? <p className={cn("py-3.5 text-xs text-muted-foreground", rows.length > 0 && "border-t")}>{m.spacesEmpty}</p> : null}+ <div className="border-t py-2.5">+ <NewSpaceHere machine={m} />+ </div>+ </div>+ </>+ ) : null}++ {account ? <RecentAccess lines={accessFor(account.access, m.current ? (row?.relayId ?? m.id) : m.id, m.current ? null : row?.device ? m.id : null)} title={account.recentTitle} empty={account.recentEmpty} now={now} error={m.current && account.thisMachine?.kind === "enrolled" ? account.readError : null} /> : null}<div className="mt-6"><button@@ -578,6 +641,7 @@ function MachineDetail({ machine: m, row, onRemoved }: { machine: MachinesViewMa</div>))}</dl>+ {m.current && account?.thisMachine ? <TrustSection trust={account.thisMachine} onTrust={devices.startEnroll} /> : null}{m.current ? <ThisMachineExtras panel={row?.panel ?? null} part="logs" /> : null}</div>) : null}diff --git a/apps/cua-spaces-web/src/routes/notifications/index.tsx b/apps/cua-spaces-web/src/routes/notifications/index.tsxindex a0679e8ff7..e3dd2727c6 100644--- a/apps/cua-spaces-web/src/routes/notifications/index.tsx+++ b/apps/cua-spaces-web/src/routes/notifications/index.tsx@@ -12,10 +12,8 @@ import { Button } from "@/components/ui/button";import { PlainList, plainRowClass } from "@/components/ui/grouped";import { toastError } from "@/components/ui/toast";import { cn } from "@/lib/utils";-import { useFlag } from "@/bridge/flags";-import { LegacyNotificationsPage } from "@/legacy/routes/notifications/index";-export const Route = createFileRoute("/notifications/")({ component: NotificationsPageSwitch });+export const Route = createFileRoute("/notifications/")({ component: NotificationsPage });/*** Notifications: the daemon's feed, one line each, newest first, unread in@@ -117,8 +115,3 @@ function NotificationRow({ row, entry, open, onToggle }: { row: NotificationLine</div>);}--/** The redesign behind `spaces_redesign` (Settings → Advanced → Labs); off, the page as it was. */-function NotificationsPageSwitch() {- return useFlag("spaces_redesign") ? <NotificationsPage /> : <LegacyNotificationsPage />;-}diff --git a/apps/cua-spaces-web/src/routes/onboarding/index.tsx b/apps/cua-spaces-web/src/routes/onboarding/index.tsxindex f8b227d66b..9f3c46d66c 100644--- a/apps/cua-spaces-web/src/routes/onboarding/index.tsx+++ b/apps/cua-spaces-web/src/routes/onboarding/index.tsx@@ -5,8 +5,9 @@ import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";import { ArrowLeftIcon, CheckIcon, CopyIcon, ExternalLinkIcon } from "lucide-react";import { useEffect, useState, type ReactNode } from "react";-import { useAgentKeys, useBridge, useFirstRun, type FirstRunArt, type FirstRunCredential, type FirstRunExtraView, type FirstRunHook, type FirstRunRow, type FirstRunView } from "@/bridge";+import { useAgentKeys, useBridge, useFirstRun, useSpaces, type FirstRunArt, type FirstRunCredential, type FirstRunExtraView, type FirstRunHook, type FirstRunRow, type FirstRunView } from "@/bridge";import { readSavedOnboarding } from "@/bridge/onboarding";+import { AddAgentSheet } from "@/components/add-agent/add-agent-sheet";import { APP_MARKS, AppMarkImage } from "@/components/agents/harness-mark";import { CuaLogo } from "@/components/cua-logo";import { OsIcon } from "@/components/os-icon";@@ -253,6 +254,30 @@ const HEADLINE_APPS = [{ agent: "cursor", name: "Cursor" },];+/**+ * "An agent on another machine": the other choice beside the coding apps found here. It opens the+ * join sheet for this machine's own Space: one line to paste into whichever agent runs elsewhere.+ * Not offered before the machine has a Space to join.+ */+function OtherMachineRow() {+ const { data: spaces } = useSpaces();+ const [open, setOpen] = useState(false);+ const space = spaces?.find((s) => s.id === "this-mac") ?? spaces?.find((s) => s.provider === "local");+ if (!space) return null;+ return (+ <div className="flex min-h-12 items-center gap-3 py-2" data-first-run-other-machine="">+ <div className="min-w-0 flex-1">+ <div className="text-[14px]">An agent on another machine</div>+ <div className="text-[13px] text-muted-foreground">Copy one line to paste into it.</div>+ </div>+ <Button variant="outline" className="h-9 shrink-0 rounded-full border-foreground/25 px-4 text-[13px] font-medium" onClick={() => setOpen(true)} data-first-run-other-machine-open="">+ Connect it+ </Button>+ <AddAgentSheet open={open} onOpenChange={setOpen} space={{ id: space.id, name: space.name }} role={null} initialStage="connect" />+ </div>+ );+}+/*** 2 · Let your coding apps use Cua: one question, asked once. It names the* coding apps found on this computer; Set up adds Cua to all of them, Not now@@ -354,6 +379,7 @@ function Connect({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {</div>);})}+ <OtherMachineRow /></Rows><div className="mt-8 flex flex-wrap items-center gap-3"><Primary label="Check again" onClick={() => void fr.act("recheck")} data-first-run-recheck="" />@@ -420,6 +446,7 @@ function Connect({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {</div>);})}+ <OtherMachineRow /></Rows><div className="mt-8 flex flex-wrap items-center gap-3">{all || failed.length ? (diff --git a/apps/cua-spaces-web/src/routes/settings/connectors.$app.tsx b/apps/cua-spaces-web/src/routes/settings/connectors.$app.tsxindex b2b7161066..76b3b80117 100644--- a/apps/cua-spaces-web/src/routes/settings/connectors.$app.tsx+++ b/apps/cua-spaces-web/src/routes/settings/connectors.$app.tsx@@ -1,16 +1,12 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { createFileRoute, redirect } from "@tanstack/react-router";+import { createFileRoute } from "@tanstack/react-router";-import { flagOn } from "@/bridge";import { ConnectorAppPage } from "@/components/settings/connectors/app-detail";-/** One coding app's page under Connectors (the redesign; off, Connectors as it was). */+/** One coding app's page under Connectors. */export const Route = createFileRoute("/settings/connectors/$app")({- beforeLoad: ({ params }) => {- if (!flagOn("spaces_redesign")) throw redirect({ to: "/settings/connectors", search: { app: params.app } });- },component: AppPage,});diff --git a/apps/cua-spaces-web/src/routes/settings/connectors.tsx b/apps/cua-spaces-web/src/routes/settings/connectors.tsxindex 50a6c04dd0..2dbd8fd7f2 100644--- a/apps/cua-spaces-web/src/routes/settings/connectors.tsx+++ b/apps/cua-spaces-web/src/routes/settings/connectors.tsx@@ -3,12 +3,9 @@import { createFileRoute, Outlet, useMatch } from "@tanstack/react-router";-import { useAgentKeys, useCliInstall, useFlag, useSettings } from "@/bridge";-import { AccountKeysSection } from "@/components/settings/account-keys";+import { useCliInstall, useSettings } from "@/bridge";import { CliSettingsSection } from "@/components/settings/cli-section";-import { CodingAppsSection } from "@/components/settings/coding-apps-section";import { ConnectorsRedesign } from "@/components/settings/connectors/connectors-page";-import { useConnectedApps } from "@/hooks/use-connected-apps";import { useQuiet } from "@/hooks/use-quiet";/** `app` is a coding app to bring into view (the Agents page's Connect). */@@ -22,14 +19,13 @@ export const Route = createFileRoute("/settings/connectors")({* Its parts come from separate host reads; the page draws once they have answered, not one by one with the page jumping at each (CUA-1951).*/function ConnectorsPage() {- // An app's own page (`/settings/connectors/<app>`, the redesign) draws in place of the list.+ // An app's own page (`/settings/connectors/<app>`) draws in place of the list.const child = useMatch({ from: "/settings/connectors/$app", shouldThrow: false });- const redesign = useFlag("spaces_redesign");if (child) return <Outlet />;- return redesign ? <Redesign /> : <Classic />;+ return <Redesign />;}-/** The redesign: Coding apps with Connect and their pages, then Providers. */+/** Coding apps with Connect and their pages, then Providers. */function Redesign() {const { app } = Route.useSearch();const { data } = useSettings();@@ -43,20 +39,3 @@ function Redesign() {</div>);}--function Classic() {- const { app } = Route.useSearch();- const { data } = useSettings();- const apps = useConnectedApps();- const keys = useAgentKeys({ watch: true });- const cli = useCliInstall();- const settled = useQuiet(`${apps.rows?.length ?? -1}|${data?.cli ? 1 : 0}|${keys.view?.rows.length ?? 0}|${cli.state.plan ? 1 : 0}`);- if (!settled) return <div className="h-96" aria-busy="true" />;- return (- <div data-settings-tab="connectors">- <CodingAppsSection apps={apps} focusApp={app} />- <AccountKeysSection />- <CliSettingsSection />- </div>- );-}diff --git a/apps/cua-spaces-web/src/routes/settings/devices.tsx b/apps/cua-spaces-web/src/routes/settings/devices.tsxindex e87b8dae90..391474e6f7 100644--- a/apps/cua-spaces-web/src/routes/settings/devices.tsx+++ b/apps/cua-spaces-web/src/routes/settings/devices.tsx@@ -1,428 +1,14 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { createFileRoute } from "@tanstack/react-router";-import { CircleHelpIcon, EllipsisIcon, HashIcon, LaptopIcon, MonitorIcon, SmartphoneIcon, UserRoundIcon, UsersIcon } from "lucide-react";-import { useState } from "react";--import { useDevices, useSession, type DeviceRow, type DevicesLabels, type UnconfirmedMachine } from "@/bridge";-import { SettingsGroup } from "@/components/settings-group";-import { ConfirmDialog } from "@/components/ui/alert-dialog";-import { Button } from "@/components/ui/button";-import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";-import { Menu } from "@/components/ui/menu";-import { deviceKind, devicesPageState, relativeText, rowDetail, thisDeviceText } from "@/lib/devices";-import { thisComputerLabel } from "@/lib/host-labels";-import { plainDevice, plainDeviceSentence } from "@/lib/settings-copy";-import { ScreenPermissionsSection } from "@/components/settings/screen-permissions-section";-import { cn } from "@/lib/utils";--export const Route = createFileRoute("/settings/devices")({ component: DevicesPage });--/** `devices::labels().signed_out`, for before the core's view exists. */-const SIGNED_OUT = "Sign in to Cua to see the devices that can reach your machines.";+import { createFileRoute, redirect } from "@tanstack/react-router";/**- * Settings, Trusted machines: this computer's trust, new machines to confirm, the- * account's devices (Approve, Deny, Rename, Revoke) and Recent Access, then- * the enroll and approval sheets. Everything shown is the app core's- * `devices::devices_view`, as in the SwiftUI app's `DevicesSettingsView`.+ * The old Settings > Trusted machines tab. Everything on it moved to the Machines tab, so a+ * bookmark or a link to it lands there. Kept only for those old links.*/-function DevicesPage() {- const { data: session } = useSession();- const devices = useDevices();- const [renaming, setRenaming] = useState<DeviceRow | null>(null);- const [revoking, setRevoking] = useState<DeviceRow | null>(null);- const [confirming, setConfirming] = useState<UnconfirmedMachine | null>(null);-- const state = devicesPageState(devices, session?.signedIn);- if (state === "unsupported") return <Muted>Devices are not available in this app yet.</Muted>;- if (state === "signed-out") return <Muted>{devices.data?.view?.labels.signedOut ?? SIGNED_OUT}</Muted>;- if (state === "error" || state === "no-view") {- return (- <Retry onRetry={() => void devices.refresh()} data-devices-error>- {devices.error ? `Couldn't read your machines: ${devices.error.message}` : "Couldn't show your machines."}- </Retry>- );- }- // The host may take a while to ask the relay.- if (state === "loading") return <Muted data-devices-loading>Loading devices…</Muted>;- const data = devices.data!;- const v = data.view!;- const labels = v.labels;-- return (- <div data-devices data-settings-tab="devices">- <Group title={plainDevice(labels.thisDevice)}>- <div className="flex min-h-11 items-center justify-between gap-4 px-4 py-2.5">- <div className="flex min-w-0 items-center gap-2.5">- <LaptopIcon className="size-4 shrink-0 text-muted-foreground" strokeWidth={1.75} />- {/* Named as the system names it ("cua's Mac Studio"), as the SwiftUI app does. */}- <span className="truncate text-[13px]" data-this-device-name>- {v.thisDevice.name ?? data.input.deviceName ?? thisComputerLabel()}- </span>- </div>- <div className="flex shrink-0 items-center gap-2">- <span data-this-device-status={v.thisDevice.kind} className={cn("text-[13px]", v.thisDevice.kind === "enrolled" ? "text-muted-foreground" : "text-warning")}>- {plainDevice(thisDeviceText(v.thisDevice))}- </span>- {v.thisDevice.actionLabel ? (- <Button size="sm" variant="outline" onClick={devices.startEnroll} data-this-device-enroll>- {plainDevice(v.thisDevice.actionLabel)}- </Button>- ) : null}- </div>- </div>- {v.banner ? (- // What it means, under the row (its one Enroll… is the row's), as- // the SwiftUI app's Devices settings have it.- <p data-devices-banner={v.banner.tone} className="px-4 py-2.5 text-xs text-muted-foreground">- <span data-banner-text>{plainDeviceSentence(v.banner.text)}</span>- </p>- ) : null}- </Group>-- {v.unconfirmedMachines.length > 0 ? (- <Group title={plainDevice(labels.newMachines)}>- {v.unconfirmedMachines.map((m) => (- <div key={m.id} data-unconfirmed-machine={m.id} className="flex min-h-11 items-center gap-2.5 px-4 py-2">- <CircleHelpIcon className="size-4 shrink-0 text-warning" />- <span className="min-w-0 flex-1 truncate text-[13px]">{m.title}</span>- <Button size="sm" variant="outline" onClick={() => setConfirming(m)}>- {labels.confirmMachine}- </Button>- </div>- ))}- </Group>- ) : null}-- {v.rows.length > 0 ? (- <Group title={plainDevice(labels.devices)}>- {v.rows.map((r) => (- <DeviceLine- key={r.id}- row={r}- labels={labels}- now={data.now}- busy={data.busy}- onApprove={() => devices.openApproval(r.id)}- onDeny={() => void devices.denyDevice(r.id)}- onRename={() => setRenaming(r)}- onRevoke={() => setRevoking(r)}- />- ))}- </Group>- ) : null}-- <Group- title={plainDevice(labels.recent)}- data-recent- footer={- // The relay refused to list them (this device is not enrolled): its words, under the list, as the SwiftUI app shows them.- // "Needs enrollment" is the not-enrolled refusal, which the page has already said.- (data.input.readError && v.thisDevice.kind === "enrolled") || data.actionError ? (- <div className="text-destructive">- {data.input.readError && v.thisDevice.kind === "enrolled" ? (- <p data-devices-read-error className="break-words">- {data.input.readError}- </p>- ) : null}- {data.actionError ? <p>{data.actionError}</p> : null}- </div>- ) : null- }- >- {v.recent.length === 0 ? <div className="px-4 py-3 text-[13px] text-muted-foreground">{plainDevice(labels.recentEmpty)}</div> : null}- {v.recent.map((a, i) => (- <div key={`${a.ts}-${i}`} data-recent-row className="flex min-h-11 items-center justify-between gap-4 px-4 py-2">- <span className="flex min-w-0 items-center gap-2 text-[13px]">- {a.notable ? (- <span title="Another account or an unenrolled device">- <UsersIcon className="size-3.5 shrink-0 text-warning" aria-label="Another account or an unenrolled device" />- </span>- ) : null}- <span className="truncate" data-recent-text>- {plainDeviceSentence(a.text)}- </span>- </span>- <span className="shrink-0 text-xs text-muted-foreground">{relativeText(a.ts, data.now)}</span>- </div>- ))}- </Group>- <ScreenPermissionsSection />-- <EnrollSheet />- <ApproveSheet />- <RenameDialog row={renaming} labels={labels} onClose={() => setRenaming(null)} onRename={(name) => renaming && void devices.rename(renaming.id, name)} />- <ConfirmDialog- open={revoking?.revokeConfirm != null}- onOpenChange={(o) => !o && setRevoking(null)}- title={plainDeviceSentence(revoking?.revokeConfirm?.title ?? "")}- description={plainDeviceSentence(revoking?.revokeConfirm?.message ?? "")}- confirmLabel={plainDevice(revoking?.revokeConfirm?.confirmLabel ?? labels.revoke)}- destructive- onConfirm={() => revoking && void devices.revoke(revoking.id)}- />- <ConfirmDialog- open={confirming !== null}- onOpenChange={(o) => !o && setConfirming(null)}- title={plainDeviceSentence(confirming?.confirm.title ?? "")}- description={plainDeviceSentence(confirming?.confirm.message ?? "")}- confirmLabel={confirming?.confirm.confirmLabel ?? labels.confirmMachine}- onConfirm={() => confirming && void devices.confirmMachine(confirming.id)}- />- </div>- );-}--function Muted({ children, ...rest }: { children: React.ReactNode } & Record<`data-${string}`, unknown>) {- return (- <p className="px-1 text-[13px] text-muted-foreground" {...rest}>- {children}- </p>- );-}--function Retry({ children, onRetry, ...rest }: { children: React.ReactNode; onRetry: () => void } & Record<`data-${string}`, unknown>) {- return (- <div className="flex items-center gap-3 px-1" {...rest}>- <p role="alert" className="min-w-0 flex-1 text-[13px] text-muted-foreground">- {children}- </p>- <Button size="sm" variant="outline" onClick={onRetry}>- Try again- </Button>- </div>- );-}--function Group({ title, footer, children, ...rest }: { title: string; footer?: React.ReactNode; children: React.ReactNode } & Record<`data-${string}`, unknown>) {- return (- <SettingsGroup title={title} footer={footer} {...rest}>- {children}- </SettingsGroup>- );-}--const ICONS = { laptop: LaptopIcon, desktop: MonitorIcon, phone: SmartphoneIcon, unknown: CircleHelpIcon } as const;--function DeviceLine({- row: r,- labels,- now,- busy,- onApprove,- onDeny,- onRename,- onRevoke,-}: {- row: DeviceRow;- labels: DevicesLabels;- now: number;- busy: boolean;- onApprove: () => void;- onDeny: () => void;- onRename: () => void;- onRevoke: () => void;-}) {- const Icon = ICONS[deviceKind(r.platform)];- const menu = [- ...(r.actions.includes("rename") ? [{ label: labels.rename, onSelect: onRename }] : []),- ...(r.actions.includes("revoke") ? [{ label: plainDevice(labels.revoke), onSelect: onRevoke, destructive: true }] : []),- ];- return (- <div data-device-row={r.id} className="flex min-h-14 items-center gap-3 px-4 py-2.5">- <Icon className="size-4 shrink-0 text-muted-foreground" strokeWidth={1.75} />- <div className="min-w-0 flex-1">- <div className="truncate text-[13px]" data-device-title>- {r.title}- </div>- <div className="truncate text-xs text-muted-foreground" data-device-detail>- {plainDevice(rowDetail(r, labels, now))}- </div>- </div>- {r.actions.includes("approve") ? (- <>- <Button size="sm" variant="outline" onClick={onApprove} data-device-approve>- {labels.approve}- </Button>- <Button size="sm" variant="ghost" disabled={busy} onClick={onDeny} data-device-deny>- {labels.deny}- </Button>- </>- ) : null}- {menu.length > 0 ? (- <Menu- items={menu.map((m) => ({ ...m, disabled: busy }))}- trigger={- <Button size="icon-sm" variant="ghost" aria-label={`More for ${r.name || r.id}`} data-device-menu>- <EllipsisIcon className="size-4 text-muted-foreground" />- </Button>- }- />- ) : null}- </div>- );-}--/** "Enroll This Device": sign in again, or approve from another device with a one-time code. */-function EnrollSheet() {- const { data, chooseEnroll, backEnroll, closeEnroll } = useDevices();- const v = data?.enroll?.view;- return (- <Dialog open={Boolean(v)} onOpenChange={(o) => !o && closeEnroll()}>- <DialogPopup className="w-[min(440px,calc(100vw-2rem))]" data-enroll>- {v ? (- <>- <div className="px-5 pt-5 pb-4">- <DialogTitle className="text-[15px] font-semibold" data-enroll-title>- {plainDeviceSentence(v.title)}- </DialogTitle>- <p className="mt-1.5 text-[13px] text-muted-foreground">{plainDeviceSentence(v.lede)}</p>- {v.options.length > 0 ? (- <div className="mt-4 flex flex-col gap-2">- {v.options.map((o) => (- <button- key={o.method}- type="button"- data-enroll-option={o.method}- onClick={() => void chooseEnroll(o.method)}- className="flex items-center gap-3 rounded-lg border bg-card px-3 py-2.5 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60"- >- {o.method === "sign-in" ? <UserRoundIcon className="size-5 text-muted-foreground" /> : <HashIcon className="size-5 text-muted-foreground" />}- <span className="min-w-0">- <span className="block text-[13px] font-medium">{plainDeviceSentence(o.title)}</span>- <span className="block text-xs text-muted-foreground">{plainDeviceSentence(o.detail)}</span>- </span>- </button>- ))}- </div>- ) : null}- {v.code ? (- <p className="mt-5 text-center font-mono text-[28px] font-semibold tracking-wider select-text" data-enroll-code>- {v.code}- </p>- ) : null}- {v.codeHelp ? <p className="mt-3 text-xs text-muted-foreground">{v.codeHelp.replace(/`/g, "")}</p> : null}- {v.status ? (- <p className="mt-4 flex items-center gap-2 text-[13px] text-muted-foreground" data-enroll-status>- {v.busy ? <span className="size-3 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-muted-foreground" /> : null}- {v.status}- </p>- ) : null}- {v.error ? (- <p className="mt-3 text-[13px] text-destructive" data-enroll-error>- {v.error}- </p>- ) : null}- </div>- <div className="flex justify-end gap-2 border-t bg-muted/60 px-5 py-3">- {v.backLabel ? (- <Button variant="outline" onClick={backEnroll} data-enroll-back>- {v.backLabel}- </Button>- ) : null}- <Button variant={v.done ? "default" : "outline"} onClick={closeEnroll} data-enroll-close>- {v.closeLabel}- </Button>- </div>- </>- ) : null}- </DialogPopup>- </Dialog>- );-}--/** A device asking to join or to be re-verified: its code, Approve (presence first) and Deny or Not Now. */-function ApproveSheet() {- const { data, setApprovalCode, approve, deny, closeApproval } = useDevices();- const v = data?.approve?.view;- return (- <Dialog open={Boolean(v)} onOpenChange={(o) => !o && closeApproval()}>- <DialogPopup className="w-[min(420px,calc(100vw-2rem))]" data-approve>- {v ? (- <form- onSubmit={(e) => {- e.preventDefault();- if (v.canApprove) void approve();- }}- >- <div className="px-5 pt-5 pb-4">- <DialogTitle className="text-[15px] font-semibold" data-approve-title>- {plainDeviceSentence(v.title)}- </DialogTitle>- <p className="mt-1.5 text-[13px] text-muted-foreground" data-approve-message>- {plainDeviceSentence(v.message)}- </p>- {v.needsCode ? (- <Input- aria-label={v.codeLabel}- className="mt-4 h-10 font-mono text-[18px] tracking-wider"- placeholder={v.codePlaceholder}- value={v.code}- disabled={v.busy}- autoFocus- autoComplete="off"- spellCheck={false}- onChange={(e) => setApprovalCode(e.currentTarget.value)}- data-approve-code- />- ) : null}- {v.error ? (- <p className="mt-3 text-[13px] text-destructive" data-approve-error>- {v.error}- </p>- ) : null}- </div>- <div className="flex items-center justify-end gap-2 border-t bg-muted/60 px-5 py-3">- {v.busy ? <span className="mr-auto size-3.5 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-muted-foreground" /> : null}- <Button variant="outline" disabled={v.busy} onClick={() => void deny()} data-approve-deny>- {v.denyLabel}- </Button>- <Button type="submit" disabled={!v.canApprove} data-approve-submit>- {v.approveLabel}- </Button>- </div>- </form>- ) : null}- </DialogPopup>- </Dialog>- );-}--function RenameDialog({ row, labels, onClose, onRename }: { row: DeviceRow | null; labels: DevicesLabels; onClose: () => void; onRename: (name: string) => void }) {- const [name, setName] = useState("");- const [forId, setForId] = useState<string | null>(null);- if (row && forId !== row.id) {- setForId(row.id);- setName(row.name);- }- return (- <Dialog open={row !== null} onOpenChange={(o) => !o && onClose()}>- <DialogPopup className="w-[min(380px,calc(100vw-2rem))]">- <form- onSubmit={(e) => {- e.preventDefault();- if (!name.trim()) return;- onRename(name);- onClose();- }}- >- <div className="px-5 pt-5 pb-4">- <DialogTitle className="text-[15px] font-semibold">{labels.renameTitle}</DialogTitle>- <Input className="mt-3" aria-label={labels.renameTitle} value={name} autoFocus maxLength={64} onChange={(e) => setName(e.currentTarget.value)} />- </div>- <div className="flex justify-end gap-2 border-t bg-muted/60 px-5 py-3">- <Button variant="outline" onClick={onClose}>- {labels.cancel}- </Button>- <Button type="submit" disabled={!name.trim()}>- {labels.renameConfirm}- </Button>- </div>- </form>- </DialogPopup>- </Dialog>- );-}+export const Route = createFileRoute("/settings/devices")({+ beforeLoad: () => {+ throw redirect({ to: "/machines", replace: true });+ },+});diff --git a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsxindex 5f5fffdbe0..8d80aa9090 100644--- a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx+++ b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx@@ -33,10 +33,9 @@ import { volumeUnavailableNote } from "@/lib/volume-notes";import { canDelete, canPower, createError, isUnsharedDesktop, 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")({- component: SpaceDetailPageSwitch,+ component: SpaceDetailPage,// Apps and files dropped on this Space's tile in the notch, by name (the host holds their paths).validateSearch: (s: Record<string, unknown>): { dropped?: string[] } => {const dropped = parseDropped(s.dropped);@@ -166,7 +165,7 @@ function SpaceDetailPage() {// Devices with the enroll sheet.const enroll = () => {devices.startEnroll();- void navigate({ to: "/settings/devices" });+ void navigate({ to: "/machines" });};const teleportApp = () => run("open Teleport for", () => teleport.open(space));const share = () => run("share", () => sharing.open(space, session?.signedIn ?? false));@@ -732,8 +731,3 @@ function threadViewOf(v: StreamViewContext | null): ThreadView | null {if (!v || v.kind !== "window") return null;return { kind: "window", app: v.app ?? null, title: v.title ?? null, windowId: v.windowId ?? null };}--/** The redesign behind `spaces_redesign` (Settings → Advanced → Labs); off, the page as it was. */-function SpaceDetailPageSwitch() {- return useFlag("spaces_redesign") ? <SpaceDetailPage /> : <LegacySpacePage />;-}diff --git a/apps/cua-spaces-web/src/routes/spaces/index.tsx b/apps/cua-spaces-web/src/routes/spaces/index.tsxindex 2e380d5c95..50e827e95a 100644--- a/apps/cua-spaces-web/src/routes/spaces/index.tsx+++ b/apps/cua-spaces-web/src/routes/spaces/index.tsx@@ -32,11 +32,9 @@ import { accessOf, isMine } from "@/lib/space-access";import { creatingElsewhereLine, machineName, matchesQuery, spaceState } from "@/lib/spaces";import { hideDesktop, showHiddenDesktops } from "@/lib/hidden-desktops";import { computerChoices, gridArea, nextSearch, shownSpaces, spaceMachineId, validateSpacesSearch, type SpacesSearch } from "@/lib/spaces-page";-import { useFlag } from "@/bridge/flags";-import { LegacySpacesPage } from "@/legacy/routes/spaces/index";export const Route = createFileRoute("/spaces/")({- component: SpacesPageSwitch,+ component: SpacesPage,// `view`, `sort`, `on`, `state`, `owner`, `select` (lib/spaces-page). The low-disk warning's "See what's using// space" opens `?view=list&on=<this computer>&sort=size`; `?sort=size` alone sorts the grid biggest first.validateSearch: (s: Record<string, unknown>): SpacesSearch => validateSpacesSearch(s),@@ -300,11 +298,6 @@ function SpacesPage() {);}-/** The redesign behind `spaces_redesign` (Settings → Advanced → Labs); off, the page as it was. */-function SpacesPageSwitch() {- return useFlag("spaces_redesign") ? <SpacesPage /> : <LegacySpacesPage />;-}-interface GridLive {selection: ReturnType<typeof useSelection>;actions: MenuActions;diff --git a/apps/cua-spaces-web/src/routes/volume/index.tsx b/apps/cua-spaces-web/src/routes/volume/index.tsxindex 8acedbe5ba..e074b9d8ab 100644--- a/apps/cua-spaces-web/src/routes/volume/index.tsx+++ b/apps/cua-spaces-web/src/routes/volume/index.tsx@@ -12,10 +12,8 @@ import { Button } from "@/components/ui/button";import { GroupedSection, SectionHeading } from "@/components/ui/grouped";import { cn } from "@/lib/utils";import { volumeUnavailableNote } from "@/lib/volume-notes";-import { useFlag } from "@/bridge/flags";-import { LegacyVolumePage } from "@/legacy/routes/volume/index";-export const Route = createFileRoute("/volume/")({ component: VolumePageSwitch });+export const Route = createFileRoute("/volume/")({ component: VolumePage });/*** Volume, as the SwiftUI app's `DrivePageView` lays it out: Open in Finder@@ -215,8 +213,3 @@ function Conflict({ conflict: c, busy, onOpen, onResolve }: { conflict: Conflict</div>);}--/** The redesign behind `spaces_redesign` (Settings → Advanced → Labs); off, the page as it was. */-function VolumePageSwitch() {- return useFlag("spaces_redesign") ? <VolumePage /> : <LegacyVolumePage />;-}diff --git a/apps/cua-spaces-web/vite.config.ts b/apps/cua-spaces-web/vite.config.tsindex 23c08e8c47..a21c055903 100644--- a/apps/cua-spaces-web/vite.config.ts+++ b/apps/cua-spaces-web/vite.config.ts@@ -59,10 +59,6 @@ export default defineConfig({// runner under the whole suite's load takes seconds where a laptop// takes milliseconds (see src/test-setup.ts).setupFiles: ["src/test-setup.ts"],- // The redesign (`spaces_redesign`) is the default; the suite sets it- // explicitly, and src/legacy/__tests__ turn it off to keep the classic- // pages working.- env: { VITE_CUA_FLAG_SPACES_REDESIGN: "1" },testTimeout: 15_000,},});diff --git a/apps/cua-spaces/src/components/Devices.test.tsx b/apps/cua-spaces/src/components/Devices.test.tsxindex 7290d8252f..c4df5d97b4 100644--- a/apps/cua-spaces/src/components/Devices.test.tsx+++ b/apps/cua-spaces/src/components/Devices.test.tsx@@ -36,8 +36,8 @@ describe("devices model", () => {it("is the core's page, enroll and approve sheets", () => {const v = devicesView(snapshot, NOW);expect(v.enrolled).toBe(true);- expect(v.thisDevice).toMatchObject({ kind: "enrolled", title: "Enrolled until", at: NOW + 30 * 86_400 });- expect(v.rows.map((r) => r.title)).toEqual(["MacBook Pro (this device)", "Old laptop", "Work laptop"]);+ expect(v.thisDevice).toMatchObject({ kind: "enrolled", title: "Trusted until", at: NOW + 30 * 86_400 });+ expect(v.rows.map((r) => r.title)).toEqual(["MacBook Pro (this machine)", "Old laptop", "Work laptop"]);expect(v.recent.map((r) => r.text)).toEqual(["[email protected] opened studio-mac", "MacBook Pro opened studio-mac"]);expect(v.approvals.map((a) => a.deviceId)).toEqual(["dev_p", "dev_o"]);let s = enrollInitial();@@ -67,19 +67,19 @@ describe("Settings → Devices", () => {onRevoke={onRevoke}/>,);- expect(screen.getByTestId("this-device-status").textContent).toMatch(/^Enrolled until /);- const devices = screen.getByRole("region", { name: "Your Devices" });- expect(within(devices).getByText("MacBook Pro (this device)")).toBeInTheDocument();- expect(within(devices).getByText(/macOS · Enrolled · re-verify in 30 days · Last seen/)).toBeInTheDocument();- expect(within(devices).getAllByRole("button", { name: "Approve…" })).toHaveLength(2);- const denyButtons = within(devices).getAllByRole("button", { name: "Deny" });+ expect(screen.getByTestId("this-device-status").textContent).toMatch(/^Trusted until /);+ const devices = screen.getByRole("region", { name: "Your Machines" });+ expect(within(devices).getByText("MacBook Pro (this machine)")).toBeInTheDocument();+ expect(within(devices).getByText(/macOS, Trusted, check again in 30 days, Last seen/)).toBeInTheDocument();+ expect(within(devices).getAllByRole("button", { name: "Add machine" })).toHaveLength(2);+ const denyButtons = within(devices).getAllByRole("button", { name: "Not me" });expect(denyButtons).toHaveLength(2);// Rows sort this device first, then alphabetically: "Old laptop" (expired) before "Work laptop" (pending).fireEvent.click(denyButtons[1]!);expect(onDeny).toHaveBeenCalledWith(expect.objectContaining({ deviceId: "dev_p", expired: false }));fireEvent.click(within(devices).getAllByRole("button", { name: "Revoke…" })[0]!);expect(onRevoke).toHaveBeenCalledWith(expect.objectContaining({ id: "dev_m" }));- const recent = screen.getByRole("region", { name: "Recent Access" });+ const recent = screen.getByRole("region", { name: "Recent access" });expect(within(recent).getByText("[email protected] opened studio-mac")).toBeInTheDocument();expect(within(recent).getByLabelText("Not one of your devices")).toBeInTheDocument();});@@ -96,7 +96,7 @@ describe("Settings → Devices", () => {);expect(screen.getByRole("status", { name: "Device enrollment" }).textContent).toContain("within 5 days");expect(screen.getByTestId("this-device-status").textContent).toMatch(/grace ends/);- fireEvent.click(screen.getAllByRole("button", { name: "Enroll…" })[0]!);+ fireEvent.click(screen.getAllByRole("button", { name: "Trust this machine" })[0]!);expect(onEnroll).toHaveBeenCalled();rerender(<DevicesSection@@ -125,10 +125,10 @@ describe("enroll sheet", () => {const bridge = createFakeDevicesBridge({ approvedAfterChecks: 2 });const onEnrolled = vi.fn();render(<EnrollSheet bridge={bridge} signIn={async () => {}} onClose={() => {}} onEnrolled={onEnrolled} pollMs={10} />);- fireEvent.click(screen.getByRole("button", { name: /Approve from another device/ }));+ fireEvent.click(screen.getByRole("button", { name: /Add it from another machine/ }));await act(async () => {});expect(screen.getByLabelText("One-time code").textContent).toBe("K7QX-M2RP");- expect(screen.getByRole("status").textContent).toBe("Waiting for approval…");+ expect(screen.getByRole("status").textContent).toBe("Waiting to be added…");await act(async () => {await vi.advanceTimersByTimeAsync(50);});@@ -163,7 +163,7 @@ describe("enroll sheet", () => {fireEvent.click(screen.getByRole("button", { name: /Sign in again/ }));expect(await screen.findByRole("alert")).toHaveTextContent("sign-in was cancelled");fireEvent.click(screen.getByRole("button", { name: "Back" }));- expect(screen.getByRole("button", { name: /Approve from another device/ })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Add it from another machine/ })).toBeInTheDocument();});});@@ -174,7 +174,7 @@ describe("approval sheet", () => {const bridge = createFakeDevicesBridge({ snapshot, presenceFails: "authentication was cancelled" });const onDone = vi.fn();render(<ApproveSheet bridge={bridge} prompt={prompt} onClose={() => {}} onDone={onDone} />);- const approve = screen.getByRole("button", { name: "Approve" });+ const approve = screen.getByRole("button", { name: "Add machine" });expect(approve).toBeDisabled();fireEvent.change(screen.getByPlaceholderText("XXXX-XXXX"), { target: { value: "k7qx m2rp" } });expect(screen.getByPlaceholderText("XXXX-XXXX")).toHaveValue("K7QX-M2RP");@@ -206,10 +206,10 @@ describe("approval sheet", () => {<ApproveSheet bridge={bridge} prompt={prompt} devices={snapshot.devices} onClose={() => {}} onDone={onDone} />,);fireEvent.change(screen.getByPlaceholderText("XXXX-XXXX"), { target: { value: "z9wy4tpn" } });- fireEvent.click(screen.getByRole("button", { name: "Approve" }));+ fireEvent.click(screen.getByRole("button", { name: "Add machine" }));expect(await screen.findByRole("alert")).toHaveTextContent("The code expired.");- expect(screen.getByText(/by ID instead/)).toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: "Approve by ID" }));+ expect(screen.getByText(/without it instead/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Add machine" }));await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1));expect(base.calls).toContain("approve::dev_p");});@@ -219,11 +219,11 @@ describe("approval sheet", () => {const onDone = vi.fn();const { unmount } = render(<ApproveSheet bridge={bridge} prompt={prompt} onClose={() => {}} onDone={onDone} />);fireEvent.change(screen.getByPlaceholderText("XXXX-XXXX"), { target: { value: "K7QXM2RP" } });- fireEvent.click(screen.getByRole("button", { name: "Approve" }));+ fireEvent.click(screen.getByRole("button", { name: "Add machine" }));await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1));unmount();render(<ApproveSheet bridge={bridge} prompt={prompt} onClose={() => {}} onDone={onDone} />);- fireEvent.click(screen.getByRole("button", { name: "Deny" }));+ fireEvent.click(screen.getByRole("button", { name: "Not me" }));await waitFor(() => expect(onDone).toHaveBeenCalledTimes(2));expect(bridge.calls).toContain("revoke:dev_p");});@@ -236,10 +236,10 @@ describe("approval sheet", () => {expect(screen.queryByPlaceholderText("XXXX-XXXX")).toBeNull();// No OS prompt on this system: the Keyvault passphrase is asked for.const passphrase = await screen.findByLabelText("Keyvault passphrase");- expect(screen.getByRole("button", { name: "Approve" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Keep machine" })).toBeDisabled();fireEvent.change(passphrase, { target: { value: "hunter2" } });- expect(screen.getByRole("button", { name: "Approve" })).toBeEnabled();- fireEvent.click(screen.getByRole("button", { name: "Not Now" }));+ expect(screen.getByRole("button", { name: "Keep machine" })).toBeEnabled();+ fireEvent.click(screen.getByRole("button", { name: "Not now" }));expect(onClose).toHaveBeenCalled();expect(bridge.calls.some((c) => c.startsWith("revoke"))).toBe(false);});@@ -257,8 +257,8 @@ describe("approval watch", () => {await waitFor(() => expect(screen.getByTestId("approving").textContent).toBe("dev_p"));const notes = bridge.calls.filter((c) => c.startsWith("notify:"));expect(notes).toEqual([- "notify:Approve “Work laptop”?:A device signed in to your Cua account and asks to reach your machines.",- "notify:Re-verify “Old laptop”?:It needs one approval to keep reaching your machines.",+ "notify:Add “Work laptop”?:A machine signed in to your Cua account and asks to be added.",+ "notify:Keep “Old laptop”?:It needs one approval to keep reaching your machines.",]);});diff --git a/apps/cua-spaces/src/components/Devices.tsx b/apps/cua-spaces/src/components/Devices.tsxindex 44dcdb1d93..b360633b08 100644--- a/apps/cua-spaces/src/components/Devices.tsx+++ b/apps/cua-spaces/src/components/Devices.tsx@@ -209,7 +209,7 @@ export function DevicesSection({<span className="st-label">{row.title}</span><span className="dv-detail">{row.detail}- {row.lastSeen != null && ` · ${l.lastSeen} ${relativeTime(row.lastSeen * 1000, nowMs)}`}+ {row.lastSeen != null && `, ${l.lastSeen} ${relativeTime(row.lastSeen * 1000, nowMs)}`}</span></div>{row.actions.includes("approve") && prompt && (diff --git a/apps/cua-spaces/src/components/ThisMachinePanel.test.tsx b/apps/cua-spaces/src/components/ThisMachinePanel.test.tsxindex 8e059f91b1..4a72df8737 100644--- a/apps/cua-spaces/src/components/ThisMachinePanel.test.tsx+++ b/apps/cua-spaces/src/components/ThisMachinePanel.test.tsx@@ -67,7 +67,7 @@ describe("host model", () => {const roster = withThisMachine([], sharing, 5, "macos");expect(notchActivity(roster, true)).toMatchObject({kind: "remote-access",- label: "Someone is connected to this computer",+ label: "Someone is connected to this machine",});expect(notchActivity(withThisMachine([], { ...sharing, clients: [] }, 5, "macos"), false)).toBeNull();});diff --git a/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx b/apps/cua-spaces/src/components/desktop/MainWindow.test.tsxindex 5b9ad89b44..5893f46267 100644--- a/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx+++ b/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx@@ -63,13 +63,13 @@ describe("MainWindow", () => {await screen.findByText("Just use this Mac to open my other machines");fireEvent.click(screen.getByRole("button", { name: "Continue" }));fireEvent.click(await screen.findByRole("button", { name: "Start using Cua Spaces" }));- expect(await screen.findByRole("listbox", { name: "My computers" })).toBeInTheDocument();+ expect(await screen.findByRole("listbox", { name: "My machines" })).toBeInTheDocument();expect(host.state.onboarding).toMatchObject({ completed: true, mode: "client" });});it("lists Spaces by where they run, with This machine first", async () => {setup();- const cloud = await screen.findByRole("listbox", { name: "My computers" });+ const cloud = await screen.findByRole("listbox", { name: "My machines" });expect(within(cloud).getByRole("option", { name: /aurora/ })).toBeInTheDocument();// The section named for this Mac holds its Spaces; the entry for This Mac is a list of its own.const lists = screen.getAllByRole("listbox", { name: "This Mac" });diff --git a/apps/cua-spaces/src/i18n/i18n.lock.json b/apps/cua-spaces/src/i18n/i18n.lock.jsonindex 82f5f08334..2547f526b4 100644--- a/apps/cua-spaces/src/i18n/i18n.lock.json+++ b/apps/cua-spaces/src/i18n/i18n.lock.json@@ -65,7 +65,7 @@"spaces.sidebar.empty": "3cb8c0f1b397","spaces.sidebar.no_matches": "2df01a03ff43","spaces.sidebar.section.connected": "22965568d22a",- "spaces.sidebar.section.my_computers": "90fd7e891731",+ "spaces.sidebar.section.my_computers": "6ae8f5f1f142","spaces.sidebar.section.this_mac": "79a4aefc396f","spaces.status.approval": "db0e960b68b5","spaces.status.cancelling": "91b104db05da",@@ -243,7 +243,7 @@"spaces.sidebar.empty": "3cb8c0f1b397","spaces.sidebar.no_matches": "2df01a03ff43","spaces.sidebar.section.connected": "22965568d22a",- "spaces.sidebar.section.my_computers": "90fd7e891731",+ "spaces.sidebar.section.my_computers": "6ae8f5f1f142","spaces.sidebar.section.this_mac": "79a4aefc396f","spaces.status.approval": "db0e960b68b5","spaces.status.cancelling": "91b104db05da",@@ -421,7 +421,7 @@"spaces.sidebar.empty": "3cb8c0f1b397","spaces.sidebar.no_matches": "2df01a03ff43","spaces.sidebar.section.connected": "22965568d22a",- "spaces.sidebar.section.my_computers": "90fd7e891731",+ "spaces.sidebar.section.my_computers": "6ae8f5f1f142","spaces.sidebar.section.this_mac": "79a4aefc396f","spaces.status.approval": "db0e960b68b5","spaces.status.cancelling": "91b104db05da",@@ -599,7 +599,7 @@"spaces.sidebar.empty": "3cb8c0f1b397","spaces.sidebar.no_matches": "2df01a03ff43","spaces.sidebar.section.connected": "22965568d22a",- "spaces.sidebar.section.my_computers": "90fd7e891731",+ "spaces.sidebar.section.my_computers": "6ae8f5f1f142","spaces.sidebar.section.this_mac": "79a4aefc396f","spaces.status.approval": "db0e960b68b5","spaces.status.cancelling": "91b104db05da",@@ -777,7 +777,7 @@"spaces.sidebar.empty": "3cb8c0f1b397","spaces.sidebar.no_matches": "2df01a03ff43","spaces.sidebar.section.connected": "22965568d22a",- "spaces.sidebar.section.my_computers": "90fd7e891731",+ "spaces.sidebar.section.my_computers": "6ae8f5f1f142","spaces.sidebar.section.this_mac": "79a4aefc396f","spaces.status.approval": "db0e960b68b5","spaces.status.cancelling": "91b104db05da",diff --git a/apps/cua-spaces/src/i18n/locales/en/spaces.json b/apps/cua-spaces/src/i18n/locales/en/spaces.jsonindex 5f9d965793..f83946d081 100644--- a/apps/cua-spaces/src/i18n/locales/en/spaces.json+++ b/apps/cua-spaces/src/i18n/locales/en/spaces.json@@ -63,7 +63,7 @@"spaces.create.creating": "Creating a Space…","spaces.sidebar.section.this_mac": "This Mac","spaces.sidebar.section.connected": "Connected",- "spaces.sidebar.section.my_computers": "My computers",+ "spaces.sidebar.section.my_computers": "My machines","spaces.sidebar.empty": "No Spaces yet","spaces.sidebar.no_matches": "No matches","spaces.status.failed": "Failed",diff --git a/apps/cua-spaces/src/i18n/locales/es/spaces.json b/apps/cua-spaces/src/i18n/locales/es/spaces.jsonindex d75d887b35..86ca1a3375 100644--- a/apps/cua-spaces/src/i18n/locales/es/spaces.json+++ b/apps/cua-spaces/src/i18n/locales/es/spaces.json@@ -63,7 +63,7 @@"spaces.create.creating": "Creando un Space…","spaces.sidebar.section.this_mac": "Este Mac","spaces.sidebar.section.connected": "Conectados",- "spaces.sidebar.section.my_computers": "Mis computadoras",+ "spaces.sidebar.section.my_computers": "Mis máquinas","spaces.sidebar.empty": "Aún no hay Spaces","spaces.sidebar.no_matches": "Sin resultados","spaces.status.failed": "Error",diff --git a/apps/cua-spaces/src/i18n/locales/ja/spaces.json b/apps/cua-spaces/src/i18n/locales/ja/spaces.jsonindex a350504390..0aca71bb46 100644--- a/apps/cua-spaces/src/i18n/locales/ja/spaces.json+++ b/apps/cua-spaces/src/i18n/locales/ja/spaces.json@@ -63,7 +63,7 @@"spaces.create.creating": "Space を作成中…","spaces.sidebar.section.this_mac": "この Mac","spaces.sidebar.section.connected": "接続済み",- "spaces.sidebar.section.my_computers": "自分のコンピュータ",+ "spaces.sidebar.section.my_computers": "自分のマシン","spaces.sidebar.empty": "まだ Spaces がありません","spaces.sidebar.no_matches": "一致する項目はありません","spaces.status.failed": "失敗",diff --git a/apps/cua-spaces/src/i18n/locales/ko/spaces.json b/apps/cua-spaces/src/i18n/locales/ko/spaces.jsonindex b99ab192f2..0f1e7182ad 100644--- a/apps/cua-spaces/src/i18n/locales/ko/spaces.json+++ b/apps/cua-spaces/src/i18n/locales/ko/spaces.json@@ -63,7 +63,7 @@"spaces.create.creating": "Space 만드는 중…","spaces.sidebar.section.this_mac": "이 Mac","spaces.sidebar.section.connected": "연결됨",- "spaces.sidebar.section.my_computers": "내 컴퓨터",+ "spaces.sidebar.section.my_computers": "내 머신","spaces.sidebar.empty": "아직 Spaces가 없어요","spaces.sidebar.no_matches": "일치하는 항목이 없어요","spaces.status.failed": "실패",diff --git a/apps/cua-spaces/src/i18n/locales/pt-BR/spaces.json b/apps/cua-spaces/src/i18n/locales/pt-BR/spaces.jsonindex ebde6a9880..4e1d4d4970 100644--- a/apps/cua-spaces/src/i18n/locales/pt-BR/spaces.json+++ b/apps/cua-spaces/src/i18n/locales/pt-BR/spaces.json@@ -63,7 +63,7 @@"spaces.create.creating": "Criando um Space…","spaces.sidebar.section.this_mac": "Este Mac","spaces.sidebar.section.connected": "Conectados",- "spaces.sidebar.section.my_computers": "Meus computadores",+ "spaces.sidebar.section.my_computers": "Minhas máquinas","spaces.sidebar.empty": "Ainda não há Spaces","spaces.sidebar.no_matches": "Nenhum resultado","spaces.status.failed": "Falhou",diff --git a/apps/cua-spaces/src/i18n/locales/zh-Hans/spaces.json b/apps/cua-spaces/src/i18n/locales/zh-Hans/spaces.jsonindex 4f2e571154..d5e5d88ce8 100644--- a/apps/cua-spaces/src/i18n/locales/zh-Hans/spaces.json+++ b/apps/cua-spaces/src/i18n/locales/zh-Hans/spaces.json@@ -63,7 +63,7 @@"spaces.create.creating": "正在创建 Space…","spaces.sidebar.section.this_mac": "这台 Mac","spaces.sidebar.section.connected": "已连接",- "spaces.sidebar.section.my_computers": "我的电脑",+ "spaces.sidebar.section.my_computers": "我的机器","spaces.sidebar.empty": "还没有任何 Spaces","spaces.sidebar.no_matches": "没有匹配项","spaces.status.failed": "失败",diff --git a/docs/content/docs/cua-cli/reference/cli/agents.mdx b/docs/content/docs/cua-cli/reference/cli/agents.mdxindex 14fb707970..d4cb813e3a 100644--- a/docs/content/docs/cua-cli/reference/cli/agents.mdx+++ b/docs/content/docs/cua-cli/reference/cli/agents.mdx@@ -34,6 +34,7 @@ description: "Agents in a Space, connecting your AI agents, the stdio MCP server| [`cua agent keys`](#cua-agent-keys) | The provider keys agents get, kept in the Keychain by the Cua daemon (Cua Spaces → Settings → Connectors). || [`cua agent keys ls`](#cua-agent-keys-ls) | List the saved keys (never their values). || [`cua agent keys set`](#cua-agent-keys-set) | Add or replace a key, read from stdin. |+| [`cua agent keys check`](#cua-agent-keys-check) | Ask each provider whether the saved API keys still work (a cheap read-only request; nothing is sent that is not a key's own request). || [`cua agent keys rm`](#cua-agent-keys-rm) | Remove the key a run gets as ENV. || [`cua agent create`](#cua-agent-create) | Deprecated alias of `add`. || [`cua agent persistent`](#cua-agent-persistent) | Deprecated alias of `ls` (without a sandbox). |@@ -565,6 +566,20 @@ cua agent keys set anthropiccua agent keys set other --env GEMINI_API_KEY```+#### `cua agent keys check`++Ask each provider whether the saved API keys still work (a cheap read-only request; nothing is sent that is not a key's own request). A key the provider refuses is listed as needing a reconnect, and runs are not given it until it is saved again.++```text output+cua agent keys check [OPTIONS]+```++**Examples**++```bash test="cli-shape" id="ref-cua-agent-keys-check"+cua agent keys check+```+#### `cua agent keys rm`Remove the key a run gets as ENV.diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdxindex 654c4a49a5..09b0b3f637 100644--- a/docs/content/docs/cua-cli/reference/cli/index.mdx+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx@@ -81,7 +81,7 @@ Agents in a Space, connecting your AI agents, the stdio MCP server, and recorded| Command | Description | Subcommands || --- | --- | --- |-| <span id="cua-agent"></span><span id="cua-agent-add"></span><span id="cua-agent-run"></span><span id="cua-agent-ls"></span><span id="cua-agent-logs"></span><span id="cua-agent-send"></span><span id="cua-agent-interrupt"></span><span id="cua-agent-stop"></span><span id="cua-agent-status"></span><span id="cua-agent-rm"></span><span id="cua-agent-ensure"></span><span id="cua-agent-schedule"></span><span id="cua-agent-schedule-add"></span><span id="cua-agent-schedule-ls"></span><span id="cua-agent-schedule-rm"></span><span id="cua-agent-schedule-enable"></span><span id="cua-agent-schedule-disable"></span><span id="cua-agent-sessions"></span><span id="cua-agent-harnesses"></span><span id="cua-agent-keys"></span><span id="cua-agent-keys-ls"></span><span id="cua-agent-keys-set"></span><span id="cua-agent-keys-rm"></span><span id="cua-agent-create"></span><span id="cua-agent-persistent"></span><span id="cua-agent-tell"></span><span id="cua-agent-save"></span><span id="cua-agent-pause"></span><span id="cua-agent-resume"></span><span id="cua-agent-forget"></span><span id="cua-agent-routine"></span><span id="cua-agent-routine-add"></span><span id="cua-agent-routine-ls"></span><span id="cua-agent-routine-rm"></span><span id="cua-agent-routine-enable"></span><span id="cua-agent-routine-disable"></span><span id="cua-agent-allow-computer"></span><span id="cua-agent-revoke-computer"></span><span id="cua-agent-computer-access"></span><span id="cua-agent-notifications"></span>[`cua agent`](/cua-cli/reference/cli/agents#cua-agent) | Agents in a Space: add, send, ls, rm, schedule; run, logs, stop. | [`add`](/cua-cli/reference/cli/agents#cua-agent-add), [`run`](/cua-cli/reference/cli/agents#cua-agent-run), [`ls`](/cua-cli/reference/cli/agents#cua-agent-ls), [`logs`](/cua-cli/reference/cli/agents#cua-agent-logs), [`send`](/cua-cli/reference/cli/agents#cua-agent-send), [`interrupt`](/cua-cli/reference/cli/agents#cua-agent-interrupt), [`stop`](/cua-cli/reference/cli/agents#cua-agent-stop), [`status`](/cua-cli/reference/cli/agents#cua-agent-status), [`rm`](/cua-cli/reference/cli/agents#cua-agent-rm), [`ensure`](/cua-cli/reference/cli/agents#cua-agent-ensure), [`schedule`](/cua-cli/reference/cli/agents#cua-agent-schedule), [`schedule add`](/cua-cli/reference/cli/agents#cua-agent-schedule-add), [`schedule ls`](/cua-cli/reference/cli/agents#cua-agent-schedule-ls), [`schedule rm`](/cua-cli/reference/cli/agents#cua-agent-schedule-rm), [`schedule enable`](/cua-cli/reference/cli/agents#cua-agent-schedule-enable), [`schedule disable`](/cua-cli/reference/cli/agents#cua-agent-schedule-disable), [`sessions`](/cua-cli/reference/cli/agents#cua-agent-sessions), [`harnesses`](/cua-cli/reference/cli/agents#cua-agent-harnesses), [`keys`](/cua-cli/reference/cli/agents#cua-agent-keys), [`keys ls`](/cua-cli/reference/cli/agents#cua-agent-keys-ls), [`keys set`](/cua-cli/reference/cli/agents#cua-agent-keys-set), [`keys rm`](/cua-cli/reference/cli/agents#cua-agent-keys-rm), [`create`](/cua-cli/reference/cli/agents#cua-agent-create), [`persistent`](/cua-cli/reference/cli/agents#cua-agent-persistent), [`tell`](/cua-cli/reference/cli/agents#cua-agent-tell), [`save`](/cua-cli/reference/cli/agents#cua-agent-save), [`pause`](/cua-cli/reference/cli/agents#cua-agent-pause), [`resume`](/cua-cli/reference/cli/agents#cua-agent-resume), [`forget`](/cua-cli/reference/cli/agents#cua-agent-forget), [`routine`](/cua-cli/reference/cli/agents#cua-agent-routine), [`routine add`](/cua-cli/reference/cli/agents#cua-agent-routine-add), [`routine ls`](/cua-cli/reference/cli/agents#cua-agent-routine-ls), [`routine rm`](/cua-cli/reference/cli/agents#cua-agent-routine-rm), [`routine enable`](/cua-cli/reference/cli/agents#cua-agent-routine-enable), [`routine disable`](/cua-cli/reference/cli/agents#cua-agent-routine-disable), [`allow-computer`](/cua-cli/reference/cli/agents#cua-agent-allow-computer), [`revoke-computer`](/cua-cli/reference/cli/agents#cua-agent-revoke-computer), [`computer-access`](/cua-cli/reference/cli/agents#cua-agent-computer-access), [`notifications`](/cua-cli/reference/cli/agents#cua-agent-notifications) |+| <span id="cua-agent"></span><span id="cua-agent-add"></span><span id="cua-agent-run"></span><span id="cua-agent-ls"></span><span id="cua-agent-logs"></span><span id="cua-agent-send"></span><span id="cua-agent-interrupt"></span><span id="cua-agent-stop"></span><span id="cua-agent-status"></span><span id="cua-agent-rm"></span><span id="cua-agent-ensure"></span><span id="cua-agent-schedule"></span><span id="cua-agent-schedule-add"></span><span id="cua-agent-schedule-ls"></span><span id="cua-agent-schedule-rm"></span><span id="cua-agent-schedule-enable"></span><span id="cua-agent-schedule-disable"></span><span id="cua-agent-sessions"></span><span id="cua-agent-harnesses"></span><span id="cua-agent-keys"></span><span id="cua-agent-keys-ls"></span><span id="cua-agent-keys-set"></span><span id="cua-agent-keys-check"></span><span id="cua-agent-keys-rm"></span><span id="cua-agent-create"></span><span id="cua-agent-persistent"></span><span id="cua-agent-tell"></span><span id="cua-agent-save"></span><span id="cua-agent-pause"></span><span id="cua-agent-resume"></span><span id="cua-agent-forget"></span><span id="cua-agent-routine"></span><span id="cua-agent-routine-add"></span><span id="cua-agent-routine-ls"></span><span id="cua-agent-routine-rm"></span><span id="cua-agent-routine-enable"></span><span id="cua-agent-routine-disable"></span><span id="cua-agent-allow-computer"></span><span id="cua-agent-revoke-computer"></span><span id="cua-agent-computer-access"></span><span id="cua-agent-notifications"></span>[`cua agent`](/cua-cli/reference/cli/agents#cua-agent) | Agents in a Space: add, send, ls, rm, schedule; run, logs, stop. | [`add`](/cua-cli/reference/cli/agents#cua-agent-add), [`run`](/cua-cli/reference/cli/agents#cua-agent-run), [`ls`](/cua-cli/reference/cli/agents#cua-agent-ls), [`logs`](/cua-cli/reference/cli/agents#cua-agent-logs), [`send`](/cua-cli/reference/cli/agents#cua-agent-send), [`interrupt`](/cua-cli/reference/cli/agents#cua-agent-interrupt), [`stop`](/cua-cli/reference/cli/agents#cua-agent-stop), [`status`](/cua-cli/reference/cli/agents#cua-agent-status), [`rm`](/cua-cli/reference/cli/agents#cua-agent-rm), [`ensure`](/cua-cli/reference/cli/agents#cua-agent-ensure), [`schedule`](/cua-cli/reference/cli/agents#cua-agent-schedule), [`schedule add`](/cua-cli/reference/cli/agents#cua-agent-schedule-add), [`schedule ls`](/cua-cli/reference/cli/agents#cua-agent-schedule-ls), [`schedule rm`](/cua-cli/reference/cli/agents#cua-agent-schedule-rm), [`schedule enable`](/cua-cli/reference/cli/agents#cua-agent-schedule-enable), [`schedule disable`](/cua-cli/reference/cli/agents#cua-agent-schedule-disable), [`sessions`](/cua-cli/reference/cli/agents#cua-agent-sessions), [`harnesses`](/cua-cli/reference/cli/agents#cua-agent-harnesses), [`keys`](/cua-cli/reference/cli/agents#cua-agent-keys), [`keys ls`](/cua-cli/reference/cli/agents#cua-agent-keys-ls), [`keys set`](/cua-cli/reference/cli/agents#cua-agent-keys-set), [`keys check`](/cua-cli/reference/cli/agents#cua-agent-keys-check), [`keys rm`](/cua-cli/reference/cli/agents#cua-agent-keys-rm), [`create`](/cua-cli/reference/cli/agents#cua-agent-create), [`persistent`](/cua-cli/reference/cli/agents#cua-agent-persistent), [`tell`](/cua-cli/reference/cli/agents#cua-agent-tell), [`save`](/cua-cli/reference/cli/agents#cua-agent-save), [`pause`](/cua-cli/reference/cli/agents#cua-agent-pause), [`resume`](/cua-cli/reference/cli/agents#cua-agent-resume), [`forget`](/cua-cli/reference/cli/agents#cua-agent-forget), [`routine`](/cua-cli/reference/cli/agents#cua-agent-routine), [`routine add`](/cua-cli/reference/cli/agents#cua-agent-routine-add), [`routine ls`](/cua-cli/reference/cli/agents#cua-agent-routine-ls), [`routine rm`](/cua-cli/reference/cli/agents#cua-agent-routine-rm), [`routine enable`](/cua-cli/reference/cli/agents#cua-agent-routine-enable), [`routine disable`](/cua-cli/reference/cli/agents#cua-agent-routine-disable), [`allow-computer`](/cua-cli/reference/cli/agents#cua-agent-allow-computer), [`revoke-computer`](/cua-cli/reference/cli/agents#cua-agent-revoke-computer), [`computer-access`](/cua-cli/reference/cli/agents#cua-agent-computer-access), [`notifications`](/cua-cli/reference/cli/agents#cua-agent-notifications) || <span id="cua-thread"></span><span id="cua-thread-join"></span><span id="cua-thread-inbox"></span><span id="cua-thread-post"></span><span id="cua-thread-read"></span>[`cua thread`](/cua-cli/reference/cli/agents#cua-thread) | A Space's thread, as the agent this computer joined with `cua join`: say who you are, read your inbox, post. | [`join`](/cua-cli/reference/cli/agents#cua-thread-join), [`inbox`](/cua-cli/reference/cli/agents#cua-thread-inbox), [`post`](/cua-cli/reference/cli/agents#cua-thread-post), [`read`](/cua-cli/reference/cli/agents#cua-thread-read) || <span id="cua-join"></span>[`cua join`](/cua-cli/reference/cli/agents#cua-join) | Join a Space as an agent on this computer, with the code from a "Join my Cua Space" link. | || <span id="cua-connect"></span><span id="cua-connect-detect"></span><span id="cua-connect-setup"></span><span id="cua-connect-status"></span><span id="cua-connect-remove"></span><span id="cua-connect-update"></span>[`cua connect`](/cua-cli/reference/cli/agents#cua-connect) | Connect the AI agents on this computer to Cua: install the cua skills and configure the cua MCP server. | [`detect`](/cua-cli/reference/cli/agents#cua-connect-detect), [`setup`](/cua-cli/reference/cli/agents#cua-connect-setup), [`status`](/cua-cli/reference/cli/agents#cua-connect-status), [`remove`](/cua-cli/reference/cli/agents#cua-connect-remove), [`update`](/cua-cli/reference/cli/agents#cua-connect-update) |diff --git a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdxindex 20fcfb9986..71f5ef1a27 100644--- a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx+++ b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx@@ -49,7 +49,7 @@ description: "Your Spaces and machines, unattended access on this machine, devic| [`cua devices status`](#cua-devices-status) | This device: enrolled, waiting for approval, or not enrolled. || [`cua devices enroll`](#cua-devices-enroll) | Enroll this device. || [`cua devices approve`](#cua-devices-approve) | Approve a new device (or re-verify an expired one) from this enrolled device, by the code it shows or by its id. |-| [`cua devices ls`](#cua-devices-ls) | Your devices and their state. |+| [`cua devices ls`](#cua-devices-ls) | Your signed-in machines and their state. || [`cua devices rename`](#cua-devices-rename) | Rename a device. || [`cua devices revoke`](#cua-devices-revoke) | Revoke a device: it can no longer list or reach your computers. || [`cua devices audit`](#cua-devices-audit) | Who accessed what, and when: enrollments, device sessions, computer access (yours and by accounts you share with), sharing changes. |@@ -908,7 +908,7 @@ cua devices approve dev_0123456789abcdef01234567### `cua devices ls`-Your devices and their state.+Your signed-in machines and their state.```text outputcua devices ls [OPTIONS]diff --git a/docs/content/docs/cua-cli/reference/mcp-tools.mdx b/docs/content/docs/cua-cli/reference/mcp-tools.mdxindex 25263c7585..0b6589dc01 100644--- a/docs/content/docs/cua-cli/reference/mcp-tools.mdx+++ b/docs/content/docs/cua-cli/reference/mcp-tools.mdx@@ -242,7 +242,7 @@ Permission: `images:list`.### `sandbox_list`-List sandboxes: local and direct ones by default, each row with location (local or direct). Pass location to list only one kind.+List sandboxes: local and direct ones by default, each row with location (local or direct). Pass location to list only one kind. When the user is signed in and has other machines, a note after the rows names them and the route to use: a machine's own desktop is the Space relay:<id> (computer tools and space_bash take it as `space`), and new Spaces go to one with create_space on="host:<name>".Permission: `sandbox:list`.diff --git a/docs/content/docs/spaces/concepts/computers-devices-and-spaces.mdx b/docs/content/docs/spaces/concepts/computers-devices-and-spaces.mdxindex 24d0dc50f2..df5bfcaa01 100644--- a/docs/content/docs/spaces/concepts/computers-devices-and-spaces.mdx+++ b/docs/content/docs/spaces/concepts/computers-devices-and-spaces.mdx@@ -8,9 +8,9 @@ Spaces. These names describe different roles:| Name | What it is | Where you see or use it || --- | --- | --- |-| Signed-in device | A computer enrolled to reach your account's machines, once, with a second factor. Signing in does not make it a host. | **Settings > Devices** or `cua devices ls`, with an id such as `dev_…`. |-| Machine | A computer set up with **Add a computer** or `cua host setup` to share its desktop, provide Spaces, or both. | The **Computers** page. When **Provide Spaces** is on, `--on host:<machine-id>` creates new Spaces on it. |-| The machine's shared desktop | The computer's own screen, input, shell and files as a Space, while **Share this desktop** is on. It is not a sandbox. | `relay:<machine-id>` for a computer set up on the relay. A direct host (set up with `--direct`, no relay record) is its own `direct:<host:port>` Space, added with `cua spaces add <host:port> --host`. For a relay computer, its row on **Computers** says **Desktop shared**, or **Desktop · 2 Spaces** when it also runs Spaces; the desktop is not counted among them. |+| Signed-in device | A computer enrolled to reach your account's machines, once, with a second factor. Signing in does not make it a host. | The **Machines** tab (a machine that is only signed in shows as **Signed in, not sharing**) or `cua devices ls`, with an id such as `dev_…`. |+| Machine | A computer set up with **Add a computer** or `cua host setup` to share its desktop, provide Spaces, or both. | The **Machines** tab. When **Provide Spaces** is on, `--on host:<machine-id>` creates new Spaces on it. |+| The machine's shared desktop | The computer's own screen, input, shell and files as a Space, while **Share this desktop** is on. It is not a sandbox. | `relay:<machine-id>` for a computer set up on the relay. A direct host (set up with `--direct`, no relay record) is its own `direct:<host:port>` Space, added with `cua spaces add <host:port> --host`. For a relay computer, its row on **Machines** says **Desktop shared**, or **Desktop and 2 Spaces** when it also runs Spaces; the desktop is not counted among them. || Sandbox Space | A container, VM or microVM created for work, on this computer or on a machine that provides Spaces. See [Space kinds](/spaces/concepts/space-kinds). | `local:<name>` on this computer. On a relay machine that provides Spaces it has its own `relay:` id, with `host` naming the computer that runs it. On a direct host (set up with `--direct`, no relay) it has a `direct:<host:port>` id, whether created on that host or added by address. |**Share this desktop** and **Provide Spaces** are separate settings. Hosting@@ -24,10 +24,10 @@ that computer, in the app or with `cua auth login`, also gives it a devicerecord. The relay keeps the two apart and doesn't link them: they are onecomputer in two roles, not two computers.-The **Computers** page joins them into one row when it can match them safely,+The **Machines** tab joins them into one row when it can match them safely,for example by the same id or matching names. If the match is unclear, such as-two Macs with the same name, they stay as separate rows. A row that is only a-device is not a host, so **Run on** in **New Space** never offers it.+two Macs with the same name, they stay as separate rows. A row that is only signed in+(**Signed in, not sharing**) is not a host, so **Run on** in **New Space** never offers it.See [Add a computer](/spaces/guides/add-a-computer) for the two settings and[How Spaces works](/spaces/concepts/how-spaces-works#space-ids) for Space ids.diff --git a/docs/content/docs/spaces/guides/add-a-computer.mdx b/docs/content/docs/spaces/guides/add-a-computer.mdxindex 57f328ddbf..ae435af8e7 100644--- a/docs/content/docs/spaces/guides/add-a-computer.mdx+++ b/docs/content/docs/spaces/guides/add-a-computer.mdx@@ -148,13 +148,12 @@ cua devices audit # who opened which machine, from which device, and whencua devices revoke dev_0123456789abcdef01234567```-A computer that is gone: `cua machines rm <name>` removes it from your relay directory and revokes its device.+A machine that is gone: `cua machines rm <name>` removes it from your relay directory and revokes its device.-In the app, **Settings > Devices** shows this device's enrollment, your devices-with Rename and Revoke, and Recent Access (which device opened which computer,-and when). When another device asks to join, the app shows an approval sheet:-Approve asks for Touch ID or your login password first, and Deny revokes that-device.+In the app, the **Machines** tab holds all of it. A machine that asks to join waits at the top+with **Add machine** and **Not me** (Add machine asks for Touch ID or your login password first, and+Not me refuses it), and the sidebar shows how many wait. Each machine's page has Rename, Revoke and+its recent access (who opened it, and when), and this machine's Details say how far it is trusted.## Share it with your team@@ -234,7 +233,7 @@ The computer has two settings, and each works on its own:| Setting | What it does | Default | `--share spaces` ||---|---|---|---|| Let other machines control this desktop (`--desktop`) | The computer itself is a Space: its screen, input, shell and files. | on | off |-| Let other machines create Spaces here (`--provide-spaces`) | Your enrolled devices can create, list and delete Spaces on it. | on for a new setup | on |+| Let other machines create Spaces here (`--provide-spaces`) | Your trusted machines can create, list and delete Spaces on it. | on for a new setup | on |A computer set up before this default keeps what it had: setting it up againnever turns **Provide Spaces** on unless you pass `--share spaces` or `--share both`. With@@ -554,7 +553,7 @@ restarts, the Mac opens the same port again.| What you see | What to do ||---|---|| "That code didn't work" | A code works once and expires. Open **Add a machine** again for a new one. |-| "This Mac can't make codes yet." | This device isn't enrolled. Enroll it in **Settings, Devices**, or use **Sign in there**. |+| "This Mac can't make codes yet." | This machine isn't trusted yet. Choose **Trust this machine** on its page in **Machines**, or use **Sign in there**. || The computer never appears | On that computer, run `cua host status`. It shows the service state and any missing permission. || The computer shows **Offline** | It is off, asleep or disconnected. Wake it or reconnect it, then run `cua host status` on it. |diff --git a/docs/content/docs/spaces/reference/threads.mdx b/docs/content/docs/spaces/reference/threads.mdxindex a0d9fb6306..41ac912b91 100644--- a/docs/content/docs/spaces/reference/threads.mdx+++ b/docs/content/docs/spaces/reference/threads.mdx@@ -62,7 +62,7 @@ Every Space has one thread: what people and its agent members said, the tasks @m#### Result-JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.+JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`, `since_ms`, `text`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`; `since_ms`: when its oldest open task was given; `text`: what it has said so far this turn, the whole text each time and only while it streams, replaced by its reply when the turn ends); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.#### Errorsdiff --git a/libs/cua/crates/cua-agents/src/failure.rs b/libs/cua/crates/cua-agents/src/failure.rsindex 467c9cf20a..92f50e9646 100644--- a/libs/cua/crates/cua-agents/src/failure.rs+++ b/libs/cua/crates/cua-agents/src/failure.rs@@ -37,38 +37,132 @@ pub struct Failure {pub retryable: bool,}-/// The words providers and harnesses use for "your credential does not work".-const AUTH_MARKERS: &[&str] = &[- "authentication_failed",- "authentication required",- "authentication failed",- "failed to authenticate",- "invalid x-api-key",- "invalid api key",- "incorrect api key",- "oauth token",- "oauth access token",- "not connected to any ai provider",- "no credential in this space",- "invalid bearer token",- "unauthorized",- "(code -32000)",- "code: -32000",- "\"code\":-32000",- "\"code\": -32000",+/// One way a provider or harness says "your credential does not work".+struct AuthText {+ /// The harness that says it; empty: any of them (a provider's own words come through every harness).+ harness: &'static str,+ /// Lower-case text to find.+ marker: &'static str,+ /// The provider it names, when the words name one.+ provider: Option<&'static str>,+ /// Definite enough to read a short reply by (a normal answer that talks about authentication+ /// would not say it this way), not only an error.+ reply: bool,+}++const fn any(marker: &'static str, reply: bool) -> AuthText {+ AuthText {+ harness: "",+ marker,+ provider: None,+ reply,+ }+}++/// Every wording of an authentication failure, in one place. Per-harness tests walk it+/// (`every_row_is_read_for_its_harness`): a harness that words it a new way gets a row and a test.+const AUTH_TEXTS: &[AuthText] = &[+ // What the providers say, through any harness.+ any("authentication_failed", true),+ any("authentication required", false),+ any("authentication failed", false),+ any("failed to authenticate", true),+ any("invalid x-api-key", true),+ any("invalid api key", true),+ any("incorrect api key", true),+ any("oauth token", false),+ any("oauth access token", true),+ any("invalid bearer token", true),+ any("unauthorized", false),+ // JSON-RPC's "internal error" that the ACP adapters use for a refused credential.+ any("(code -32000)", false),+ any("code: -32000", false),+ any("\"code\":-32000", false),+ any("\"code\": -32000", false),+ // Claude Code.+ AuthText {+ harness: "claude-code",+ marker: "invalid authentication credentials",+ provider: Some("anthropic"),+ reply: true,+ },+ AuthText {+ harness: "claude-code",+ marker: "please run /login",+ provider: Some("anthropic"),+ reply: true,+ },+ // Codex.+ AuthText {+ harness: "openai-codex",+ marker: "incorrect api key provided",+ provider: Some("openai"),+ reply: true,+ },+ AuthText {+ harness: "openai-codex",+ marker: "refresh token",+ provider: Some("openai"),+ reply: false,+ },+ // Hermes answers a refused key as an ordinary reply, with its own advice.+ AuthText {+ harness: "hermes",+ marker: "not connected to any ai provider",+ provider: None,+ reply: true,+ },+ AuthText {+ harness: "hermes",+ marker: "rejected your api key",+ provider: None,+ reply: true,+ },+ AuthText {+ harness: "hermes",+ marker: "hermes setup",+ provider: None,+ reply: true,+ },+ AuthText {+ harness: "hermes",+ marker: "no credential in this space",+ provider: None,+ reply: true,+ },];-/// Whether `text` is an authentication failure.+/// Statuses that read as a refused credential when the text is the status of an API error.+const AUTH_STATUSES: &[&str] = &["api error: 401", "status 401", "http 401", "error 401"];++/// The longest reply that can be an error in disguise: a real answer is longer than any harness's error sentence.+const MAX_REPLY: usize = 900;++fn says_auth(harness: &str, t: &str, reply_only: bool) -> bool {+ AUTH_TEXTS+ .iter()+ .filter(|a| a.harness.is_empty() || a.harness == harness || harness.is_empty())+ .filter(|a| !reply_only || a.reply)+ .any(|a| t.contains(a.marker))+}++/// Whether `text` is an authentication failure (an error of a turn or a start: every wording counts).pub fn is_auth_failure(text: &str) -> bool {let t = text.to_ascii_lowercase();- if AUTH_MARKERS.iter().any(|m| t.contains(m)) {- return true;+ says_auth("", &t, false) || AUTH_STATUSES.iter().any(|s| t.contains(s))+}++/// Whether `reply`, a harness's ordinary answer, is really an authentication failure it reported as+/// text (Hermes answers "Anthropic rejected your API key ..." as a successful turn). Only a short+/// reply that says it in a harness's definite words counts, so an answer that talks about+/// authentication, or quotes a 401 it found in someone's code, is left alone.+pub fn is_auth_failure_reply(harness: &str, reply: &str) -> bool {+ let t = reply.trim().to_ascii_lowercase();+ if t.is_empty() || t.chars().count() > MAX_REPLY {+ return false;}- // A bare 401 counts when it is the status of an API error.- t.contains("api error: 401")- || t.contains("status 401")- || t.contains("http 401")- || t.contains("error 401")+ says_auth(harness, &t, true)+ || (AUTH_STATUSES.iter().any(|s| t.contains(s)) && t.contains("oauth"))}fn cap(text: &str) -> String {@@ -86,6 +180,15 @@ fn cap(text: &str) -> String {/// from the text where the harness has more than one.fn provider_for(harness: &str, text: &str) -> Option<String> {let t = text.to_ascii_lowercase();+ // A row that names its provider.+ if let Some(p) = AUTH_TEXTS+ .iter()+ .filter(|a| a.harness == harness || a.harness.is_empty())+ .find(|a| t.contains(a.marker))+ .and_then(|a| a.provider)+ {+ return Some(p.into());+ }let from_text = if t.contains("anthropic") || t.contains("claude") {Some("anthropic")} else if t.contains("openai") || t.contains("chatgpt") || t.contains("codex") {@@ -121,13 +224,47 @@ pub fn classify(harness: &str, text: &str) -> Failure {}}+/// The credential was there and the provider refused it (so signing in again, not connecting for+/// the first time, is the fix).+fn refused(text: &str) -> bool {+ let t = text.to_ascii_lowercase();+ [+ "rejected your api key",+ "invalid x-api-key",+ "invalid api key",+ "incorrect api key",+ "oauth access token is invalid",+ "invalid authentication credentials",+ "401",+ ]+ .iter()+ .any(|m| t.contains(m))+}++/// A provider's name for a person.+fn provider_label(provider: Option<&str>) -> &'static str {+ match provider {+ Some("anthropic") => "Anthropic",+ Some("openai") => "OpenAI",+ _ => "The provider",+ }+}+/// What a person reads instead of the raw error, in plain words from the-/// agent's side (it is the agent's reply).+/// agent's side (it is the agent's reply). The harness's own advice ("run+/// `hermes setup`") is never in it: Cua manages the sign-in, and the complete+/// text stays under Show details.pub fn plain(f: &Failure, harness: &str) -> String {match f.class {FailureClass::NeedsConnect => match (harness, f.provider.as_deref()) {+ ("claude-code", _) if refused(&f.message) => "Claude needs you to sign in again.".into(),+ ("openai-codex", _) if refused(&f.message) => "OpenAI needs you to sign in again.".into(),("claude-code", _) => "I can't reach Claude yet. Connect Claude, then try again.".into(),("openai-codex", _) => "I can't reach OpenAI yet. Connect OpenAI, then try again.".into(),+ ("hermes", p) if refused(&f.message) => format!(+ "{} rejected the key Hermes used. Update it, then try again.",+ provider_label(p)+ ),// The subscription sign-ins are Claude Code's and Codex's alone.("hermes", _) => "Hermes needs an Anthropic API key or another provider. Your Claude subscription sign-in only works in Claude Code.".into(),(h, _) => {@@ -198,4 +335,100 @@ mod tests {assert!(!p.contains("401") && !p.contains('{'), "{p}");assert!(!p.contains('\u{b7}'));}++ /// Every row of the table is read for the harness that says it (and a row that is not for a harness+ /// is read for all of them), as an error and, where it is definite, as a reply.+ #[test]+ fn every_row_is_read_for_its_harness() {+ for row in AUTH_TEXTS {+ let harnesses: Vec<&str> = if row.harness.is_empty() {+ vec!["claude-code", "openai-codex", "hermes"]+ } else {+ vec![row.harness]+ };+ for h in harnesses {+ let text = format!("Something failed: {} (please look)", row.marker);+ assert!(is_auth_failure(&text), "{h}: {}", row.marker);+ assert_eq!(+ is_auth_failure_reply(h, &text),+ row.reply,+ "{h} reply: {}",+ row.marker+ );+ assert_eq!(+ classify(h, &text).class,+ FailureClass::NeedsConnect,+ "{h}: {}",+ row.marker+ );+ }+ }+ // A harness's own wording is not another harness's.+ assert!(!is_auth_failure_reply(+ "claude-code",+ "run `hermes setup` first"+ ));+ }++ /// The owner's reply, word for word: Hermes answers a refused key as an ordinary turn.+ #[test]+ fn hermes_answering_a_refused_key_as_text_is_a_connect_failure() {+ let reply = "Anthropic rejected your API key, so the model can't be reached. Update it in Settings -> Providers, or run `hermes setup` in a terminal. Provider said: HTTP 401: OAuth access token is invalid.";+ assert!(is_auth_failure_reply("hermes", reply));+ let f = classify("hermes", reply);+ assert_eq!(f.class, FailureClass::NeedsConnect);+ assert_eq!(f.provider.as_deref(), Some("anthropic"));+ assert_eq!(f.message, reply, "the complete text stays for Show details");+ let p = plain(&f, "hermes");+ assert_eq!(+ p,+ "Anthropic rejected the key Hermes used. Update it, then try again."+ );+ // The harness's own advice never reaches the summary.+ assert!(+ !p.contains("hermes setup") && !p.contains("Settings ->") && !p.contains("401"),+ "{p}"+ );+ }++ #[test]+ fn claude_and_codex_say_sign_in_again_when_their_credential_was_refused() {+ let f = classify(+ "claude-code",+ "Internal error: Failed to authenticate. API Error: 401 OAuth access token is invalid",+ );+ assert_eq!(+ plain(&f, "claude-code"),+ "Claude needs you to sign in again."+ );+ let f = classify("openai-codex", "Incorrect API key provided: sk-...abcd");+ assert_eq!(+ plain(&f, "openai-codex"),+ "OpenAI needs you to sign in again."+ );+ // Nothing saved at all is a first connect, not a sign-in again.+ let f = classify("claude-code", "Authentication required");+ assert_eq!(+ plain(&f, "claude-code"),+ "I can't reach Claude yet. Connect Claude, then try again."+ );+ }++ /// An answer that talks about authentication is an answer.+ #[test]+ fn a_normal_reply_is_never_read_as_a_failure() {+ for reply in [+ "I fixed the login bug. The endpoint returned 401 Unauthorized when the token was missing, so I added the header.",+ "Done. Tests pass. The OAuth token refresh now runs before each request.",+ "Here is how authentication works in your app: the API checks the x-api-key header and answers HTTP 401 if it is missing.",+ "",+ ] {+ for h in ["claude-code", "openai-codex", "hermes"] {+ assert!(!is_auth_failure_reply(h, reply), "{h}: {reply}");+ }+ }+ // A long answer that happens to contain the words is an answer too.+ let long = format!("{} not connected to any AI provider", "word ".repeat(400));+ assert!(!is_auth_failure_reply("hermes", &long));+ }}diff --git a/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs b/libs/cua/crates/cua-cli/src/agent_keys_cmd.rsindex bbe436653c..ba96deff1d 100644--- a/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs+++ b/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs@@ -6,6 +6,7 @@//! pbpaste | cua agent keys set anthropic # the key comes from stdin, never argv//! cua agent keys set other --env MISTRAL_API_KEY < key.txt//! cua agent keys rm ANTHROPIC_API_KEY+//! cua agent keys check # ask each provider whether the saved keys still work//! ```//!//! These are the daemon's app methods (`agent_keys.*`), not MCP tools: no@@ -37,6 +38,13 @@ pub enum KeysCmd {#[arg(long)]env: Option<String>,},+ /// Ask each provider whether the saved API keys still work (a cheap+ /// read-only request; nothing is sent that is not a key's own request).+ /// A key the provider refuses is listed as needing a reconnect, and runs+ /// are not given it until it is saved again.+ #[command(after_help = "Examples:+ cua agent keys check")]+ Check,/// Remove the key a run gets as ENV.#[command(after_help = "Examples:cua agent keys rm ANTHROPIC_API_KEY")]@@ -72,6 +80,7 @@ pub async fn run() -> Result<i32, CuaError> {let (method, args) = match cmd.unwrap_or(KeysCmd::Ls) {KeysCmd::Ls => ("agent_keys.list", serde_json::json!({})),+ KeysCmd::Check => ("agent_keys.check", serde_json::json!({})),KeysCmd::Set { provider, env } => {let value = read_key(&mut std::io::stdin(), std::io::stdin().is_terminal())?;let mut a = serde_json::json!({ "provider": provider, "value": value });@@ -126,10 +135,18 @@ fn lines(report: &serde_json::Value) -> Vec<String> {"{:<10} {:<24} {}",k["provider"].as_str().unwrap_or(""),k["env"].as_str().unwrap_or(""),- if last4.is_empty() {- "saved".to_string()- } else {- format!("****{last4}")+ {+ let shown = if last4.is_empty() {+ "saved".to_string()+ } else {+ format!("****{last4}")+ };+ // A key the provider refused (or that expired) no longer works.+ if k["expired"] == true {+ format!("{shown} needs reconnect")+ } else {+ shown+ }}));}@@ -159,5 +176,11 @@ mod tests {);let r = serde_json::json!({"keys": [], "available": false, "unavailable": "no Keychain"});assert!(lines(&r)[0].contains("no Keychain"));+ // A key the provider refused says so.+ let r = serde_json::json!({"keys": [{"provider": "openai", "env": "OPENAI_API_KEY", "last4": "9z9z", "added_ms": 1, "expired": true}], "available": true});+ assert_eq!(+ lines(&r),+ vec!["openai OPENAI_API_KEY ****9z9z needs reconnect"]+ );}}diff --git a/libs/cua/crates/cua-cli/src/devices_cmd.rs b/libs/cua/crates/cua-cli/src/devices_cmd.rsindex 60a79394da..696ea1b4b5 100644--- a/libs/cua/crates/cua-cli/src/devices_cmd.rs+++ b/libs/cua/crates/cua-cli/src/devices_cmd.rs@@ -61,7 +61,7 @@ pub enum DevicesCmd {#[arg(long, hide = true)]relay: Option<String>,},- /// Your devices and their state.+ /// Your signed-in machines and their state.#[command(visible_alias = "list",after_help = "Examples:diff --git a/libs/cua/crates/cua-cli/src/mcp.rs b/libs/cua/crates/cua-cli/src/mcp.rsindex 4a9a2a65c2..919d5ac70e 100644--- a/libs/cua/crates/cua-cli/src/mcp.rs+++ b/libs/cua/crates/cua-cli/src/mcp.rs@@ -356,7 +356,7 @@ const TOOLS: &[Tool] = &[Tool {name: "sandbox_list",permission: "sandbox:list",- description: "List sandboxes: local and direct ones by default, each row with location (local or direct). Pass location to list only one kind.",+ description: "List sandboxes: local and direct ones by default, each row with location (local or direct). Pass location to list only one kind. When the user is signed in and has other machines, a note after the rows names them and the route to use: a machine's own desktop is the Space relay:<id> (computer tools and space_bash take it as `space`), and new Spaces go to one with create_space on=\"host:<name>\".",params: &[("location","string",@@ -1014,6 +1014,60 @@ fn text(s: impl Into<String>) -> ToolResult {Ok(vec![json!({"type": "text", "text": s.into()})])}+/// The user's other machines, from the Spaces list (`list_spaces` rows `relay:<machine>`,+/// a Space on a machine is `relay:<machine>/<name>`), and the route that reaches each. `None`+/// when the user is not signed in or has no other machine: nothing to say then.+async fn other_machines_note(cua: &Cua) -> Option<String> {+ let text = cua+ .spaces()+ .call_tool_json("list_spaces".into(), None)+ .await+ .ok()?+ .text;+ machines_note(&serde_json::from_str::<Vec<Value>>(&text).ok()?)+}++/// See [`other_machines_note`].+fn machines_note(rows: &[Value]) -> Option<String> {+ let machines: Vec<(String, String, bool)> = rows+ .iter()+ .filter_map(|r| {+ let id = r["id"].as_str()?;+ let rest = id.strip_prefix("relay:")?;+ if rest.is_empty() || rest.contains('/') {+ return None;+ }+ let name = r["name"].as_str().filter(|n| !n.is_empty()).unwrap_or(rest);+ Some((+ id.to_string(),+ name.to_string(),+ r["phase"].as_str() == Some("ready"),+ ))+ })+ .collect();+ if machines.is_empty() {+ return None;+ }+ let list = machines+ .iter()+ .map(|(id, name, ready)| {+ format!(+ "{name} ({id}, {})",+ if *ready { "online" } else { "offline" }+ )+ })+ .collect::<Vec<_>>()+ .join("; ");+ let (first_id, first_name, _) = &machines[0];+ Some(format!(+ "note: the sandboxes above are on this machine. The user's other machines: {list}. \+ To use one machine's own desktop, pass its id as `space` (for example \+ space=\"{first_id}\") to computer_screenshot, computer_click, computer_type or space_bash; \+ it must be online and sharing its desktop. To create a Space on one, call create_space \+ with on=\"host:{first_name}\". list_spaces shows their Spaces."+ ))+}+fn jtext(v: Value) -> ToolResult {text(serde_json::to_string_pretty(&v).unwrap_or_default())}@@ -1369,6 +1423,7 @@ impl Server {)));}};+ let all_locations = location.is_none();let l = sbx.list_with_warnings(location).await?;let mut content = jtext(Value::Array(l.sandboxes.iter().map(sandbox::info_json).collect(),@@ -1376,6 +1431,11 @@ impl Server {for w in l.warnings {content.push(json!({"type": "text", "text": format!("warning: {w}")}));}+ // These are this machine's sandboxes. The user's other machines are+ // somewhere else: say so, and which route reaches them.+ if all_locations && let Some(note) = other_machines_note(&self.cua).await {+ content.push(json!({"type": "text", "text": note}));+ }Ok(content)}.await@@ -2155,6 +2215,37 @@ async fn runs_tool(name: &str, a: &Value) -> ToolResult {#[cfg(test)]mod tests {+ #[test]+ fn the_sandbox_list_names_the_users_other_machines_and_the_route_to_use() {+ use super::machines_note;+ use serde_json::json;+ // Nothing to say without another machine (a Space on a machine is not one).+ assert_eq!(machines_note(&[]), None);+ assert_eq!(+ machines_note(&[+ json!({"id": "local:build", "name": "build"}),+ json!({"id": "relay:abc/dev", "name": "dev"})+ ]),+ None+ );+ let note = machines_note(&[+ json!({"id": "relay:0123abcd", "name": "Dillon's MacBook", "phase": "ready"}),+ json!({"id": "relay:0123abcd/dev", "name": "dev", "phase": "ready"}),+ json!({"id": "relay:ffff", "name": "mac-mini", "phase": "offline"}),+ ])+ .unwrap();+ assert!(+ note.contains("Dillon's MacBook (relay:0123abcd, online)"),+ "{note}"+ );+ assert!(note.contains("mac-mini (relay:ffff, offline)"), "{note}");+ // The route: its desktop is `space`, new Spaces go with `on`.+ assert!(note.contains("space=\"relay:0123abcd\""), "{note}");+ assert!(note.contains("on=\"host:Dillon's MacBook\""), "{note}");+ // The Space on the machine is not listed as a machine.+ assert!(!note.contains("relay:0123abcd/dev"), "{note}");+ }+use super::*;#[test]diff --git a/libs/cua/crates/cua-daemon/src/spaces_svc.rs b/libs/cua/crates/cua-daemon/src/spaces_svc.rsindex 8ca5d8ccb8..28d16ccb71 100644--- a/libs/cua/crates/cua-daemon/src/spaces_svc.rs+++ b/libs/cua/crates/cua-daemon/src/spaces_svc.rs@@ -939,9 +939,11 @@ mod imp {// The app's Settings → Connectors methods: not contract tools, so no// MCP server lists or forwards them to an agent.let out = if app_method {- cua_spaces::agents::keys::app_tool(&r.name, args).unwrap_or_else(|| {- cua_spaces::mcp::ToolOutcome::error_message("not_found", r.name.clone())- })+ cua_spaces::agents::keys::app_tool_async(&r.name, args)+ .await+ .unwrap_or_else(|| {+ cua_spaces::mcp::ToolOutcome::error_message("not_found", r.name.clone())+ })} else {caller.scope(self.mcp().call(&r.name, args)).await};diff --git a/libs/cua/crates/cua-sdk/src/native/spaces.rs b/libs/cua/crates/cua-sdk/src/native/spaces.rsindex 9a5b573f5f..8dd8c3bcce 100644--- a/libs/cua/crates/cua-sdk/src/native/spaces.rs+++ b/libs/cua/crates/cua-sdk/src/native/spaces.rs@@ -2669,17 +2669,18 @@ impl Host {async fn tool(&self, name: &str, arguments: Value) -> Result<ToolOut> {match self {Host::Embedded(spaces) => {- let o =- match cua_spaces::agents::keys::is_app_method(name) {- true => cua_spaces::agents::keys::app_tool(name, arguments).unwrap_or_else(- || cua_spaces::mcp::ToolOutcome::error_message("not_found", name),- ),- false => {- cua_spaces::mcp::McpServer::new(spaces.clone())- .call(name, arguments)- .await- }- };+ let o = match cua_spaces::agents::keys::is_app_method(name) {+ true => cua_spaces::agents::keys::app_tool_async(name, arguments)+ .await+ .unwrap_or_else(|| {+ cua_spaces::mcp::ToolOutcome::error_message("not_found", name)+ }),+ false => {+ cua_spaces::mcp::McpServer::new(spaces.clone())+ .call(name, arguments)+ .await+ }+ };Ok(ToolOut {content: o.content,structured: o.structured,diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/devices.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/devices.jsonindex 4eeffef119..b049ccdd0f 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/devices.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/devices.json@@ -6,14 +6,14 @@"view": {"activity": [],"approvals": [],- "banner": "warning: Enroll this device within 5 days to keep reaching your machines. [Enroll…]",+ "banner": "warning: Trust this machine within 5 days to keep reaching your machines. [Trust this machine]","enrolled": false,- "labels": "Devices / This Device / Your Devices / Recent Access (No access yet) / Last seen / Approve… Deny Rename… Revoke… / Rename Device Rename Cancel / New Computers Confirm",+ "labels": "Machines / This Machine / Your Machines / Recent access (No access yet.) / Last seen / Add machine Not me Rename… Revoke… / Rename Machine Rename Cancel / New machines Add machine","recent": [],"rows": [- "Studio | Linux · Enrolled · re-verify in 12 days | seen 1799990000 | "+ "Studio | Linux, Trusted, check again in 12 days | seen 1799990000 | "],- "thisDevice": "grace: Needs enrollment · grace ends @1800432000 name=- [Enroll…]",+ "thisDevice": "grace: Not trusted yet, grace ends @1800432000 name=- [Trust this machine]","unconfirmedMachines": []}},@@ -22,12 +22,12 @@"view": {"activity": [],"approvals": [],- "banner": "critical: Enroll this device to reach your machines. [Enroll…]",+ "banner": "critical: Trust this machine to reach your machines. [Trust this machine]","enrolled": false,- "labels": "Devices / This Device / Your Devices / Recent Access (No access yet) / Last seen / Approve… Deny Rename… Revoke… / Rename Device Rename Cancel / New Computers Confirm",+ "labels": "Machines / This Machine / Your Machines / Recent access (No access yet.) / Last seen / Add machine Not me Rename… Revoke… / Rename Machine Rename Cancel / New machines Add machine","recent": [],"rows": [],- "thisDevice": "needs-enrollment: Needs enrollment @null name=- [Enroll…]",+ "thisDevice": "needs-enrollment: Not trusted yet @null name=- [Trust this machine]","unconfirmedMachines": []}},@@ -36,15 +36,15 @@"view": {"activity": [],"approvals": [],- "banner": "warning: Sign in again to enroll this device, or approve it from an enrolled device with the code K7QX-M2RP. [Enroll…]",+ "banner": "warning: Sign in again to trust this machine, or add it from a machine you already trust with the code K7QX-M2RP. [Trust this machine]","enrolled": false,- "labels": "Devices / This Device / Your Devices / Recent Access (No access yet) / Last seen / Approve… Deny Rename… Revoke… / Rename Device Rename Cancel / New Computers Confirm",+ "labels": "Machines / This Machine / Your Machines / Recent access (No access yet.) / Last seen / Add machine Not me Rename… Revoke… / Rename Machine Rename Cancel / New machines Add machine","recent": [],"rows": [- "MacBook Pro (this device) | macOS · Waiting for approval | seen null | | current",- "Studio | Linux · Enrolled · re-verify in 12 days | seen null | "+ "MacBook Pro (this machine) | macOS, Waiting to be added | seen null | | current",+ "Studio | Linux, Trusted, check again in 12 days | seen null | "],- "thisDevice": "waiting: Waiting for approval @null name=MacBook Pro [Enroll…]",+ "thisDevice": "waiting: Waiting to be added @null name=MacBook Pro [Trust this machine]","unconfirmedMachines": []}},@@ -53,33 +53,33 @@"view": {"activity": ["1799990500 Lost phone was revoked from MacBook Pro",- "1799990400 An unenrolled device opened build-box (notable)",+ "1799990400 An untrusted machine opened build-box (notable)","1799990300 Work laptop asked to join","1799990200 [email protected] opened studio-mac (notable)","1799990100 MacBook Pro opened studio-mac","1799990000 MacBook Pro was approved from dev_a"],"approvals": [- "dev_p: Let “Work laptop” list and open your machines? Only approve a device you just signed in on. | Approve “Work laptop”? / A device signed in to your Cua account and asks to reach your machines.",- "dev_o (expired): Re-verify “Old laptop” for another 30 days? | Re-verify “Old laptop”? / It needs one approval to keep reaching your machines."+ "dev_p: Add “Work laptop” to your machines? Only add a machine you just signed in on. | Add “Work laptop”? / A machine signed in to your Cua account and asks to be added.",+ "dev_o (expired): Keep “Old laptop” on your account for another 30 days? | Keep “Old laptop”? / It needs one approval to keep reaching your machines."],"banner": null,"enrolled": true,- "labels": "Devices / This Device / Your Devices / Recent Access (No access yet) / Last seen / Approve… Deny Rename… Revoke… / Rename Device Rename Cancel / New Computers Confirm",+ "labels": "Machines / This Machine / Your Machines / Recent access (No access yet.) / Last seen / Add machine Not me Rename… Revoke… / Rename Machine Rename Cancel / New machines Add machine","recent": [- "1799990400 An unenrolled device opened build-box (notable)",+ "1799990400 An untrusted machine opened build-box (notable)","1799990200 [email protected] opened studio-mac (notable)","1799990100 MacBook Pro opened studio-mac"],"rows": [- "MacBook Pro (this device) | macOS · Enrolled · re-verify in 30 days | seen 1799999940 | rename,revoke | current | Revoke “MacBook Pro”? / This device will no longer list or reach your machines until you enroll it again.",- "Lost phone | iOS · Revoked | seen null | ",- "Old laptop | Linux · Re-verification due | seen 1797300000 | approve,rename,revoke | Revoke “Old laptop”? / Old laptop will no longer list or reach your machines. To use it again, enroll it again.",- "Work laptop | Windows · Waiting for approval | seen null | approve,rename,revoke | Revoke “Work laptop”? / Work laptop will no longer list or reach your machines. To use it again, enroll it again."+ "MacBook Pro (this machine) | macOS, Trusted, check again in 30 days | seen 1799999940 | rename,revoke | current | Revoke “MacBook Pro”? / This machine will no longer see or reach your machines until you trust it again.",+ "Lost phone | iOS, Revoked | seen null | ",+ "Old laptop | Linux, Needs a quick check | seen 1797300000 | approve,rename,revoke | Revoke “Old laptop”? / Old laptop will no longer see or reach your machines. To use it again, add it again.",+ "Work laptop | Windows, Waiting to be added | seen null | approve,rename,revoke | Revoke “Work laptop”? / Work laptop will no longer see or reach your machines. To use it again, add it again."],- "thisDevice": "enrolled: Enrolled until @1802592000 name=MacBook Pro [-]",+ "thisDevice": "enrolled: Trusted until @1802592000 name=MacBook Pro [-]","unconfirmedMachines": [- "build-box: Confirm “build-box”? / build-box registered to your account without proof it was you: an enrolled device's signature or a sign-in with a second factor. Confirm it only if you recognize it."+ "build-box: Add “build-box”? / build-box registered to your account without proof it was you. Add it only if you recognize it."]}},@@ -88,14 +88,14 @@"view": {"activity": [],"approvals": [],- "banner": "warning: Re-verify this device within 2 days: sign in again, or approve it from another enrolled device. [-]",+ "banner": "warning: Check this machine within 2 days: sign in again, or add it from a machine you already trust. [-]","enrolled": true,- "labels": "Devices / This Device / Your Devices / Recent Access (No access yet) / Last seen / Approve… Deny Rename… Revoke… / Rename Device Rename Cancel / New Computers Confirm",+ "labels": "Machines / This Machine / Your Machines / Recent access (No access yet.) / Last seen / Add machine Not me Rename… Revoke… / Rename Machine Rename Cancel / New machines Add machine","recent": [],"rows": [- "MacBook Pro (this device) | macOS · Enrolled · re-verify in 2 days | seen null | rename,revoke | current | Revoke “MacBook Pro”? / This device will no longer list or reach your machines until you enroll it again."+ "MacBook Pro (this machine) | macOS, Trusted, check again in 2 days | seen null | rename,revoke | current | Revoke “MacBook Pro”? / This machine will no longer see or reach your machines until you trust it again."],- "thisDevice": "enrolled: Enrolled until @1800172800 name=MacBook Pro [-]",+ "thisDevice": "enrolled: Trusted until @1800172800 name=MacBook Pro [-]","unconfirmedMachines": []}},@@ -104,19 +104,19 @@"view": {"activity": [],"approvals": [- "dev_p: Let “Work laptop” list and open your machines? Only approve a device you just signed in on. | Approve “Work laptop”? / A device signed in to your Cua account and asks to reach your machines.",- "dev_o (expired): Re-verify “Old laptop” for another 30 days? | Re-verify “Old laptop”? / It needs one approval to keep reaching your machines."+ "dev_p: Add “Work laptop” to your machines? Only add a machine you just signed in on. | Add “Work laptop”? / A machine signed in to your Cua account and asks to be added.",+ "dev_o (expired): Keep “Old laptop” on your account for another 30 days? | Keep “Old laptop”? / It needs one approval to keep reaching your machines."],"banner": null,"enrolled": true,- "labels": "Devices / This Device / Your Devices / Recent Access (No access yet) / Last seen / Approve… Deny Rename… Revoke… / Rename Device Rename Cancel / New Computers Confirm",+ "labels": "Machines / This Machine / Your Machines / Recent access (No access yet.) / Last seen / Add machine Not me Rename… Revoke… / Rename Machine Rename Cancel / New machines Add machine","recent": [],"rows": [- "MacBook Pro (this device) | macOS · Enrolled · re-verify in 30 days | seen null | rename,revoke | current | Revoke “MacBook Pro”? / This device will no longer list or reach your machines until you enroll it again.",- "Old laptop | Linux · Re-verification due | seen null | approve,rename,revoke | Revoke “Old laptop”? / Old laptop will no longer list or reach your machines. To use it again, enroll it again.",- "Work laptop | Windows · Waiting for approval | seen null | approve,rename,revoke | Revoke “Work laptop”? / Work laptop will no longer list or reach your machines. To use it again, enroll it again."+ "MacBook Pro (this machine) | macOS, Trusted, check again in 30 days | seen null | rename,revoke | current | Revoke “MacBook Pro”? / This machine will no longer see or reach your machines until you trust it again.",+ "Old laptop | Linux, Needs a quick check | seen null | approve,rename,revoke | Revoke “Old laptop”? / Old laptop will no longer see or reach your machines. To use it again, add it again.",+ "Work laptop | Windows, Waiting to be added | seen null | approve,rename,revoke | Revoke “Work laptop”? / Work laptop will no longer see or reach your machines. To use it again, add it again."],- "thisDevice": "enrolled: Enrolled until @1802592000 name=MacBook Pro [-]",+ "thisDevice": "enrolled: Trusted until @1802592000 name=MacBook Pro [-]","unconfirmedMachines": []}},@@ -131,11 +131,11 @@"done": false,"error": null,"options": [- "sign-in: Sign in again / A fresh sign-in enrolls this device right away.",- "approve: Approve from another device / Show a one-time code to approve from an enrolled device."+ "sign-in: Sign in again / A fresh sign-in trusts this machine right away.",+ "approve: Add it from another machine / Show a one-time code to add it from a machine you already trust."],"status": null,- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -150,11 +150,11 @@"done": false,"error": null,"options": [- "sign-in: Sign in again / A fresh sign-in enrolls this device right away.",- "approve: Approve from another device / Show a one-time code to approve from an enrolled device."+ "sign-in: Sign in again / A fresh sign-in trusts this machine right away.",+ "approve: Add it from another machine / Show a one-time code to add it from a machine you already trust."],"status": null,- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -170,7 +170,7 @@"error": null,"options": [],"status": "Finish signing in in your browser…",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -185,8 +185,8 @@"done": false,"error": null,"options": [],- "status": "Registering this device…",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "status": "Registering this machine…",+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -197,12 +197,12 @@"busy": true,"buttons": "- / Cancel","code": "K7QX-M2RP",- "codeHelp": "On an enrolled device, approve it in Cua Spaces or run `cua devices approve K7QX-M2RP`. The code expires in 10 minutes.",+ "codeHelp": "On a machine you already trust, add it in Cua Spaces under Machines, or run `cua devices approve K7QX-M2RP`. The code expires in 10 minutes.","done": false,"error": null,"options": [],- "status": "Waiting for approval…",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "status": "Waiting to be added…",+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -217,8 +217,8 @@"done": true,"error": null,"options": [],- "status": "This device is enrolled.",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "status": "This machine is trusted.",+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -232,11 +232,11 @@"done": false,"error": null,"options": [- "sign-in: Sign in again / A fresh sign-in enrolls this device right away.",- "approve: Approve from another device / Show a one-time code to approve from an enrolled device."+ "sign-in: Sign in again / A fresh sign-in trusts this machine right away.",+ "approve: Add it from another machine / Show a one-time code to add it from a machine you already trust."],"status": null,- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -252,7 +252,7 @@"error": null,"options": [],"status": "Finish signing in in your browser…",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -267,8 +267,8 @@"done": false,"error": null,"options": [],- "status": "Registering this device…",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "status": "Registering this machine…",+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -283,8 +283,8 @@"done": true,"error": null,"options": [],- "status": "This device is enrolled.",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "status": "This machine is trusted.",+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -298,11 +298,11 @@"done": false,"error": null,"options": [- "sign-in: Sign in again / A fresh sign-in enrolls this device right away.",- "approve: Approve from another device / Show a one-time code to approve from an enrolled device."+ "sign-in: Sign in again / A fresh sign-in trusts this machine right away.",+ "approve: Add it from another machine / Show a one-time code to add it from a machine you already trust."],"status": null,- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -317,8 +317,8 @@"done": false,"error": null,"options": [],- "status": "Registering this device…",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "status": "Registering this machine…",+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -334,7 +334,7 @@"error": "the relay is unreachable","options": [],"status": null,- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -349,11 +349,11 @@"done": false,"error": null,"options": [- "sign-in: Sign in again / A fresh sign-in enrolls this device right away.",- "approve: Approve from another device / Show a one-time code to approve from an enrolled device."+ "sign-in: Sign in again / A fresh sign-in trusts this machine right away.",+ "approve: Add it from another machine / Show a one-time code to add it from a machine you already trust."],"status": null,- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -368,8 +368,8 @@"done": false,"error": null,"options": [],- "status": "Registering this device…",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "status": "Registering this machine…",+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -380,12 +380,12 @@"busy": true,"buttons": "- / Cancel","code": "Z9WY-4TPN",- "codeHelp": "On an enrolled device, approve it in Cua Spaces or run `cua devices approve Z9WY-4TPN`. The code expires in 10 minutes.",+ "codeHelp": "On a machine you already trust, add it in Cua Spaces under Machines, or run `cua devices approve Z9WY-4TPN`. The code expires in 10 minutes.","done": false,"error": null,"options": [],- "status": "Waiting for approval…",- "title": "Enroll This Device / Your machines can be reached only from enrolled devices."+ "status": "Waiting to be added…",+ "title": "Trust this machine / Your machines can be reached only from machines you trust."}},{@@ -393,14 +393,14 @@"approve": "dev_p","view": {"busy": false,- "buttons": "Approve / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": false,"code": "Code [XXXX-XXXX] = ","error": null,- "message": "Enter the code Work laptop shows to let it list and open your machines. Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "Enter the code Work laptop shows to let it see and open your machines. Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": null,- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -408,14 +408,14 @@"approve": "dev_p","view": {"busy": false,- "buttons": "Approve / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": false,"code": "Code [XXXX-XXXX] = ","error": null,- "message": "Enter the code Work laptop shows to let it list and open your machines. Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "Enter the code Work laptop shows to let it see and open your machines. Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": null,- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -423,14 +423,14 @@"approve": "dev_p","view": {"busy": false,- "buttons": "Approve / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": false,"code": "Code [XXXX-XXXX] = K7QX","error": null,- "message": "Enter the code Work laptop shows to let it list and open your machines. Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "Enter the code Work laptop shows to let it see and open your machines. Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": null,- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -438,14 +438,14 @@"approve": "dev_p","view": {"busy": false,- "buttons": "Approve / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": true,"code": "Code [XXXX-XXXX] = K7QX-M2RP","error": null,- "message": "Enter the code Work laptop shows to let it list and open your machines. Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "Enter the code Work laptop shows to let it see and open your machines. Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": "code=K7QX-M2RP device=-",- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -453,14 +453,14 @@"approve": "dev_p","view": {"busy": true,- "buttons": "Approve / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": false,"code": "Code [XXXX-XXXX] = K7QX-M2RP","error": null,- "message": "Enter the code Work laptop shows to let it list and open your machines. Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "Enter the code Work laptop shows to let it see and open your machines. Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": "code=K7QX-M2RP device=-",- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -468,14 +468,14 @@"approve": "dev_p","view": {"busy": true,- "buttons": "Approve / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": false,"code": "Code [XXXX-XXXX] = K7QX-M2RP","error": null,- "message": "Enter the code Work laptop shows to let it list and open your machines. Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "Enter the code Work laptop shows to let it see and open your machines. Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": "code=K7QX-M2RP device=-",- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -483,14 +483,14 @@"approve": "dev_p","view": {"busy": false,- "buttons": "Approve / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": true,"code": "Code [XXXX-XXXX] = K7QX-M2RP","error": "authentication was cancelled",- "message": "Enter the code Work laptop shows to let it list and open your machines. Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "Enter the code Work laptop shows to let it see and open your machines. Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": "code=K7QX-M2RP device=-",- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -498,14 +498,14 @@"approve": "dev_p","view": {"busy": false,- "buttons": "Approve / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": true,"code": "Code [XXXX-XXXX] = Z9WY-4TPN","error": null,- "message": "Enter the code Work laptop shows to let it list and open your machines. Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "Enter the code Work laptop shows to let it see and open your machines. Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": "code=Z9WY-4TPN device=-",- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -513,14 +513,14 @@"approve": "dev_p","view": {"busy": true,- "buttons": "Approve / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": false,"code": "Code [XXXX-XXXX] = Z9WY-4TPN","error": null,- "message": "Enter the code Work laptop shows to let it list and open your machines. Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "Enter the code Work laptop shows to let it see and open your machines. Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": "code=Z9WY-4TPN device=-",- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -528,14 +528,14 @@"approve": "dev_p","view": {"busy": false,- "buttons": "Approve by ID / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": true,"code": "Code [XXXX-XXXX] = Z9WY-4TPN","error": "The code expired.",- "message": "The code expired. Approve “Work laptop” by ID instead? Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "The code expired. Add “Work laptop” without it instead? Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": "code=- device=dev_p",- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -543,14 +543,14 @@"approve": "dev_p","view": {"busy": true,- "buttons": "Approve by ID / Deny (revokes)",+ "buttons": "Add machine / Not me (revokes)","canApprove": false,"code": "Code [XXXX-XXXX] = Z9WY-4TPN","error": null,- "message": "The code expired. Approve “Work laptop” by ID instead? Only approve a device you just signed in on.",- "presence": "approve “Work laptop” for your Cua account",+ "message": "The code expired. Add “Work laptop” without it instead? Only add a machine you just signed in on.",+ "presence": "add “Work laptop” to your Cua account","request": "code=- device=dev_p",- "title": "Approve “Work laptop”?"+ "title": "Add “Work laptop”?"}},{@@ -558,14 +558,14 @@"approve": "dev_o","view": {"busy": false,- "buttons": "Approve / Not Now",+ "buttons": "Keep machine / Not now","canApprove": true,"code": null,"error": null,"message": "Old laptop needs one approval to keep reaching your machines for another 30 days.",- "presence": "approve “Old laptop” for your Cua account",+ "presence": "add “Old laptop” to your Cua account","request": "code=- device=dev_o",- "title": "Re-verify “Old laptop”?"+ "title": "Keep “Old laptop”?"}},{@@ -573,14 +573,14 @@"approve": "dev_o","view": {"busy": true,- "buttons": "Approve / Not Now",+ "buttons": "Keep machine / Not now","canApprove": false,"code": null,"error": null,"message": "Old laptop needs one approval to keep reaching your machines for another 30 days.",- "presence": "approve “Old laptop” for your Cua account",+ "presence": "add “Old laptop” to your Cua account","request": "code=- device=dev_o",- "title": "Re-verify “Old laptop”?"+ "title": "Keep “Old laptop”?"}}]diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.jsonindex 33e4bf3bd1..44cb52af4e 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json@@ -828,11 +828,11 @@"omarchy Omarchy: 1.7 GB download · about 3 min the first time"],"footnote": null,- "note": "A separate computer on this computer. Pick a system to start it.",+ "note": "A separate computer on this machine. Pick a system to start it.","phase": "choose","title": "Make a first Space"},- "lede": "Spaces run on this computer, away from your files and your mouse.",+ "lede": "Spaces run on this machine, away from your files and your mouse.","primary": "done:Done","prompt": null,"status": null,diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/machines.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/machines.jsonindex 0c86d58f15..86b73ca723 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/machines.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/machines.json@@ -78,13 +78,8 @@"● Ada's MacBook Pro [This Mac] — Desktop and 2 Spaces","● cua's Mac Studio — Desktop and 1 Space","○ Cua BYOC tests — Offline",- "○ Adas-MacBook-Pro-2.local — Not sharing"- ]- },- {- "group": "Your devices",- "rows": [- "● Ana's laptop — Signed-in device, not shared"+ "○ Adas-MacBook-Pro-2.local — Not sharing",+ "● Ana's laptop — Signed in, not sharing"]},{@@ -143,14 +138,10 @@"Remove from account -> b695 (disabled: It’s online. Remove it on that Mac, or here once it’s offline.)"],[- "Ana's laptop — Online (rename: device)",- "Let other machines create Spaces here: off (read-only)",- "Let other machines control this desktop: off (read-only)",- "note: Change this on that PC.",- "spaces: No Spaces yet.",- "New Space here on host:dev_lap (disabled: It doesn’t let other machines create Spaces. Turn on “Let other machines create Spaces here” in Settings on that PC.)",+ "Ana's laptop — Signed in, not sharing (rename: device)",+ " on host:dev_lap (disabled: It is signed in, but it does not share this machine.)","details: OS: Windows",- "Remove from account -> dev_lap"+ "Revoke -> dev_lap"],["mac-mini-staging — Offline (rename: machine)",@@ -180,15 +171,15 @@{"group": "Your machines","rows": [- "○ Ada's MacBook Pro [This Mac] — Not sharing"+ "○ Ada's MacBook Pro [This Mac] — Not sharing",+ "○ Cua BYOC tests — Signed in, not sharing",+ "● Ana's laptop — Signed in, not sharing"]},{- "group": "Your devices",+ "group": "Offline for 30+ days (1) (collapsed) · Remove old machines","rows": [- "○ Cua BYOC tests — Signed-in device, not shared",- "○ mac-mini-staging — Signed-in device, not shared",- "● Ana's laptop — Signed-in device, not shared"+ "○ mac-mini-staging — Signed in, not sharing"]}],@@ -203,34 +194,22 @@"Remove from account -> host setup"],[- "Cua BYOC tests — Offline (rename: device)",- "notice: This machine is offline. Open Cua Spaces on it to use it.",- "Let other machines create Spaces here: off (read-only)",- "Let other machines control this desktop: off (read-only)",- "spaces: No Spaces. The machine is offline.",- "New Space here on host:dev_byoc (disabled: It’s offline.)",+ "Cua BYOC tests — Signed in, not sharing (rename: device)",+ " on host:dev_byoc (disabled: It is signed in, but it does not share this machine.)","details: Last seen: 9 days ago; OS: macOS",- "Remove from account -> dev_byoc"+ "Revoke -> dev_byoc"],[- "mac-mini-staging — Offline (rename: device)",- "notice: This machine is offline. Open Cua Spaces on it to use it.",- "Let other machines create Spaces here: off (read-only)",- "Let other machines control this desktop: off (read-only)",- "spaces: No Spaces. The machine is offline.",- "New Space here on host:dev_old1 (disabled: It’s offline.)",- "details: Last seen: 41 days ago; OS: macOS",- "Remove from account -> dev_old1"+ "Ana's laptop — Signed in, not sharing (rename: device)",+ " on host:dev_lap (disabled: It is signed in, but it does not share this machine.)",+ "details: OS: Windows",+ "Revoke -> dev_lap"],[- "Ana's laptop — Online (rename: device)",- "Let other machines create Spaces here: off (read-only)",- "Let other machines control this desktop: off (read-only)",- "note: Change this on that PC.",- "spaces: No Spaces yet.",- "New Space here on host:dev_lap (disabled: It doesn’t let other machines create Spaces. Turn on “Let other machines create Spaces here” in Settings on that PC.)",- "details: OS: Windows",- "Remove from account -> dev_lap"+ "mac-mini-staging — Signed in, not sharing (rename: device)",+ " on host:dev_old1 (disabled: It is signed in, but it does not share this machine.)",+ "details: Last seen: 41 days ago; OS: macOS",+ "Revoke -> dev_old1"]],"summary": "4 machines, 1 online",@@ -265,13 +244,8 @@"● Ada's MacBook Pro [This Mac] — Desktop and 2 Spaces [fail]","● cua's Mac Studio — Desktop and 1 Space [warn]","○ Cua BYOC tests — Offline",- "○ Adas-MacBook-Pro-2.local — Not sharing"- ]- },- {- "group": "Your devices",- "rows": [- "● Ana's laptop — Signed-in device, not shared"+ "○ Adas-MacBook-Pro-2.local — Not sharing",+ "● Ana's laptop — Signed in, not sharing"]},{@@ -334,14 +308,10 @@"Remove from account -> b695 (disabled: It’s online. Remove it on that Mac, or here once it’s offline.)"],[- "Ana's laptop — Online (rename: device)",- "Let other machines create Spaces here: off (read-only)",- "Let other machines control this desktop: off (read-only)",- "note: Change this on that PC.",- "spaces: No Spaces yet.",- "New Space here on host:dev_lap (disabled: It doesn’t let other machines create Spaces. Turn on “Let other machines create Spaces here” in Settings on that PC.)",+ "Ana's laptop — Signed in, not sharing (rename: device)",+ " on host:dev_lap (disabled: It is signed in, but it does not share this machine.)","details: OS: Windows",- "Remove from account -> dev_lap"+ "Revoke -> dev_lap"],["mac-mini-staging — Offline (rename: machine)",@@ -374,13 +344,8 @@"● Ada's MacBook Pro [This Mac] — Desktop and 2 Spaces [fail]","● cua's Mac Studio — Desktop and 1 Space [warn]","○ Cua BYOC tests — Offline",- "○ Adas-MacBook-Pro-2.local — Not sharing"- ]- },- {- "group": "Your devices",- "rows": [- "● Ana's laptop — Signed-in device, not shared"+ "○ Adas-MacBook-Pro-2.local — Not sharing",+ "● Ana's laptop — Signed in, not sharing"]},{@@ -443,14 +408,10 @@"Remove from account -> b695 (disabled: It’s online. Remove it on that Mac, or here once it’s offline.)"],[- "Ana's laptop — Online (rename: device)",- "Let other machines create Spaces here: off (read-only)",- "Let other machines control this desktop: off (read-only)",- "note: Change this on that PC.",- "spaces: No Spaces yet.",- "New Space here on host:dev_lap (disabled: It doesn’t let other machines create Spaces. Turn on “Let other machines create Spaces here” in Settings on that PC.)",+ "Ana's laptop — Signed in, not sharing (rename: device)",+ " on host:dev_lap (disabled: It is signed in, but it does not share this machine.)","details: OS: Windows",- "Remove from account -> dev_lap"+ "Revoke -> dev_lap"],["mac-mini-staging — Offline (rename: machine)",@@ -483,13 +444,8 @@"● Ada's MacBook Pro [This Mac] — Desktop and 2 Spaces [fail]","● cua's Mac Studio — Desktop and 1 Space [warn]","○ Cua BYOC tests — Offline",- "○ Adas-MacBook-Pro-2.local — Not sharing"- ]- },- {- "group": "Your devices",- "rows": [- "● Ana's laptop — Signed-in device, not shared"+ "○ Adas-MacBook-Pro-2.local — Not sharing",+ "● Ana's laptop — Signed in, not sharing"]},{@@ -552,14 +508,10 @@"Remove from account -> b695 (disabled: It’s online. Remove it on that Mac, or here once it’s offline.)"],[- "Ana's laptop — Online (rename: device)",- "Let other machines create Spaces here: off (read-only)",- "Let other machines control this desktop: off (read-only)",- "note: Change this on that PC.",- "spaces: No Spaces yet.",- "New Space here on host:dev_lap (disabled: It doesn’t let other machines create Spaces. Turn on “Let other machines create Spaces here” in Settings on that PC.)",+ "Ana's laptop — Signed in, not sharing (rename: device)",+ " on host:dev_lap (disabled: It is signed in, but it does not share this machine.)","details: OS: Windows",- "Remove from account -> dev_lap"+ "Revoke -> dev_lap"],["mac-mini-staging — Offline (rename: machine)",@@ -590,7 +542,6 @@"order": ["clouds","yours",- "devices","old","team"],@@ -639,13 +590,8 @@"● Ada's MacBook Pro [This Mac] — Desktop and 2 Spaces [fail]","● cua's Mac Studio — Desktop and 1 Space [warn]","○ Cua BYOC tests — Offline",- "○ Adas-MacBook-Pro-2.local — Not sharing"- ]- },- {- "group": "Your devices",- "rows": [- "● Ana's laptop — Signed-in device, not shared"+ "○ Adas-MacBook-Pro-2.local — Not sharing",+ "● Ana's laptop — Signed in, not sharing"]},{@@ -708,14 +654,10 @@"Remove from account -> b695 (disabled: It’s online. Remove it on that Mac, or here once it’s offline.)"],[- "Ana's laptop — Online (rename: device)",- "Let other machines create Spaces here: off (read-only)",- "Let other machines control this desktop: off (read-only)",- "note: Change this on that PC.",- "spaces: No Spaces yet.",- "New Space here on host:dev_lap (disabled: It doesn’t let other machines create Spaces. Turn on “Let other machines create Spaces here” in Settings on that PC.)",+ "Ana's laptop — Signed in, not sharing (rename: device)",+ " on host:dev_lap (disabled: It is signed in, but it does not share this machine.)","details: OS: Windows",- "Remove from account -> dev_lap"+ "Revoke -> dev_lap"],["mac-mini-staging — Offline (rename: machine)",@@ -746,7 +688,6 @@"order": ["clouds","yours",- "devices","old","team"],@@ -796,13 +737,8 @@"● Ada's MacBook Pro [This Mac] — Desktop and 2 Spaces [fail]","● cua's Mac Studio — Desktop and 1 Space [warn]","○ Cua BYOC tests — Offline",- "○ Adas-MacBook-Pro-2.local — Not sharing"- ]- },- {- "group": "Your devices",- "rows": [- "● Ana's laptop — Signed-in device, not shared"+ "○ Adas-MacBook-Pro-2.local — Not sharing",+ "● Ana's laptop — Signed in, not sharing"]},{@@ -865,14 +801,10 @@"Remove from account -> b695 (disabled: It’s online. Remove it on that Mac, or here once it’s offline.)"],[- "Ana's laptop — Online (rename: device)",- "Let other machines create Spaces here: off (read-only)",- "Let other machines control this desktop: off (read-only)",- "note: Change this on that PC.",- "spaces: No Spaces yet.",- "New Space here on host:dev_lap (disabled: It doesn’t let other machines create Spaces. Turn on “Let other machines create Spaces here” in Settings on that PC.)",+ "Ana's laptop — Signed in, not sharing (rename: device)",+ " on host:dev_lap (disabled: It is signed in, but it does not share this machine.)","details: OS: Windows",- "Remove from account -> dev_lap"+ "Revoke -> dev_lap"],["mac-mini-staging — Offline (rename: machine)",diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/tips.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/tips.jsonindex 85ea6f1d6b..daa6811acf 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/tips.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/tips.json@@ -121,7 +121,7 @@],"code": "cua create --on auto","openIn": null,- "tip": "on-auto (sidebar): New Spaces can go to whichever computer has room."+ "tip": "on-auto (sidebar): New Spaces can go to whichever machine has room."},"state": "off=false done=try-agent,power","step": "powered from a tile",@@ -157,7 +157,7 @@],"code": "cua create --on auto","openIn": null,- "tip": "on-auto (sidebar): New Spaces can go to whichever computer has room."+ "tip": "on-auto (sidebar): New Spaces can go to whichever machine has room."},"state": "off=false done=try-agent,power,bulk-select","step": "a bulk delete",@@ -193,7 +193,7 @@],"code": "cua create --on auto","openIn": null,- "tip": "on-auto (sidebar): New Spaces can go to whichever computer has room."+ "tip": "on-auto (sidebar): New Spaces can go to whichever machine has room."},"state": "off=false done=try-agent,power,bulk-select,share","step": "share closed for now",@@ -273,7 +273,7 @@],"code": "cua create --on auto","openIn": null,- "tip": "on-auto (sidebar): New Spaces can go to whichever computer has room."+ "tip": "on-auto (sidebar): New Spaces can go to whichever machine has room."},"state": "off=false done=","step": "back on, on a page with no tip",@@ -287,7 +287,7 @@],"code": "cua create --on auto","openIn": null,- "tip": "on-auto (sidebar): New Spaces can go to whichever computer has room."+ "tip": "on-auto (sidebar): New Spaces can go to whichever machine has room."}},{diff --git a/libs/cua/crates/cua-spaces-app-core/src/agent_prompts.rs b/libs/cua/crates/cua-spaces-app-core/src/agent_prompts.rsindex 72736a103f..7971ae72f3 100644--- a/libs/cua/crates/cua-spaces-app-core/src/agent_prompts.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/agent_prompts.rs@@ -22,7 +22,7 @@ pub fn add_computer_prompt(code: &str, url: Option<&str>) -> String {let link = url.map(str::to_string).unwrap_or_else(|| format!("https://cua.ai/add/{code}"));- format!("Add this computer to my Cua Spaces: {link}")+ format!("Add this machine to my Cua Spaces: {link}")}/// "Connect a cloud". With a cloud (`AWS`) it names the cloud, and the@@ -91,14 +91,14 @@ mod tests {fn the_words_are_the_approved_ones() {assert_eq!(add_computer_prompt("K7QM-4XPB-2RHD", None),- "Add this computer to my Cua Spaces: https://cua.ai/add/K7QM-4XPB-2RHD"+ "Add this machine to my Cua Spaces: https://cua.ai/add/K7QM-4XPB-2RHD");assert_eq!(add_computer_prompt("K7QM-4XPB-2RHD",Some("https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Fr.example")),- "Add this computer to my Cua Spaces: https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Fr.example"+ "Add this machine to my Cua Spaces: https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Fr.example");assert_eq!(connect_cloud_prompt(None, None, None),diff --git a/libs/cua/crates/cua-spaces-app-core/src/cloud_page.rs b/libs/cua/crates/cua-spaces-app-core/src/cloud_page.rsindex 0f64c3d63f..7391f05a45 100644--- a/libs/cua/crates/cua-spaces-app-core/src/cloud_page.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/cloud_page.rs@@ -696,7 +696,7 @@ fn settings_of(c: &CloudInput) -> Vec<CloudSettingRow> {rows.push(CloudSettingRow {id: "access".into(),label: "Access".into(),- help: "The AWS CLI's sign-in on this computer".into(),+ help: "The AWS CLI's sign-in on this machine".into(),value: String::new(),});}@@ -1405,7 +1405,7 @@ mod tests {assert!(p.issues.is_empty());assert_eq!(p.status, "Connected");let access = p.settings.iter().find(|r| r.id == "access").unwrap();- assert_eq!(access.help, "The AWS CLI's sign-in on this computer");+ assert_eq!(access.help, "The AWS CLI's sign-in on this machine");// An OIDC link, or a CLI link with no suggestion, offers nothing.assert!(view(&input(aws())).pages[0].switch_auth.is_none());c.suggest_auth.clear();@@ -1419,7 +1419,7 @@ mod tests {let mut c = aws();c.status = "failed".into();c.issue =- "AWS was disconnected on another device; 2 machines this computer made may still run."+ "AWS was disconnected on another device; 2 machines this machine made may still run.".into();let v = view(&input(c));let p = v.pages[0].clone();diff --git a/libs/cua/crates/cua-spaces-app-core/src/cloud_sheet.rs b/libs/cua/crates/cua-spaces-app-core/src/cloud_sheet.rsindex a97ebb8363..38dd17d051 100644--- a/libs/cua/crates/cua-spaces-app-core/src/cloud_sheet.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/cloud_sheet.rs@@ -855,7 +855,7 @@ pub fn cloud_sheet_view(input: &CloudSheetInput, state: &CloudSheetState) -> Clokind: "secret".into(),value: String::new(),placeholder: if found(input, id) {- "Using the token on this computer".into()+ "Using the token on this machine".into()} else {"Project token (Read & Write)".into()},@@ -895,14 +895,14 @@ pub fn cloud_sheet_view(input: &CloudSheetInput, state: &CloudSheetState) -> Clo.to_string()}Kind::Oidc => "Cua signs in to AWS on its own each time; there's no key to copy or store.".to_string(),- Kind::Token => "Hetzner has no OIDC, so it takes an API token. Cua keeps it on this computer and uses it only for your Spaces.".to_string(),- Kind::Local => "Modal uses the sign-in on this computer. Cua keeps no copy of it.".to_string(),+ Kind::Token => "Hetzner has no OIDC, so it takes an API token. Cua keeps it on this machine and uses it only for your Spaces.".to_string(),+ Kind::Local => "Modal uses the sign-in on this machine. Cua keeps no copy of it.".to_string(),Kind::Soon => format!("Cua signs in to {name} on its own each time. This arrives in a later update."),};let note = match kind {Kind::Token => "Revoke it any time in the Hetzner console.".to_string(),Kind::Local if !found(input, id) => {- "No Modal sign-in on this computer. Run `modal token new`, then come back.".to_string()+ "No Modal sign-in on this machine. Run `modal token new`, then come back.".to_string()}Kind::Soon => String::new(),_ => SAFETY_NOTE.to_string(),diff --git a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs b/libs/cua/crates/cua-spaces-app-core/src/connectors.rsindex d6e8a0f2dc..7b278961a6 100644--- a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/connectors.rs@@ -685,14 +685,19 @@ fn app_row(input: &ConnectorsInput, a: &ConnectorAppInput) -> ConnectorAppRow {)} else if a.configured || !a.installed {// Cua's tools are in it (or it is not on this machine): what it still needs.+ let reconnect = app_expired(input, &a.agent);("not-connected",- if app_expired(input, &a.agent) {- Some("The sign-in expired. Reconnect.".to_string())+ if reconnect {+ Some("Needs reconnect.".to_string())} else {needs},- Some(button("connect", "Connect", true)),+ Some(button(+ "connect",+ if reconnect { "Reconnect" } else { "Connect" },+ true,+ )),)} else {(@@ -745,7 +750,7 @@ fn provider_row(input: &ConnectorsInput, p: &Provider, can_edit: bool) -> Connec} else if provider_expired(input, p) {("not-connected",- "Expired, reconnect".into(),+ "Needs reconnect".into(),button("connect", "Reconnect", can_edit),)} else {@@ -1534,7 +1539,7 @@ mod tests {}#[test]- fn an_expired_sign_in_is_not_connected_and_says_reconnect() {+ fn a_sign_in_that_no_longer_works_is_not_connected_and_says_reconnect() {let mut i = input();i.apps[0].configured = true;let mut k = key("CLAUDE_CODE_OAUTH_TOKEN", "AAAA");@@ -1544,10 +1549,15 @@ mod tests {let v = view(&i);let p = v.providers.iter().find(|p| p.id == "anthropic").unwrap();assert_eq!(p.state, "not-connected");- assert_eq!(p.status, "Expired, reconnect");+ assert_eq!(p.status, "Needs reconnect");assert_eq!(p.button.label, "Reconnect");let a = v.apps.iter().find(|a| a.agent == "claude-code").unwrap();- assert_eq!(a.line.as_deref(), Some("The sign-in expired. Reconnect."));+ assert_eq!(a.line.as_deref(), Some("Needs reconnect."));+ // The app's row offers Reconnect, not a first Connect.+ assert_eq!(+ a.button.as_ref().map(|b| b.label.as_str()),+ Some("Reconnect")+ );}#[test]diff --git a/libs/cua/crates/cua-spaces-app-core/src/devices.rs b/libs/cua/crates/cua-spaces-app-core/src/devices.rsindex 5e3c2f74c3..bfba3ea9f1 100644--- a/libs/cua/crates/cua-spaces-app-core/src/devices.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/devices.rs@@ -395,24 +395,24 @@ pub fn activity_text(.map(|m| machines.get(m).map(String::as_str).unwrap_or(m));let subject = e.subject.as_deref().unwrap_or("");let by = |who: Option<&str>| who.map(|d| format!(" from {d}")).unwrap_or_default();- let target = device.unwrap_or("A device");+ let target = device.unwrap_or("A machine");match e.kind.as_str() {"machine_access" if subject == "unenrolled device" => format!(- "An unenrolled device opened {}",- machine.unwrap_or("a computer")+ "An untrusted machine opened {}",+ machine.unwrap_or("a machine")),- "machine_access" => format!("{target} opened {}", machine.unwrap_or("a computer")),- "shared_access" => format!("{subject} opened {}", machine.unwrap_or("a computer")),- "unenrolled_access" => "An unenrolled device used your account".into(),+ "machine_access" => format!("{target} opened {}", machine.unwrap_or("a machine")),+ "shared_access" => format!("{subject} opened {}", machine.unwrap_or("a machine")),+ "unenrolled_access" => "An untrusted machine used your account".into(),"device_registered" => format!("{target} asked to join"),"device_enrolled" if subject == "bootstrap:grace" => {- format!("{target} was enrolled during the grace period")+ format!("{target} was added during the grace period")}"device_enrolled" if subject.starts_with("bootstrap:") => {- format!("{target} was enrolled by a fresh sign-in")+ format!("{target} was added by a fresh sign-in")}"device_rekeyed" => format!(- "{target} replaced {} on the same computer",+ "{target} replaced {} on the same machine",name_or_id(devices, subject)),"device_enrolled" => format!(@@ -424,21 +424,21 @@ pub fn activity_text("device_revoked" => format!("{} was revoked{}", name_or_id(devices, subject), by(device)),"share_added" => format!("{} was shared with {subject}{}",- machine.unwrap_or("A computer"),+ machine.unwrap_or("A machine"),by(device)),"share_removed" => format!("{} is no longer shared with {subject}{}",- machine.unwrap_or("A computer"),+ machine.unwrap_or("A machine"),by(device)),- "share_left" => format!("{subject} left {}", machine.unwrap_or("a computer")),- "machine_left" => format!("You left {}", machine.unwrap_or("a computer")),- "sharing_stopped" => format!("{} stopped sharing", machine.unwrap_or("A computer")),- "sharing_started" => format!("{} started sharing", machine.unwrap_or("A computer")),- "machine_registered" => format!("{} was added", machine.unwrap_or("A computer")),- "machine_reregistered" => format!("{} was set up again", machine.unwrap_or("A computer")),- "machine_removed" => format!("{} was removed", machine.unwrap_or("A computer")),+ "share_left" => format!("{subject} left {}", machine.unwrap_or("a machine")),+ "machine_left" => format!("You left {}", machine.unwrap_or("a machine")),+ "sharing_stopped" => format!("{} stopped sharing", machine.unwrap_or("A machine")),+ "sharing_started" => format!("{} started sharing", machine.unwrap_or("A machine")),+ "machine_registered" => format!("{} was added", machine.unwrap_or("A machine")),+ "machine_reregistered" => format!("{} was set up again", machine.unwrap_or("A machine")),+ "machine_removed" => format!("{} was removed", machine.unwrap_or("A machine")),other => other.replace('_', " "),}}@@ -454,35 +454,34 @@ pub fn is_access(kind: &str) -> bool {/// The page's words.pub fn labels() -> DevicesLabels {DevicesLabels {- title: "Devices".into(),- this_device: "This Device".into(),- devices: "Your Devices".into(),- recent: "Recent Access".into(),- recent_empty: "No access yet".into(),+ title: "Machines".into(),+ this_device: "This Machine".into(),+ devices: "Your Machines".into(),+ recent: "Recent access".into(),+ recent_empty: "No access yet.".into(),last_seen: "Last seen".into(),- approve: "Approve\u{2026}".into(),- deny: "Deny".into(),+ approve: "Add machine".into(),+ deny: "Not me".into(),rename: "Rename\u{2026}".into(),revoke: "Revoke\u{2026}".into(),- rename_title: "Rename Device".into(),+ rename_title: "Rename Machine".into(),rename_confirm: "Rename".into(),cancel: "Cancel".into(),- signed_out: "Sign in to Cua to see the devices that can reach your machines.".into(),- new_machines: "New Computers".into(),- confirm_machine: "Confirm".into(),+ signed_out: "Sign in to Cua to see your machines.".into(),+ new_machines: "New machines".into(),+ confirm_machine: "Add machine".into(),}}/// Asked before confirming a new machine is really the user's (S5).fn confirm_machine_confirm(name: &str) -> DeviceConfirm {DeviceConfirm {- title: format!("Confirm \u{201c}{name}\u{201d}?"),+ title: format!("Add \u{201c}{name}\u{201d}?"),message: format!(- "{name} registered to your account without proof it was you: an enrolled \- device's signature or a sign-in with a second factor. Confirm it only if you \- recognize it."+ "{name} registered to your account without proof it was you. Add it only if \+ you recognize it."),- confirm_label: "Confirm".into(),+ confirm_label: "Add machine".into(),cancel_label: "Cancel".into(),}}@@ -504,11 +503,11 @@ fn revoke_confirm(name: &str, this: bool) -> DeviceConfirm {DeviceConfirm {title: format!("Revoke \u{201c}{name}\u{201d}?"),message: if this {- "This device will no longer list or reach your machines until you enroll it again."+ "This machine will no longer see or reach your machines until you trust it again.".into()} else {format!(- "{name} will no longer list or reach your machines. To use it again, enroll it again."+ "{name} will no longer see or reach your machines. To use it again, add it again.")},confirm_label: "Revoke".into(),@@ -516,25 +515,23 @@ fn revoke_confirm(name: &str, this: bool) -> DeviceConfirm {}}-const ENROLL_LABEL: &str = "Enroll\u{2026}";+const ENROLL_LABEL: &str = "Trust this machine";fn this_device(current: Option<&DeviceInput>, input: &DevicesInput, now: u64) -> ThisDevice {let name = current.map(|d| d.name.clone()).filter(|n| !n.is_empty());let (kind, title, at) = match current.map(|d| (d.state.as_str(), d.enrolled_until)) {- Some(("enrolled", Some(until))) => {- (EnrollmentKind::Enrolled, "Enrolled until", Some(until))- }- Some(("enrolled", None)) => (EnrollmentKind::Enrolled, "Enrolled", None),- Some(("pending", _)) => (EnrollmentKind::Waiting, "Waiting for approval", None),- Some(("expired", _)) => (EnrollmentKind::Due, "Re-verification due", None),+ Some(("enrolled", Some(until))) => (EnrollmentKind::Enrolled, "Trusted until", Some(until)),+ Some(("enrolled", None)) => (EnrollmentKind::Enrolled, "Trusted", None),+ Some(("pending", _)) => (EnrollmentKind::Waiting, "Waiting to be added", None),+ Some(("expired", _)) => (EnrollmentKind::Due, "Needs a quick check", None),Some(("revoked", _)) => (EnrollmentKind::Revoked, "Revoked", None),_ => match input.enforce_after {Some(t) if t > now => (EnrollmentKind::Grace,- "Needs enrollment \u{b7} grace ends",+ "Not trusted yet, grace ends",Some(t),),- _ => (EnrollmentKind::NeedsEnrollment, "Needs enrollment", None),+ _ => (EnrollmentKind::NeedsEnrollment, "Not trusted yet", None),},};ThisDevice {@@ -564,7 +561,7 @@ pub fn devices_view(input: &DevicesInput, now: u64) -> DevicesView {Some(DeviceBanner {tone: BannerTone::Warning,text: format!(- "Re-verify this device within {}: sign in again, or approve it from another enrolled device.",+ "Check this machine within {}: sign in again, or add it from a machine you already trust.",days(until.saturating_sub(now))),action: None,@@ -574,11 +571,11 @@ pub fn devices_view(input: &DevicesInput, now: u64) -> DevicesView {Some(("enrolled", _)) => None,Some(("expired", _)) => Some(enroll(BannerTone::Critical,- "Re-verification is due: sign in again, or approve this device from another enrolled device.".into(),+ "It needs a quick check: sign in again, or add this machine from a machine you already trust.".into(),)),Some(("revoked", _)) => Some(enroll(BannerTone::Critical,- "This device was revoked. Enroll it again to reach your machines.".into(),+ "This machine was revoked. Trust it again to reach your machines.".into(),)),// Signing in again enrolls it at once: the banner offers that// before the code.@@ -586,9 +583,9 @@ pub fn devices_view(input: &DevicesInput, now: u64) -> DevicesView {BannerTone::Warning,match &input.pending_code {Some(code) => format!(- "Sign in again to enroll this device, or approve it from an enrolled device with the code {code}."+ "Sign in again to trust this machine, or add it from a machine you already trust with the code {code}."),- None => "Sign in again to enroll this device, or approve it from an enrolled device.".into(),+ None => "Sign in again to trust this machine, or add it from a machine you already trust.".into(),},)),_ => Some(enroll(@@ -598,10 +595,10 @@ pub fn devices_view(input: &DevicesInput, now: u64) -> DevicesView {},match input.enforce_after {Some(t) if t > now => format!(- "Enroll this device within {} to keep reaching your machines.",+ "Trust this machine within {} to keep reaching your machines.",days(t - now)),- _ => "Enroll this device to reach your machines.".into(),+ _ => "Trust this machine to reach your machines.".into(),},)),};@@ -618,11 +615,11 @@ pub fn devices_view(input: &DevicesInput, now: u64) -> DevicesView {let this = current.is_some_and(|c| c.id == d.id);let subtitle = match d.state.as_str() {"enrolled" => match d.enrolled_until {- Some(u) if u > now => format!("Enrolled \u{b7} re-verify in {}", days(u - now)),- _ => "Enrolled".into(),+ Some(u) if u > now => format!("Trusted, check again in {}", days(u - now)),+ _ => "Trusted".into(),},- "pending" => "Waiting for approval".into(),- "expired" => "Re-verification due".into(),+ "pending" => "Waiting to be added".into(),+ "expired" => "Needs a quick check".into(),"revoked" => "Revoked".into(),other => other.into(),};@@ -638,7 +635,7 @@ pub fn devices_view(input: &DevicesInput, now: u64) -> DevicesView {let detail = if platform.is_empty() {subtitle.clone()} else {- format!("{platform} \u{b7} {subtitle}")+ format!("{platform}, {subtitle}")};let display = if d.name.is_empty() {d.id.as_str()@@ -648,7 +645,7 @@ pub fn devices_view(input: &DevicesInput, now: u64) -> DevicesView {DeviceRow {id: d.id.clone(),title: if this {- format!("{display} (this device)")+ format!("{display} (this machine)")} else {display.to_string()},@@ -677,22 +674,22 @@ pub fn devices_view(input: &DevicesInput, now: u64) -> DevicesView {ApprovalPrompt {device_id: d.id.clone(),text: if expired {- format!("Re-verify \u{201c}{name}\u{201d} for another 30 days?")+ format!("Keep \u{201c}{name}\u{201d} on your account for another 30 days?")} else {format!(- "Let \u{201c}{name}\u{201d} list and open your machines? Only approve a device you just signed in on."+ "Add \u{201c}{name}\u{201d} to your machines? Only add a machine you just signed in on.")},requires_presence: true,notify_title: if expired {- format!("Re-verify \u{201c}{name}\u{201d}?")+ format!("Keep \u{201c}{name}\u{201d}?")} else {- format!("Approve \u{201c}{name}\u{201d}?")+ format!("Add \u{201c}{name}\u{201d}?")},notify_body: if expired {"It needs one approval to keep reaching your machines.".into()} else {- "A device signed in to your Cua account and asks to reach your machines."+ "A machine signed in to your Cua account and asks to be added.".into()},name,@@ -774,9 +771,9 @@ pub struct MachineAccessNotice {/// "Enroll This Mac…": the notice's action for a device that never/// enrolled, waits for approval or was revoked.-pub const ENROLL_THIS_MAC_LABEL: &str = "Enroll This Mac\u{2026}";+pub const ENROLL_THIS_MAC_LABEL: &str = "Trust this Mac";/// "Re-verify This Mac…": the notice's action once enrollment expired.-pub const REVERIFY_THIS_MAC_LABEL: &str = "Re-verify This Mac\u{2026}";+pub const REVERIFY_THIS_MAC_LABEL: &str = "Check this Mac";/// The notice for this device's enrollment `kind`: `None` while it may/// open the account's machines (enrolled, or still in the grace period).@@ -794,28 +791,28 @@ pub fn machine_access_notice(match kind {EnrollmentKind::Enrolled | EnrollmentKind::Grace => None,EnrollmentKind::NeedsEnrollment => Some(notice(- "Not enrolled",- "Enroll this Mac to connect to your other machines.".into(),+ "Not trusted yet",+ "Trust this Mac to connect to your other machines.".into(),ENROLL_THIS_MAC_LABEL,)),EnrollmentKind::Waiting => Some(notice(- "Waiting for approval",+ "Waiting to be added",match pending_code.map(str::trim).filter(|c| !c.is_empty()) {Some(code) => format!(- "Waiting for approval. On an enrolled device, approve this Mac with the code {code}."+ "Waiting to be added. On a machine you already trust, add this Mac with the code {code}."),- None => "Waiting for approval. Approve this Mac in Settings \u{203a} Devices on an enrolled device.".into(),+ None => "Waiting to be added. Add this Mac from Machines on a machine you already trust.".into(),},ENROLL_THIS_MAC_LABEL,)),EnrollmentKind::Due => Some(notice(- "Re-verification due",- "This Mac\u{2019}s access expired. Re-verify it to connect to your other machines.".into(),+ "Needs a quick check",+ "This Mac\u{2019}s access expired. Check it again to connect to your other machines.".into(),REVERIFY_THIS_MAC_LABEL,)),EnrollmentKind::Revoked => Some(notice("Revoked",- "This Mac was revoked. Enroll it again to connect to your other machines.".into(),+ "This Mac was revoked. Trust it again to connect to your other machines.".into(),ENROLL_THIS_MAC_LABEL,)),}@@ -996,12 +993,12 @@ pub fn enroll_view(state: &EnrollState) -> EnrollView {EnrollOption {method: EnrollMethod::SignIn,title: "Sign in again".into(),- detail: "A fresh sign-in enrolls this device right away.".into(),+ detail: "A fresh sign-in trusts this machine right away.".into(),},EnrollOption {method: EnrollMethod::Approve,- title: "Approve from another device".into(),- detail: "Show a one-time code to approve from an enrolled device.".into(),+ title: "Add it from another machine".into(),+ detail: "Show a one-time code to add it from a machine you already trust.".into(),},]} else {@@ -1009,19 +1006,19 @@ pub fn enroll_view(state: &EnrollState) -> EnrollView {};let (status, busy) = match state.phase {EnrollPhase::SigningIn => (Some("Finish signing in in your browser\u{2026}"), true),- EnrollPhase::Registering => (Some("Registering this device\u{2026}"), true),- EnrollPhase::Waiting => (Some("Waiting for approval\u{2026}"), true),- EnrollPhase::Enrolled => (Some("This device is enrolled."), false),+ EnrollPhase::Registering => (Some("Registering this machine\u{2026}"), true),+ EnrollPhase::Waiting => (Some("Waiting to be added\u{2026}"), true),+ EnrollPhase::Enrolled => (Some("This machine is trusted."), false),EnrollPhase::Choose | EnrollPhase::Failed => (None, false),};EnrollView {- title: "Enroll This Device".into(),- lede: "Your machines can be reached only from enrolled devices.".into(),+ title: "Trust this machine".into(),+ lede: "Your machines can be reached only from machines you trust.".into(),options,code: state.code.clone(),code_help: state.code.as_ref().map(|code| {format!(- "On an enrolled device, approve it in Cua Spaces or run `cua devices approve {code}`. The code expires in 10 minutes."+ "On a machine you already trust, add it in Cua Spaces under Machines, or run `cua devices approve {code}`. The code expires in 10 minutes.")}),status: status.map(str::to_owned),@@ -1235,19 +1232,19 @@ pub fn approve_view(state: &ApproveSheetState, devices: &[DeviceInput]) -> Approlet ready = approve_ready(state, devices);ApproveSheetView {title: if state.expired {- format!("Re-verify \u{201c}{name}\u{201d}?")+ format!("Keep \u{201c}{name}\u{201d}?")} else {- format!("Approve \u{201c}{name}\u{201d}?")+ format!("Add \u{201c}{name}\u{201d}?")},message: if state.expired {format!("{name} needs one approval to keep reaching your machines for another 30 days.")} else if fallback.is_some() {format!(- "The code expired. Approve \u{201c}{name}\u{201d} by ID instead? Only approve a device you just signed in on."+ "The code expired. Add \u{201c}{name}\u{201d} without it instead? Only add a machine you just signed in on.")} else {format!(- "Enter the code {name} shows to let it list and open your machines. Only approve a device you just signed in on."+ "Enter the code {name} shows to let it see and open your machines. Only add a machine you just signed in on.")},needs_code: !state.expired,@@ -1255,18 +1252,18 @@ pub fn approve_view(state: &ApproveSheetState, devices: &[DeviceInput]) -> Approcode_placeholder: "XXXX-XXXX".into(),code: state.code.clone(),can_approve: ready && !state.busy,- approve_label: if fallback.is_some() {- "Approve by ID".into()+ approve_label: if state.expired {+ "Keep machine".into()} else {- "Approve".into()+ "Add machine".into()},deny_label: if state.expired {- "Not Now".into()+ "Not now".into()} else {- "Deny".into()+ "Not me".into()},deny_revokes: !state.expired,- presence_reason: format!("approve \u{201c}{name}\u{201d} for your Cua account"),+ presence_reason: format!("add \u{201c}{name}\u{201d} to your Cua account"),busy: state.busy,error: state.error.clone(),request: ready.then(|| {@@ -1321,7 +1318,7 @@ mod tests {assert_eq!(b.tone, BannerTone::Warning);assert_eq!(b.text,- "Enroll this device within 5 days to keep reaching your machines."+ "Trust this machine within 5 days to keep reaching your machines.");assert_eq!(b.action, Some(DeviceAction::Enroll));assert!(!v.enrolled);@@ -1355,8 +1352,8 @@ mod tests {let v = devices_view(&input, NOW);assert!(v.enrolled);assert!(v.banner.is_none());- assert_eq!(v.rows[0].title, "MacBook (this device)");- assert_eq!(v.rows[0].subtitle, "Enrolled \u{b7} re-verify in 20 days");+ assert_eq!(v.rows[0].title, "MacBook (this machine)");+ assert_eq!(v.rows[0].subtitle, "Trusted, check again in 20 days");assert_eq!(v.rows[0].actions,[DeviceAction::Rename, DeviceAction::Revoke]@@ -1387,7 +1384,7 @@ mod tests {let banner = v.banner.unwrap();assert_eq!(banner.text,- "Sign in again to enroll this device, or approve it from an enrolled device with the code K7QX-M2RP."+ "Sign in again to trust this machine, or add it from a machine you already trust with the code K7QX-M2RP.");// The banner opens the enroll sheet (Sign in again).assert_eq!(banner.action, Some(DeviceAction::Enroll));@@ -1417,16 +1414,16 @@ mod tests {};assert_eq!(text("device_enrolled", "bootstrap:fresh-sign-in"),- "MacBook was enrolled by a fresh sign-in"+ "MacBook was added by a fresh sign-in");assert_eq!(text("device_enrolled", "bootstrap:grace"),- "MacBook was enrolled during the grace period"+ "MacBook was added during the grace period");// The replaced key is no longer listed: it reads as its id.assert_eq!(text("device_rekeyed", "dev_old"),- "MacBook replaced dev_old on the same computer"+ "MacBook replaced dev_old on the same machine");}@@ -1445,7 +1442,7 @@ mod tests {let b = devices_view(&soon, NOW).banner.unwrap();assert_eq!(b.tone, BannerTone::Warning);assert!(- b.text.starts_with("Re-verify this device within 1 day"),+ b.text.starts_with("Check this machine within 1 day"),"{}",b.text);@@ -1555,7 +1552,7 @@ mod tests {};let t = devices_view(&enrolled, NOW).this_device;assert_eq!(t.kind, EnrollmentKind::Enrolled);- assert_eq!(t.title, "Enrolled until");+ assert_eq!(t.title, "Trusted until");assert_eq!(t.at, Some(NOW + 20 * 86_400));assert_eq!(t.action_label, None);let grace = DevicesInput {@@ -1565,7 +1562,7 @@ mod tests {let t = devices_view(&grace, NOW).this_device;assert_eq!(t.kind, EnrollmentKind::Grace);assert_eq!(t.at, Some(NOW + 5 * 86_400));- assert_eq!(t.action_label.as_deref(), Some("Enroll\u{2026}"));+ assert_eq!(t.action_label.as_deref(), Some("Trust this machine"));let enforced = DevicesInput {enforce_after: Some(NOW - 5),..Default::default()@@ -1573,7 +1570,7 @@ mod tests {let t = devices_view(&enforced, NOW).this_device;assert_eq!((t.kind, t.title.as_str(), t.at),- (EnrollmentKind::NeedsEnrollment, "Needs enrollment", None)+ (EnrollmentKind::NeedsEnrollment, "Not trusted yet", None));}@@ -1592,16 +1589,13 @@ mod tests {let v = devices_view(&input, NOW);let row = v.rows.iter().find(|r| r.id == "dev_b").unwrap();assert_eq!(row.platform, "Linux");- assert_eq!(- row.detail,- "Linux \u{b7} Enrolled \u{b7} re-verify in 9 days"- );+ assert_eq!(row.detail, "Linux, Trusted, check again in 9 days");assert_eq!(row.last_seen, Some(NOW - 60));let confirm = row.revoke_confirm.as_ref().unwrap();assert_eq!(confirm.title, "Revoke \u{201c}Phone\u{201d}?");assert_eq!(confirm.confirm_label, "Revoke");assert!(v.rows[0].current);- assert_eq!(v.rows[0].detail, "Enrolled \u{b7} re-verify in 9 days");+ assert_eq!(v.rows[0].detail, "Trusted, check again in 9 days");assert_eq!(platform_name(Some("macos")), "macOS");assert_eq!(platform_name(None), "");}@@ -1760,7 +1754,7 @@ mod tests {});let v = approve_view(&expired, &no_devices);assert!(!v.needs_code && v.can_approve && !v.deny_revokes);- assert_eq!(v.deny_label, "Not Now");+ assert_eq!(v.deny_label, "Not now");assert_eq!(v.request.unwrap().device_id.as_deref(), Some("dev_b"));assert_eq!(clean_name(" work\u{7}phone ").as_deref(),@@ -1801,11 +1795,11 @@ mod tests {assert_eq!(s.error.as_deref(), Some("The code expired."));let v = approve_view(&s, &one_match);assert!(v.can_approve && v.needs_code);- assert_eq!(v.approve_label, "Approve by ID");+ assert_eq!(v.approve_label, "Add machine");assert!(v.message.contains("Phone")&& v.message- .contains("Only approve a device you just signed in on.")+ .contains("Only add a machine you just signed in on."));assert_eq!(v.request,@@ -1831,7 +1825,7 @@ mod tests {let s = failed(&approve_open(&prompt), &no_match);let v = approve_view(&s, &no_match);assert!(!v.can_approve && v.request.is_none());- assert_eq!(v.approve_label, "Approve");+ assert_eq!(v.approve_label, "Add machine");// Two pending devices sharing the name: ambiguous, no fallback.let ambiguous = [@@ -1859,19 +1853,15 @@ mod tests {assert!(machine_access_notice(EnrollmentKind::Enrolled, None).is_none());assert!(machine_access_notice(EnrollmentKind::Grace, None).is_none());let never = machine_access_notice(EnrollmentKind::NeedsEnrollment, None).unwrap();- assert_eq!(never.status, "Not enrolled");+ assert_eq!(never.status, "Not trusted yet");assert_eq!(never.action_label, ENROLL_THIS_MAC_LABEL);- assert!(never.text.contains("Enroll this Mac"));+ assert!(never.text.contains("Trust this Mac"));let waiting = machine_access_notice(EnrollmentKind::Waiting, Some("K7QX-M2RP")).unwrap();- assert_eq!(waiting.status, "Waiting for approval");+ assert_eq!(waiting.status, "Waiting to be added");assert!(waiting.text.contains("K7QX-M2RP"), "{}", waiting.text);- // No code this launch: how to approve from another device instead.+ // No code this launch: how to add it from another machine instead.let waiting = machine_access_notice(EnrollmentKind::Waiting, Some(" ")).unwrap();- assert!(- waiting.text.contains("Settings \u{203a} Devices"),- "{}",- waiting.text- );+ assert!(waiting.text.contains("from Machines"), "{}", waiting.text);let expired = machine_access_notice(EnrollmentKind::Due, None).unwrap();assert_eq!(expired.action_label, REVERIFY_THIS_MAC_LABEL);assert!(expired.text.contains("expired"));diff --git a/libs/cua/crates/cua-spaces-app-core/src/diagnostics.rs b/libs/cua/crates/cua-spaces-app-core/src/diagnostics.rsindex bbffc6678d..012c598442 100644--- a/libs/cua/crates/cua-spaces-app-core/src/diagnostics.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/diagnostics.rs@@ -93,7 +93,7 @@ fn word(s: &str) -> &str {"linux" => "Linux","windows" => "Windows","macos" => "macOS",- "local" => "this computer",+ "local" => "this machine","relay" => "another of my machines","container" => "container","vm" => "VM",@@ -948,7 +948,7 @@ mod tests {fn keeps_the_apps_words_for_this_machine() {// The machine row is named "This Mac" ("This PC", "This computer"),// so it is among the names to hide. The phrase stays: it names no one.- for phrase in ["This Mac", "This PC", "This computer", "This machine"] {+ for phrase in ["This Mac", "This PC", "This machine", "This machine"] {let names = vec![phrase.to_string(), "Studio".to_string()];assert_eq!(redact_with(&format!("{phrase} can't reach Studio."), &names),diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rsindex 75a7aec873..8242f77424 100644--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs@@ -266,6 +266,7 @@ pub const METHODS: &[&str] = &["machines.merge","machines.pageRows","machines.view",+ "machines.account","devices.activityText","devices.labels","devices.platformName",@@ -1168,6 +1169,12 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {&a.get::<Option<crate::machines_view::MachinesViewInput>>("input")?.unwrap_or_default(),)),+ "machines.account" => out(crate::machines_account::view(+ &a.get::<Option<devices::DevicesInput>>("input")?+ .unwrap_or_default(),+ a.get::<Option<u64>>("now")?.unwrap_or(0),+ a.get::<Option<String>>("readError")?.as_deref(),+ )),"devices.view" => out(devices::devices_view(&a.get::<Option<devices::DevicesInput>>("input")?.unwrap_or_default(),diff --git a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs b/libs/cua/crates/cua-spaces-app-core/src/first_run.rsindex ac3c1f4687..6d93ef8689 100644--- a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/first_run.rs@@ -63,13 +63,13 @@ const AGENT_KEYS: [(&str, &str); 2] = [("claude-code", "anthropic"), ("codex", "/// Home's to-do request: it works on this computer with nothing else set up.pub const FIRST_PROMPT: &str = "List my machines and tell me what's on this Mac";-const FIRST_PROMPT_OTHER: &str = "List my machines and tell me what's on this computer";+const FIRST_PROMPT_OTHER: &str = "List my machines and tell me what's on this machine";const FIRST_PROMPT_PC: &str = "List my machines and tell me what's on this PC";/// The try screen's request: the agent makes a Space on this computer.pub const TRY_PROMPT: &str = "Make a Linux Space on this Mac and show its desktop in a new window.";const TRY_PROMPT_OTHER: &str =- "Make a Linux Space on this computer and show its desktop in a new window.";+ "Make a Linux Space on this machine and show its desktop in a new window.";const TRY_PROMPT_PC: &str = "Make a Linux Space on this PC and show its desktop in a new window.";/// The CLI's name when the host did not say (the released app's,@@ -746,7 +746,7 @@ fn this_computer(os: &str) -> &'static str {match os {"macos" => "this Mac","windows" => "this PC",- _ => "this computer",+ _ => "this machine",}}@@ -763,7 +763,7 @@ fn os_name(os: &str) -> &'static str {"linux" => "Linux","omarchy" => "Omarchy","windows" => "Windows",- _ => "a computer",+ _ => "a machine",}}diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/client.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/client.rsindex 2791fa48ea..f9d868d235 100644--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/client.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/client.rs@@ -318,7 +318,7 @@ impl KeyvaultCommands {} else if !status.initialized {Some(("no_vault",- "It keeps the sessions teleport moves, encrypted on this computer.".to_string(),+ "It keeps the sessions teleport moves, encrypted on this machine.".to_string(),))} else if !status.unlocked {Some(("locked", "Unlock it to see and approve items.".to_string()))diff --git a/libs/cua/crates/cua-spaces-app-core/src/lib.rs b/libs/cua/crates/cua-spaces-app-core/src/lib.rsindex 2daf27045f..8dc3b07118 100644--- a/libs/cua/crates/cua-spaces-app-core/src/lib.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/lib.rs@@ -89,6 +89,7 @@ pub mod keyvault;pub mod local_network;pub mod login_item;pub mod machines;+pub mod machines_account;pub mod machines_health;pub mod machines_view;pub mod message;diff --git a/libs/cua/crates/cua-spaces-app-core/src/machines_account.rs b/libs/cua/crates/cua-spaces-app-core/src/machines_account.rsnew file mode 100644index 0000000000..90dfc7fde4--- /dev/null+++ b/libs/cua/crates/cua-spaces-app-core/src/machines_account.rs@@ -0,0 +1,404 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! What the Machines page adds from the account: the machines waiting to be+//! added ("Add machine", "Not me"), this machine's own trust, and who reached+//! each machine lately. It replaces Settings > Trusted machines: one list of+//! machines, with the state on the row and everything you can do to a machine+//! on its page.+//!+//! [`view`] reads what the relay says of the account's sign-ins and its+//! access log ([`crate::devices::DevicesInput`]) and answers in plain words:+//! "machines", never "devices", and no jargon about enrolling. The web UI+//! in the Mac app, in Electron and in the browser all draw this one view.++use serde::{Deserialize, Serialize};++use crate::devices::{self, BannerTone, DevicesInput, EnrollmentKind, devices_view, platform_name};++/// Newest access lines one machine's page shows.+pub const RECENT_PER_MACHINE: usize = 5;++/// "Add machine": what the person does to a machine that waits.+pub const ADD_LABEL: &str = "Add machine";+/// "Not me": the machine is not the person's.+pub const NOT_ME_LABEL: &str = "Not me";+/// The pending group's title.+pub const PENDING_TITLE: &str = "Waiting for you";+/// A machine's recent access, under its page.+pub const RECENT_TITLE: &str = "Recent access";+/// Nothing reached it yet.+pub const RECENT_EMPTY: &str = "No access yet.";++/// A pending machine's kind.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum PendingKind {+ /// A machine that registered to the account without proof it was the+ /// person's: Add machine confirms it, Not me removes it.+ Machine,+ /// A machine that signed in and waits for an added machine to approve it+ /// (or one that needs a quick check again): Add machine opens the+ /// "Add this machine?" sheet, Not me denies it.+ SignIn,+}++/// One machine waiting to be added.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PendingMachine {+ /// Row id: the machine's, or the sign-in's.+ pub id: String,+ /// What kind of wait it is.+ pub kind: PendingKind,+ /// Its name.+ pub name: String,+ /// `macOS`, `Windows`, `Linux`, or empty.+ pub os: String,+ /// The row's one line.+ pub line: String,+ /// When it last reached the relay (Unix seconds): "asked 2 minutes ago".+ pub since: Option<u64>,+ /// The question the "Add this machine?" page asks.+ pub text: String,+ /// The relay machine (`kind` machine).+ pub machine: Option<String>,+ /// The sign-in (`kind` sign-in).+ pub device: Option<String>,+ /// It was added before and needs a quick check again.+ pub expired: bool,+ /// The approval needs the person present (Touch ID or a password).+ pub requires_presence: bool,+ /// Title and body of the notification that asks for it.+ pub notify_title: String,+ /// See `notify_title`.+ pub notify_body: String,+ /// "Add machine".+ pub add_label: String,+ /// "Not me".+ pub not_me_label: String,+}++/// This machine's own trust, in plain words.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ThisMachineTrust {+ /// `enrolled`, `grace`, `needs-enrollment`, ...: as the devices view says it.+ pub kind: EnrollmentKind,+ /// "Trusted until", "Not trusted yet", ... (a date follows when `at` is set).+ pub status: String,+ /// The date after the status (Unix seconds); the shell formats it.+ pub at: Option<u64>,+ /// What it means and what to do, when there is something to say.+ pub text: Option<String>,+ /// `warning` or `critical`.+ pub tone: Option<String>,+ /// The button that fixes it ("Trust this machine"), when there is one.+ pub action_label: Option<String>,+}++/// One line of who reached a machine.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AccessLine {+ /// Unix seconds.+ pub ts: u64,+ /// In words.+ pub text: String,+ /// Another account or an untrusted machine.+ pub notable: bool,+ /// The machine reached.+ pub machine: Option<String>,+ /// The sign-in that reached it.+ pub device: Option<String>,+}++/// The account's part of the Machines page.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MachinesAccountView {+ /// Waiting machines, newest wait last.+ pub pending: Vec<PendingMachine>,+ /// How many wait (the Machines sidebar item's count).+ pub pending_count: usize,+ /// The group's title.+ pub pending_title: String,+ /// This machine's trust; none while it is unknown.+ pub this_machine: Option<ThisMachineTrust>,+ /// Recent access, newest first, for every machine.+ pub access: Vec<AccessLine>,+ /// "Recent access".+ pub recent_title: String,+ /// "No access yet."+ pub recent_empty: String,+ /// Why the account could not be read (the relay's words), when it could not.+ pub read_error: Option<String>,+}++/// The account's part of the Machines page at `now` (Unix seconds).+pub fn view(input: &DevicesInput, now: u64, read_error: Option<&str>) -> MachinesAccountView {+ let v = devices_view(input, now);+ let os_of = |id: &str| {+ input+ .devices+ .iter()+ .find(|d| d.id == id)+ .map(|d| platform_name(d.platform.as_deref()))+ .unwrap_or_default()+ };+ let mut pending: Vec<PendingMachine> = v+ .unconfirmed_machines+ .iter()+ .map(|m| PendingMachine {+ id: m.id.clone(),+ kind: PendingKind::Machine,+ name: m.title.clone(),+ os: String::new(),+ line: "Waiting to be added".into(),+ since: None,+ text: format!(+ "Add \u{201c}{}\u{201d} to your machines? It signed in without proof it was you. Only add a machine you recognize.",+ m.title+ ),+ machine: Some(m.id.clone()),+ device: None,+ expired: false,+ requires_presence: false,+ notify_title: format!("Add \u{201c}{}\u{201d}?", m.title),+ notify_body: "A machine signed in to your Cua account and asks to be added.".into(),+ add_label: ADD_LABEL.into(),+ not_me_label: NOT_ME_LABEL.into(),+ })+ .collect();+ pending.extend(v.approvals.iter().map(|a| {+ PendingMachine {+ id: a.device_id.clone(),+ kind: PendingKind::SignIn,+ name: a.name.clone(),+ os: os_of(&a.device_id),+ line: if a.expired {+ "Needs a quick check".into()+ } else {+ "Waiting to be added".into()+ },+ since: input+ .devices+ .iter()+ .find(|d| d.id == a.device_id)+ .and_then(|d| d.last_seen),+ text: a.text.clone(),+ machine: None,+ device: Some(a.device_id.clone()),+ expired: a.expired,+ requires_presence: a.requires_presence,+ notify_title: a.notify_title.clone(),+ notify_body: a.notify_body.clone(),+ add_label: ADD_LABEL.into(),+ not_me_label: NOT_ME_LABEL.into(),+ }+ }));++ let this = &v.this_device;+ let this_machine = Some(ThisMachineTrust {+ kind: this.kind,+ status: this.title.clone(),+ at: this.at,+ text: v.banner.as_ref().map(|b| b.text.clone()),+ tone: v.banner.as_ref().map(|b| {+ match b.tone {+ BannerTone::Critical => "critical",+ _ => "warning",+ }+ .to_string()+ }),+ action_label: this.action_label.clone(),+ });++ let access: Vec<AccessLine> = input+ .audit+ .iter()+ .rev()+ .zip(v.activity.iter())+ .filter(|(e, _)| devices::is_access(&e.kind))+ .map(|(e, row)| AccessLine {+ ts: row.ts,+ text: row.text.clone(),+ notable: row.notable,+ machine: e.machine.clone(),+ device: e.device.clone(),+ })+ .take(devices::RECENT_ACCESS_LIMIT * 5)+ .collect();++ MachinesAccountView {+ pending_count: pending.len(),+ pending,+ pending_title: PENDING_TITLE.into(),+ this_machine,+ access,+ recent_title: RECENT_TITLE.into(),+ recent_empty: RECENT_EMPTY.into(),+ read_error: read_error+ .map(str::trim)+ .filter(|e| !e.is_empty())+ .map(String::from),+ }+}++/// The access lines for one machine: those that reached its id, or its+/// sign-in's, newest first, at most [`RECENT_PER_MACHINE`].+pub fn access_for<'a>(+ lines: &'a [AccessLine],+ machine: &str,+ device: Option<&str>,+) -> Vec<&'a AccessLine> {+ lines+ .iter()+ .filter(|l| {+ l.machine.as_deref() == Some(machine)+ || device.is_some_and(|d| l.device.as_deref() == Some(d) && l.machine.is_none())+ })+ .take(RECENT_PER_MACHINE)+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::devices::{AuditInput, DeviceInput, MachineInput};++ fn dev(id: &str, name: &str, state: &str, current: bool) -> DeviceInput {+ DeviceInput {+ id: id.into(),+ name: name.into(),+ state: state.into(),+ enrolled_until: Some(2_000_000_000),+ last_seen: Some(1_000),+ current,+ platform: Some("macos".into()),+ }+ }++ fn input() -> DevicesInput {+ DevicesInput {+ devices: vec![+ dev("dev_me", "My Mac", "enrolled", true),+ dev("dev_new", "Ana's laptop", "pending", false),+ dev("dev_old", "Studio", "expired", false),+ ],+ audit: vec![+ AuditInput {+ ts: 10,+ kind: "machine_access".into(),+ device: Some("dev_old".into()),+ machine: Some("studio".into()),+ subject: None,+ detail: None,+ },+ AuditInput {+ ts: 20,+ kind: "device_session".into(),+ device: Some("dev_old".into()),+ machine: None,+ subject: None,+ detail: None,+ },+ AuditInput {+ ts: 30,+ kind: "unenrolled_access".into(),+ device: None,+ machine: Some("studio".into()),+ subject: None,+ detail: None,+ },+ ],+ machines: vec![MachineInput {+ id: "unknown-box".into(),+ name: "unknown-box".into(),+ confirmed: false,+ }],+ ..DevicesInput::default()+ }+ }++ #[test]+ fn waiting_machines_come_first_with_two_choices_and_a_count() {+ let v = view(&input(), 100, None);+ assert_eq!(v.pending_count, 3);+ assert_eq!(v.pending_title, "Waiting for you");+ let names: Vec<(&str, PendingKind, &str)> = v+ .pending+ .iter()+ .map(|p| (p.name.as_str(), p.kind, p.line.as_str()))+ .collect();+ assert_eq!(+ names,+ [+ ("unknown-box", PendingKind::Machine, "Waiting to be added"),+ ("Ana's laptop", PendingKind::SignIn, "Waiting to be added"),+ ("Studio", PendingKind::SignIn, "Needs a quick check"),+ ]+ );+ for p in &v.pending {+ assert_eq!(+ (p.add_label.as_str(), p.not_me_label.as_str()),+ ("Add machine", "Not me")+ );+ // The words are the machine's: no "device" and no "computer".+ for text in [&p.text, &p.line, &p.notify_title, &p.notify_body] {+ assert!(!text.to_lowercase().contains("device"), "{text}");+ assert!(!text.to_lowercase().contains("computer"), "{text}");+ }+ }+ assert_eq!(v.pending[1].os, "macOS");+ assert!(v.pending[1].requires_presence);+ assert_eq!(v.pending[1].device.as_deref(), Some("dev_new"));+ assert_eq!(v.pending[0].machine.as_deref(), Some("unknown-box"));+ }++ #[test]+ fn a_machine_that_is_not_added_yet_cannot_approve_others() {+ let mut i = input();+ i.devices[0].state = "pending".into();+ let v = view(&i, 100, None);+ // Only the relay's unconfirmed machine waits for this person; the other+ // sign-ins wait for a machine that is already trusted.+ assert_eq!(v.pending_count, 1);+ let me = v.this_machine.unwrap();+ assert_eq!(me.status, "Waiting to be added");+ assert_eq!(me.action_label.as_deref(), Some("Trust this machine"));+ assert!(!me.text.unwrap().to_lowercase().contains("device"));+ }++ #[test]+ fn this_machine_says_it_is_trusted_in_plain_words() {+ let v = view(&input(), 100, None);+ let me = v.this_machine.unwrap();+ assert_eq!(me.kind, EnrollmentKind::Enrolled);+ assert_eq!(me.status, "Trusted until");+ assert_eq!(me.at, Some(2_000_000_000));+ assert_eq!(me.action_label, None);+ }++ #[test]+ fn recent_access_is_per_machine_and_in_machine_words() {+ let v = view(&input(), 100, None);+ // The session is not access; the other two are, newest first.+ assert_eq!(v.access.len(), 2);+ assert!(v.access[0].notable);+ assert_eq!(v.access[0].text, "An untrusted machine used your account");+ let studio = access_for(&v.access, "studio", Some("dev_old"));+ assert_eq!(studio.len(), 2);+ assert!(access_for(&v.access, "other", None).is_empty());+ for l in &v.access {+ assert!(!l.text.to_lowercase().contains("device"), "{}", l.text);+ }+ }++ #[test]+ fn a_relay_that_refused_to_list_is_said_plainly() {+ let v = view(&DevicesInput::default(), 100, Some(" Needs approval "));+ assert_eq!(v.read_error.as_deref(), Some("Needs approval"));+ assert_eq!(v.pending_count, 0);+ }+}diff --git a/libs/cua/crates/cua-spaces-app-core/src/machines_view.rs b/libs/cua/crates/cua-spaces-app-core/src/machines_view.rsindex 8d7f66bd00..e1d289b37f 100644--- a/libs/cua/crates/cua-spaces-app-core/src/machines_view.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/machines_view.rs@@ -2,8 +2,8 @@// Copyright (c) 2026 Cua AI, Inc.//! The Machines page as every UI draws it: the list in groups ("Your-//! machines", "Your devices" (signed-in devices that are none of the-//! machines, whatever their age), a collapsed "Offline for 30+ days", "Team+//! machines" (a signed-in machine that shares nothing is a row there, in the+//! state "Signed in, not sharing"), a collapsed "Offline for 30+ days", "Team//! machines"), one//! muted line per row, and each machine's page (its name and rename, the//! "Let other machines control this desktop" switch, the Spaces on it as@@ -362,16 +362,15 @@ pub struct MachinesView {pub const DESKTOP_LABEL: &str = "Desktop";/// "Your machines".pub const YOURS_TITLE: &str = "Your machines";-/// "Your devices": the group of signed-in devices that are none of your-/// machines, whatever their age.-pub const DEVICES_TITLE: &str = "Your devices";-/// The line of a row that is only a signed-in device: it can't run Spaces+/// The state of a row that is only a signed-in machine: it can't run Spaces/// and nothing is shared from it.-pub const DEVICE_LINE: &str = "Signed-in device, not shared";+pub const DEVICE_LINE: &str = "Signed in, not sharing";/// "Team machines".pub const TEAM_TITLE: &str = "Team machines";/// The button that removes a machine.pub const REMOVE_LABEL: &str = "Remove from account";+/// The button that revokes a signed-in machine that shares nothing.+pub const REVOKE_LABEL: &str = "Revoke";/// The button that opens New Space with the machine chosen.pub const NEW_SPACE_LABEL: &str = "New Space here";/// Under another machine's switches.@@ -538,7 +537,9 @@ fn remove_confirm(name: &str, current: bool, device_only: bool) -> HostConfirm {this machine leaves your machines. Turning a switch on again sets it up again.".to_string()} else if device_only {- format!("{name} will no longer list or reach your machines. Sign in on it again to use it.")+ format!(+ "{name} will no longer see or reach your machines. Signing in on it again adds it back."+ )} else {format!("{name} leaves your machines, and its Spaces are no longer listed here. \@@ -546,9 +547,13 @@ fn remove_confirm(name: &str, current: bool, device_only: bool) -> HostConfirm {)};HostConfirm {- title: format!("Remove \u{201c}{name}\u{201d} from your account?"),+ title: if device_only {+ format!("Revoke \u{201c}{name}\u{201d}?")+ } else {+ format!("Remove \u{201c}{name}\u{201d} from your account?")+ },message,- confirm_label: "Remove".into(),+ confirm_label: if device_only { "Revoke" } else { "Remove" }.into(),cancel_label: "Cancel".into(),}}@@ -564,7 +569,6 @@ pub fn view(input: &MachinesViewInput) -> MachinesView {let host = input.host.as_ref();let mut list = Vec::with_capacity(rows.len());let mut yours = vec![];- let mut devices = vec![];let mut old = vec![];let mut team_ids = vec![];let mut old_removes = vec![];@@ -657,7 +661,9 @@ pub fn view(input: &MachinesViewInput) -> MachinesView {parts.remove(0)};- let status = if !row.online {+ let status = if row.device_only {+ DEVICE_LINE.into()+ } else if !row.online {machines::OFFLINE.into()} else if svc_down {SERVICE_STOPPED.into()@@ -700,6 +706,9 @@ pub fn view(input: &MachinesViewInput) -> MachinesView {let (notice, notice_action) = if row.current {let p = crate::host::panel(host);(p.notice, p.notice_action)+ } else if row.device_only {+ // Nothing is shared from it: its state says so; there is no notice to add.+ (None, None)} else if !row.online {(Some(OFFLINE_NOTICE.into()), None)} else if stopped {@@ -714,12 +723,15 @@ pub fn view(input: &MachinesViewInput) -> MachinesView {(None, None)};+ // A signed-in machine that shares nothing has no Spaces switches.let toggles = if row.current {host_toggles(host)+ } else if row.device_only {+ vec![]} else {remote_toggles(&sw, team)};- let toggles_note = if row.current {+ let toggles_note = if row.current || row.device_only {None} else if team {Some(format!(@@ -733,15 +745,21 @@ pub fn view(input: &MachinesViewInput) -> MachinesView {};let new_space = MachinesViewNewSpace {- label: NEW_SPACE_LABEL.into(),+ label: if row.device_only {+ String::new()+ } else {+ NEW_SPACE_LABEL.into()+ },on: if row.current {"local".into()} else {format!("host:{}", row.id)},- enabled: row.current || (live && sw.provide),+ enabled: row.current || (!row.device_only && live && sw.provide),help: if row.current {None+ } else if row.device_only {+ Some("It is signed in, but it does not share this machine.".into())} else if !row.online {Some("It\u{2019}s offline.".into())} else if stopped {@@ -851,7 +869,7 @@ pub fn view(input: &MachinesViewInput) -> MachinesView {})} else if row.device_only {Some(MachinesViewRemove {- label: REMOVE_LABEL.into(),+ label: REVOKE_LABEL.into(),enabled: true,help: None,host: false,@@ -884,9 +902,7 @@ pub fn view(input: &MachinesViewInput) -> MachinesView {&& row.last_seen.is_some_and(|t| t > 0 && now.saturating_sub(t) >= OLD_AFTER_SECS);- if row.device_only {- devices.push(row.id.clone());- } else if team {+ if team {team_ids.push(row.id.clone());} else if is_old {old.push(row.id.clone());@@ -942,9 +958,14 @@ pub fn view(input: &MachinesViewInput) -> MachinesView {notice_action,toggles,toggles_note,- spaces_title: "Spaces on this machine".into(),+ // A signed-in machine that shares nothing has no Spaces to list.+ spaces_title: if row.device_only {+ String::new()+ } else {+ "Spaces on this machine".into()+ },desktop,- spaces_empty: on.is_empty().then(|| {+ spaces_empty: (on.is_empty() && !row.device_only).then(|| {if row.online && has_desktop {"No other Spaces yet.".into()} else if row.online {@@ -980,15 +1001,6 @@ pub fn view(input: &MachinesViewInput) -> MachinesView {remove_all: None,});}- if !devices.is_empty() {- groups.push(MachinesViewGroup {- id: "devices".into(),- title: DEVICES_TITLE.into(),- collapsed: false,- ids: devices,- remove_all: None,- });- }if !old.is_empty() {let n = old_removes.len();groups.push(MachinesViewGroup {@@ -1270,7 +1282,7 @@ mod tests {}#[test]- fn a_device_that_is_only_signed_in_is_under_your_devices() {+ fn a_machine_that_is_only_signed_in_is_in_the_one_list() {let base = with_devices();let shell = MachinesViewInput {rows: Some(machines::page_rows(&base.page)),@@ -1290,6 +1302,8 @@ mod tests {)}).collect();+ // No separate group: the signed-in machines sit with the others, and the+ // one that has been away for 30+ days is with the old ones.assert_eq!(groups,[@@ -1297,19 +1311,17 @@ mod tests {"yours","Your machines",false,- vec!["this-mac", "studio", "byoc"]+ vec!["this-mac", "studio", "byoc", "dev_lap", "dev_away"]),(- "devices",- "Your devices",- false,- vec!["dev_lap", "dev_away", "dev_stale"]+ "old",+ "Offline for 30+ days (2)",+ true,+ vec!["old1", "dev_stale"]),- ("old", "Offline for 30+ days (1)", true, vec!["old1"]),("team", "Team machines", false, vec!["team"]),]);- assert!(v.groups[1].remove_all.is_none());let flat: Vec<&str> = v.groups.iter()@@ -1319,15 +1331,18 @@ mod tests {flat,v.machines.iter().map(|m| m.id.as_str()).collect::<Vec<_>>());- let all = v.groups[2].remove_all.as_ref().unwrap();- assert_eq!(all.removes.len(), 1);+ let all = v.groups[1].remove_all.as_ref().unwrap();+ assert_eq!(all.removes.len(), 2);assert_eq!(all.removes[0].machine.as_deref(), Some("old1"));assert_eq!(all.removes[0].device.as_deref(), Some("dev_old1"));+ // The signed-in one is revoked through its sign-in.+ assert_eq!(all.removes[1].machine, None);+ assert_eq!(all.removes[1].device.as_deref(), Some("dev_stale"));}}#[test]- fn a_device_of_its_own_reads_signed_in_device_not_shared() {+ fn a_signed_in_machine_that_shares_nothing_says_so_on_its_row() {let mut input = with_devices();input.page@@ -1337,14 +1352,14 @@ mod tests {let devs = ["dev_lap", "dev_away", "dev_stale", "dev_never"];for id in devs {let m = by_id(&v, id);- assert_eq!(m.line, "Signed-in device, not shared", "{id}");+ assert_eq!(m.line, "Signed in, not sharing", "{id}");+ assert_eq!(m.status, "Signed in, not sharing", "{id}");+ // No Spaces switches on a machine that shares nothing.+ assert!(m.toggles.is_empty(), "{id}");+ assert!(!m.new_space.enabled, "{id}");assert_eq!(m.online, id == "dev_lap", "{id}");- assert_eq!(- m.status,- if id == "dev_lap" { "Online" } else { "Offline" },- "{id}"- );let rm = m.remove.as_ref().unwrap();+ assert_eq!(rm.label, "Revoke", "{id}");assert!(rm.enabled, "{id}");assert!(rm.device.is_some() && rm.machine.is_none(), "{id}");}diff --git a/libs/cua/crates/cua-spaces-app-core/src/notch/mod.rs b/libs/cua/crates/cua-spaces-app-core/src/notch/mod.rsindex 63c1eb6e0c..fd0113c727 100644--- a/libs/cua/crates/cua-spaces-app-core/src/notch/mod.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/notch/mod.rs@@ -1053,9 +1053,9 @@ pub fn activity(return Some(NotchActivity {kind: NotchActivityKind::RemoteAccess,label: if connected == 1 {- "Someone is connected to this computer".into()+ "Someone is connected to this machine".into()} else {- format!("{connected} are connected to this computer")+ format!("{connected} are connected to this machine")},symbol: Some(REMOTE_ACCESS_SYMBOL.into()),permille: None,@@ -1923,7 +1923,7 @@ mod tests {"before the hotspot");assert_eq!(a.symbol.as_deref(), Some(REMOTE_ACCESS_SYMBOL));- assert_eq!(a.label, "Someone is connected to this computer");+ assert_eq!(a.label, "Someone is connected to this machine");// A transfer in flight still shows its progress first.let t = NotchTransfer {sent: Some(1),@@ -1945,7 +1945,7 @@ mod tests {);assert_eq!(activity(&[two], false, None, None).unwrap().label,- "2 are connected to this computer"+ "2 are connected to this machine");let gone = this_machine_space(Some(&HostSummaryInput {diff --git a/libs/cua/crates/cua-spaces-app-core/src/onboarding.rs b/libs/cua/crates/cua-spaces-app-core/src/onboarding.rsindex a852e0c001..21e11e1f0a 100644--- a/libs/cua/crates/cua-spaces-app-core/src/onboarding.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/onboarding.rs@@ -1237,7 +1237,7 @@ fn this_computer(os: SpaceOs) -> &'static str {match os {SpaceOs::Macos => "this Mac",SpaceOs::Windows => "this PC",- _ => "this computer",+ _ => "this machine",}}@@ -1700,7 +1700,7 @@ mod tests {);assert_eq!(view_on(&s, SpaceOs::Linux).title,- "How do you want to use this computer?"+ "How do you want to use this machine?");}diff --git a/libs/cua/crates/cua-spaces-app-core/src/relay_usage.rs b/libs/cua/crates/cua-spaces-app-core/src/relay_usage.rsindex 62593f2784..f945e248a3 100644--- a/libs/cua/crates/cua-spaces-app-core/src/relay_usage.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/relay_usage.rs@@ -26,7 +26,7 @@ pub const ROW_LABEL: &str = "Remote use";/// Free plan card, `cua usage`). The relay meters the time an account has/// at least one live session through it; a computer used from itself never/// goes through the relay.-pub const REMOTE_HOURS_MEANING: &str = "Remote hours: time spent using your machines from somewhere else (your laptop, phone or an agent on another computer). Using a computer from itself is free.";+pub const REMOTE_HOURS_MEANING: &str = "Remote hours: time spent using your machines from somewhere else (your laptop, phone or an agent on another machine). Using a machine from itself is free.";/// The notice's button.pub const UPGRADE: &str = "Upgrade";@@ -759,7 +759,7 @@ mod tests {assert_eq!((f.plan.as_str(), f.label.as_str()), ("free", "Free plan"));assert_eq!(f.detail,- "2 live sessions and 20 remote hours a month. Remote hours: time spent using your machines from somewhere else (your laptop, phone or an agent on another computer). Using a computer from itself is free."+ "2 live sessions and 20 remote hours a month. Remote hours: time spent using your machines from somewhere else (your laptop, phone or an agent on another machine). Using a machine from itself is free.");let p = f.primary.unwrap();assert_eq!(diff --git a/libs/cua/crates/cua-spaces-app-core/src/runtimes.rs b/libs/cua/crates/cua-spaces-app-core/src/runtimes.rsindex dfedadcf64..6b0e551301 100644--- a/libs/cua/crates/cua-spaces-app-core/src/runtimes.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/runtimes.rs@@ -364,9 +364,9 @@ fn kind_rows(kind: &str, label: &str, input: &RuntimesInput) -> Vec<SettingsRow>None => row(&detected_id, Note, "Looking for what is installed\u{2026}"),Some([]) => {let label = if k.expected.is_empty() {- "Nothing found on this computer".to_string()+ "Nothing found on this machine".to_string()} else {- format!("No {} found on this computer", join_or(&k.expected))+ format!("No {} found on this machine", join_or(&k.expected))};row(&detected_id, Note, &label)}@@ -691,7 +691,7 @@ mod tests {);assert_eq!(get(&s, "runtime-detected:container").label,- "No Docker or Podman found on this computer"+ "No Docker or Podman found on this machine");}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.rsindex bbd4e0b5cd..bda5de80f6 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@@ -1464,9 +1464,9 @@ mod tests {assert_eq!(enrolled, detail_with(&m, None, None, &x));assert!(enrolled.can_stream && enrolled.access.is_none());for (kind, status) in [- (EnrollmentKind::NeedsEnrollment, "Not enrolled"),- (EnrollmentKind::Waiting, "Waiting for approval"),- (EnrollmentKind::Due, "Re-verification due"),+ (EnrollmentKind::NeedsEnrollment, "Not trusted yet"),+ (EnrollmentKind::Waiting, "Waiting to be added"),+ (EnrollmentKind::Due, "Needs a quick check"),] {let notice = machine_access_notice(kind, Some("K7QX-M2RP")).unwrap();// Unreachable (the relay refuses it): still listed, still explained.diff --git a/libs/cua/crates/cua-spaces-app-core/src/tips.rs b/libs/cua/crates/cua-spaces-app-core/src/tips.rsindex 46dbcf2e0d..86fe8d5975 100644--- a/libs/cua/crates/cua-spaces-app-core/src/tips.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/tips.rs@@ -346,7 +346,7 @@ pub fn view(place: TipPlace, facts: &TipFacts, state: &TipsState) -> Option<Tip>let mut t = tip("on-auto",place,- "New Spaces can go to whichever computer has room.".into(),+ "New Spaces can go to whichever machine has room.".into(),action(TipActionKind::CopyCommand,"Copy",@@ -607,7 +607,7 @@ mod tests {};let t = view(TipPlace::Sidebar, &f, &TipsState::default()).unwrap();assert_eq!(t.id, "on-auto");- assert_eq!(t.text, "New Spaces can go to whichever computer has room.");+ assert_eq!(t.text, "New Spaces can go to whichever machine has room.");assert_eq!(t.code.as_deref(), Some("cua create --on auto"));assert_eq!(t.action.kind, TipActionKind::CopyCommand);assert_eq!(t.action.value.as_deref(), Some("cua create --on auto"));diff --git a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs b/libs/cua/crates/cua-spaces-app-core/src/wizard.rsindex 57e4e43f55..28c023b45a 100644--- a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/wizard.rs@@ -1303,7 +1303,7 @@ fn microvm_support(Some(h) if h.online && host_runs_microvm(h) => Ok(vec![]),Some(h) => Err(MicrovmBlock::Why(host_microvm_why(h))),None => Err(MicrovmBlock::Why(- "needs a computer that runs microVMs".into(),+ "needs a machine that runs microVMs".into(),)),},Location::Auto => {@@ -3728,7 +3728,7 @@ pub fn view_on(state: &WizardState, env: &WizardEnv, os: SpaceOs) -> WizardView},Location::Host => host_why.clone()- .unwrap_or_else(|| "Choose a computer.".to_string()),+ .unwrap_or_else(|| "Choose a machine.".to_string()),Location::Auto => "None of your machines can take it now.".to_string(),Location::Local if runtime_switch.is_some() => match image.local {Some(LocalEngine::Container) => {@@ -4191,7 +4191,7 @@ pub struct FirstSpaceOffer {/// What the offers say while this machine's runtimes or free space are not/// read yet: a VM that may not fit or run here is not offered until they are.-pub const OFFER_NOT_CHECKED: &str = "Still checking this computer.";+pub const OFFER_NOT_CHECKED: &str = "Still checking this machine.";/// Why a macOS VM can't run on a host of this architecture, or none.pub const MACOS_NEEDS_APPLE_SILICON: &str = "macOS Spaces need a Mac with Apple silicon.";diff --git a/libs/cua/crates/cua-spaces-contract/src/lib.rs b/libs/cua/crates/cua-spaces-contract/src/lib.rsindex 987bbd7450..d773f7545e 100644--- a/libs/cua/crates/cua-spaces-contract/src/lib.rs+++ b/libs/cua/crates/cua-spaces-contract/src/lib.rs@@ -1306,7 +1306,7 @@ pub fn tools() -> Vec<Tool> {// --- Space thread and members ------------------------------------------Spec {category: Category::Thread,- result: "JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.",+ result: "JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`, `since_ms`, `text`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`; `since_ms`: when its oldest open task was given; `text`: what it has said so far this turn, the whole text each time and only while it streams, replaced by its reply when the turn ends); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.",instructions: THREAD_READ_INSTRUCTIONS,capabilities: &["thread.read"],sdk_symbol: "space.thread().read(after:limit:)",diff --git a/libs/cua/crates/cua-spaces-ext/src/lib.rs b/libs/cua/crates/cua-spaces-ext/src/lib.rsindex bcdfccde08..1fcb879e6d 100644--- a/libs/cua/crates/cua-spaces-ext/src/lib.rs+++ b/libs/cua/crates/cua-spaces-ext/src/lib.rs@@ -118,6 +118,8 @@ pub const BUDGET_KIND: &str = "budget";pub struct DriveExtension {drive: cua_volume::Drive,live: Arc<tokio::sync::Mutex<persistent::Live>>,+ /// What working sessions have said so far this turn (the thread's streaming rows).+ partials: persistent::Partials,owner: Arc<std::sync::RwLock<thread::Author>>,team_admins: Arc<std::sync::RwLock<std::collections::HashSet<String>>>,pub(crate) runtime: drive_runtime::DriveRuntime,@@ -129,6 +131,7 @@ impl DriveExtension {DriveExtension {drive,live: Default::default(),+ partials: Default::default(),owner: Arc::new(std::sync::RwLock::new(thread::Author::owner())),team_admins: Default::default(),runtime: Default::default(),@@ -175,6 +178,10 @@ impl DriveExtension {pub(crate) fn live(&self) -> Arc<tokio::sync::Mutex<persistent::Live>> {self.live.clone()}++ pub(crate) fn partials(&self) -> persistent::Partials {+ self.partials.clone()+ }}impl SpacesExtension for DriveExtension {diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/members.rsindex 3c558612ad..3a69552406 100644--- a/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs@@ -681,6 +681,7 @@ impl Persistent {// complete error (and a Connect button when it needs a// sign-in) in `failure`.let failure = failure_for(rec, &e.to_string());+ note_rejected(rec, &failure);let mut reply = Draft::new(Author::agent(&rec.name),EntryKind::Message,@@ -909,6 +910,11 @@ impl Persistent {let written = store.release(t.seq, drafts)?;anchor = written.first().map(|e| e.seq);}+ // Nothing is streaming any more: the reply (or the failure) is the entry.+ self.partials+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .remove(&format!("{}/{}#{}", rec.space, rec.name, rec.k()));self.update_in(rec, |r| {r.task = None;r.activity = None;@@ -957,7 +963,26 @@ impl Persistent {.as_ref().is_some_and(|f| !f.open_tasks(Some(&rec.name)).is_empty());if let (Some(stage), true) = (stage, open) {- rows.push(json!({"agent": rec.handle(), "stage": stage}));+ let mut row = json!({"agent": rec.handle(), "stage": stage});+ // When its oldest open task was given (the working row's elapsed time) and what it+ // has said so far this turn (the streaming entry, replaced whole each time).+ if let Some(since) = fold+ .as_ref()+ .and_then(|f| f.open_tasks(Some(&rec.name)).iter().map(|t| t.ts_ms).min())+ {+ row["since_ms"] = json!(since);+ }+ let key = format!("{}/{}#{}", rec.space, rec.name, rec.k());+ if let Some(p) = self+ .partials+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .get(&key)+ .filter(|p| !p.text.trim().is_empty())+ {+ row["text"] = json!(p.text.trim_end());+ }+ rows.push(row);}}rows.sort_by_key(|r| r["agent"].as_str().unwrap_or_default().to_string());@@ -965,9 +990,10 @@ impl Persistent {.iter().map(|r| {format!(- "{}={}",+ "{}={}#{}",r["agent"].as_str().unwrap_or_default(),- r["stage"].as_str().unwrap_or_default()+ r["stage"].as_str().unwrap_or_default(),+ r["text"].as_str().map_or(0, str::len))}).collect::<Vec<_>>()@@ -1967,13 +1993,24 @@ pub(crate) fn failure_for(rec: &AgentRecord, e: &str) -> ag::failure::Failure {f}-/// A failed member's status line: "Not connected" when it needs a sign-in,-/// else the error's first line, whole.+/// A run that was refused its credential: what its harness read from the saved keys for that+/// provider reads as needing a reconnect in Settings, and no run is given it again until it is saved+/// again.+pub(crate) fn note_rejected(rec: &AgentRecord, f: &ag::failure::Failure) {+ if f.class == ag::failure::FailureClass::NeedsConnect+ && let Some(provider) = f.provider.as_deref()+ {+ ag::keys::mark_rejected_for_run(&rec.harness, provider);+ }+}++/// A failed member's status: one short word ("Not connected" when it needs a sign-in, else "Stopped").+/// The error itself is never the status; the member's `failure` carries its complete text for Show+/// details.fn failed_line(harness: &str, e: &str) -> String {- let f = ag::failure::classify(harness, e);- match f.class {+ match ag::failure::classify(harness, e).class {ag::failure::FailureClass::NeedsConnect => "Not connected".into(),- ag::failure::FailureClass::Error => super::notify::reason(e),+ ag::failure::FailureClass::Error => "Stopped".into(),}}@@ -2033,7 +2070,8 @@ pub fn session_state("failed" => s.last_error.as_deref().map(|e| failed_line(&s.harness, e)),_ => None,};- // An error is never cut: only a working line is clipped.+ // A failed session's word is short already; a working line is clipped. (The error is not cut+ // anywhere: its complete text is the session's `failure`.)let activity = if state == "failed" {activity} else {diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rsindex 216d661f56..5a4e86080d 100644--- a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs@@ -482,8 +482,25 @@ pub struct Persistent {owner: Arc<std::sync::RwLock<crate::thread::Author>>,/// Account ids of the admins of the owner's teams.admins: Arc<std::sync::RwLock<std::collections::HashSet<String>>>,+ /// What each working session has said so far this turn, for the thread's streaming row+ /// (`live_rows`); gone when the turn ends (the reply is then the real entry).+ partials: Partials,}+/// What each working session has said so far this turn, by `<space>/<name>#<session>`; shared by every+/// handle on one runtime (the tools and the supervisor each hold their own).+pub(crate) type Partials = Arc<std::sync::Mutex<HashMap<String, Partial>>>;++/// A turn's message so far.+#[derive(Clone, Debug, Default)]+pub(crate) struct Partial {+ turn: u32,+ text: String,+}++/// The longest streaming text a live row carries (characters): the whole message follows as the reply.+const MAX_PARTIAL: usize = 8_000;+impl std::fmt::Debug for Persistent {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {f.debug_struct("Persistent")@@ -504,6 +521,7 @@ impl Persistent {spaces: Spaces,drive: cua_volume::Drive,live: Arc<tokio::sync::Mutex<Live>>,+ partials: Partials,owner: Arc<std::sync::RwLock<crate::thread::Author>>,admins: Arc<std::sync::RwLock<std::collections::HashSet<String>>>,) -> Persistent {@@ -513,6 +531,7 @@ impl Persistent {drive,dir,live,+ partials,owner,admins,}@@ -1661,6 +1680,49 @@ impl Persistent {r}+ /// Keeps what the session's turn has said so far (`message` events), so the thread can show it+ /// as one live entry that is replaced whole; clears it when the turn ends or fails, because the+ /// reply then lands as the entry. Wakes the thread's followers when the text changed.+ fn note_partial(+ &self,+ rec: &AgentRecord,+ events: &[ag::AgentEvent],+ ended: Option<u32>,+ failed: Option<&(u32, String)>,+ ) {+ let key = format!("{}/{}#{}", rec.space, rec.name, rec.k());+ let mut changed = false;+ {+ let mut map = self.partials.lock().unwrap_or_else(|p| p.into_inner());+ for e in events.iter().filter(|e| e.kind == "message") {+ let Some(text) = e.text.as_deref().filter(|t| !t.is_empty()) else {+ continue;+ };+ let p = map.entry(key.clone()).or_default();+ if p.turn != e.turn {+ *p = Partial {+ turn: e.turn,+ text: String::new(),+ };+ }+ if p.text.chars().count() < MAX_PARTIAL {+ p.text.push_str(text);+ changed = true;+ }+ }+ let over = |turn: u32| {+ ended.is_some_and(|t| t >= turn) || failed.is_some_and(|(t, _)| *t >= turn)+ };+ if map.get(&key).is_some_and(|p| over(p.turn)) {+ map.remove(&key);+ changed = true;+ }+ }+ if changed {+ self.thread_store(&rec.space).wake();+ }+ }+async fn tick_agent_inner(&self, rec: AgentRecord, report: &mut TickReport) -> Result<()> {let run = rec.run_id.clone().expect("filtered");let agents = self.cached_agents(&rec.space).await?;@@ -1688,6 +1750,20 @@ impl Persistent {self.renew_claims(&rec, &agents, &run).await?;let rec = self.get(&rec.name)?.session(rec.k());let (ended, failed) = turn_outcome(&page.events);+ self.note_partial(&rec, &page.events, ended, failed.as_ref());+ // A harness may answer a refused credential as an ordinary turn (Hermes does, with its own+ // advice): read the reply as the failed turn it is, so the person's message is not "Done",+ // the reply is the standard Connect card and the credential reads as needing a reconnect.+ let failed = match (&failed, ended) {+ (None, Some(turn)) if turn > rec.saved_turn => agents+ .result(&run)+ .await+ .ok()+ .map(|r| r.text)+ .filter(|text| ag::failure::is_auth_failure_reply(&rec.harness, text))+ .map(|text| (turn, text.trim().to_string())),+ _ => failed,+ };// The thread task this run's turn worked on: its reply and state.let mut anchor = None;let mut task_ended = false;@@ -1718,6 +1794,9 @@ impl Persistent {task_ended = true;}}+ if let Some((_, err)) = &failed {+ members::note_rejected(&rec, &members::failure_for(&rec, err));+ }if let Some((turn, err)) = &failed {// One notification per failed turn, posted before anything// below can fail this pass (a later pass sees the same events).@@ -2039,6 +2118,7 @@ impl SpacesPersistent for Spaces {self.clone(),ext.drive().clone(),ext.live(),+ ext.partials(),ext.owner(),ext.team_admins(),)diff --git a/libs/cua/crates/cua-spaces-ext/tests/agent_sessions.rs b/libs/cua/crates/cua-spaces-ext/tests/agent_sessions.rsindex 05c5a53672..ab989bd8c8 100644--- a/libs/cua/crates/cua-spaces-ext/tests/agent_sessions.rs+++ b/libs/cua/crates/cua-spaces-ext/tests/agent_sessions.rs@@ -532,7 +532,14 @@ async fn each_session_shows_its_state_and_activity() {.starts_with("waiting for an answer to #"));assert_eq!(s[2]["state"], "failed", "{s:?}");- assert!(s[2]["activity"].as_str().unwrap().contains("exited"));+ // A short word, never the error; the complete text is the session's failure.+ assert_eq!(s[2]["activity"], "Stopped");+ assert!(+ s[2]["failure"]["message"]+ .as_str()+ .unwrap()+ .contains("exited")+ );let m = call(&fx.mcp, "agent_members", json!({"space": fx.space})).await.unwrap();diff --git a/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs b/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rsindex 48f8f7c52d..504f16df82 100644--- a/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs+++ b/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs@@ -819,10 +819,12 @@ async fn a_live_row_follows_the_stage_and_clears_on_the_reply() {.unwrap();let task = posted["entry"]["seq"].as_u64().unwrap();// Right away, before the dispatcher's next pass.- assert_eq!(- live(&fx).await["agents"],- json!([{"agent": "ada", "stage": "thinking"}])- );+ let first = live(&fx).await;+ assert_eq!(first["agents"][0]["agent"], "ada");+ assert_eq!(first["agents"][0]["stage"], "thinking");+ // When the task was given, for the working row's clock; nothing said yet.+ assert!(first["agents"][0]["since_ms"].as_u64().unwrap() > 0);+ assert!(first["agents"][0]["text"].is_null());Box::pin(p.tick()).await;run_state(&fx, json!({"status": "running", "turn": 2}));let mut seen = vec![];@@ -852,12 +854,10 @@ async fn a_live_row_follows_the_stage_and_clears_on_the_reply() {raw_events(&fx, &evs);Box::pin(p.tick()).await;let l = live(&fx).await;- assert_eq!(- l["agents"],- json!([{"agent": "ada", "stage": want}]),- "{want}"- );- assert_eq!(l["key"], format!("ada={want}"));+ assert_eq!(l["agents"].as_array().unwrap().len(), 1, "{want}");+ assert_eq!(l["agents"][0]["agent"], "ada", "{want}");+ assert_eq!(l["agents"][0]["stage"], want, "{want}");+ assert_eq!(l["key"], format!("ada={want}#0"));seen.push(want);}assert_eq!(@@ -902,11 +902,17 @@ async fn a_live_row_follows_the_stage_and_clears_on_the_reply() {t0.elapsed());let followed = followed.unwrap();+ // What it has said so far streams as one live entry, replaced whole by the next snapshot.+ assert_eq!(followed["live"]["agents"][0]["text"], "2 failures");+ assert_eq!(followed["entries"], json!([]));+ events(&fx, &[("message", 2, Some(": a, b"))]);+ Box::pin(p.tick()).await;+ let l = live(&fx).await;assert_eq!(- followed["live"]["agents"],- json!([{"agent": "ada", "stage": "replying"}])+ l["agents"][0]["text"], "2 failures: a, b",+ "the whole text so far, not a chunk");- assert_eq!(followed["entries"], json!([]));+ assert_eq!(l["agents"][0]["stage"], "replying");// The turn ends: the reply is the answer and nobody is at work.events(&fx, &[("turn_ended", 2, None)]);run_state(&fx, json!({"status": "idle", "turn": 2}));@@ -948,10 +954,9 @@ async fn a_cold_start_shows_starting_and_a_failure_clears_the_row() {).await.unwrap();- assert_eq!(- live(&fx).await["agents"],- json!([{"agent": "ada", "stage": "starting"}])- );+ let cold = live(&fx).await;+ assert_eq!(cold["agents"][0]["agent"], "ada");+ assert_eq!(cold["agents"][0]["stage"], "starting");// The mock guest can't start a run: the delivery fails.Box::pin(p.tick()).await;let t = call(&fx.mcp, "thread_read", json!({"space": fx.space}))@@ -1535,6 +1540,105 @@ async fn a_failed_turn_fails_its_task_and_the_notification_points_at_it() {assert!(p.get("ada").unwrap().task.is_none());}+/// Hermes answers a refused key as an ordinary turn, with its own advice. The thread reads it as the+/// failed turn it is: the person's message fails (never "Done"), the reply is the standard Connect+/// card in plain words without Hermes' advice, and the complete text stays under Show details.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_refused_key_answered_as_text_is_a_failed_turn() {+ let fx = setup().await;+ let (p, _proc) = member_with_idle_run(&fx).await;+ edit_record(&fx, "ada", |r| r["harness"] = json!("hermes"));+ let posted = call(+ &fx.mcp,+ "thread_post",+ json!({"space": fx.space, "text": "@ada hello"}),+ )+ .await+ .unwrap();+ let task = posted["entry"]["seq"].as_u64().unwrap();+ Box::pin(p.tick()).await;+ let said = "Anthropic rejected your API key, so the model can't be reached. Update it in Settings -> Providers, or run `hermes setup` in a terminal. Provider said: HTTP 401: OAuth access token is invalid.";+ events(+ &fx,+ &[+ ("turn_started", 2, None),+ ("message", 2, Some(said)),+ ("turn_ended", 2, None),+ ],+ );+ run_state(&fx, json!({"status": "idle", "turn": 2}));+ Box::pin(p.tick()).await;+ let t = call(&fx.mcp, "thread_read", json!({"space": fx.space}))+ .await+ .unwrap();+ let e = entries(&t);+ let reply = e+ .iter()+ .find(|x| x["reply_to"] == task && x["kind"] == "message")+ .expect("a reply");+ assert_eq!(+ reply["text"],+ "Anthropic rejected the key Hermes used. Update it, then try again."+ );+ assert!(!reply["text"].as_str().unwrap().contains("hermes setup"));+ assert_eq!(reply["failure"]["class"], "needs_connect");+ assert_eq!(reply["failure"]["provider"], "anthropic");+ assert_eq!(reply["failure"]["message"], said);+ let update = e.iter().rev().find(|x| x["kind"] == "task_update").unwrap();+ assert_eq!(update["update"]["state"], "failed");+ // One notification, the failure's (not "Finished").+ let notes = p.feed().list(false, None).unwrap();+ assert!(notes.iter().any(|n| n.kind == "error" && n.body == said));+ assert!(!notes.iter().any(|n| n.kind == "turn_ended"));+}++/// An ordinary answer that merely talks about authentication stays an answer.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn an_answer_that_mentions_a_401_is_still_an_answer() {+ let fx = setup().await;+ let (p, _proc) = member_with_idle_run(&fx).await;+ edit_record(&fx, "ada", |r| r["harness"] = json!("hermes"));+ let posted = call(+ &fx.mcp,+ "thread_post",+ json!({"space": fx.space, "text": "@ada why does login fail"}),+ )+ .await+ .unwrap();+ let task = posted["entry"]["seq"].as_u64().unwrap();+ Box::pin(p.tick()).await;+ events(+ &fx,+ &[+ ("turn_started", 2, None),+ (+ "message",+ 2,+ Some(+ "The endpoint answers 401 Unauthorized when the token is missing, so I added the header.",+ ),+ ),+ ("turn_ended", 2, None),+ ],+ );+ run_state(&fx, json!({"status": "idle", "turn": 2}));+ Box::pin(p.tick()).await;+ let t = call(&fx.mcp, "thread_read", json!({"space": fx.space}))+ .await+ .unwrap();+ let reply = entries(&t)+ .into_iter()+ .find(|x| x["reply_to"] == task && x["kind"] == "message")+ .expect("a reply");+ assert!(reply["failure"].is_null());+ assert!(+ reply["text"]+ .as_str()+ .unwrap()+ .starts_with("The endpoint answers 401")+ );+}+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn a_read_without_after_is_the_newest_page_and_pages_back() {let fx = setup().await;diff --git a/libs/cua/crates/cua-spaces/src/agents/keys.rs b/libs/cua/crates/cua-spaces/src/agents/keys.rsindex 2cf52b1581..0079d38733 100644--- a/libs/cua/crates/cua-spaces/src/agents/keys.rs+++ b/libs/cua/crates/cua-spaces/src/agents/keys.rs@@ -30,6 +30,7 @@ pub const SECRET_NAME: &str = "agent-keys";/// never read or change a key.pub const APP_METHODS: &[&str] = &["agent_keys.list",+ "agent_keys.check","agent_keys.set","agent_keys.remove","agent_keys.shell",@@ -292,6 +293,10 @@ struct Stored {source: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]expires_ms: Option<u64>,+ /// When the provider (or an agent's run) said this credential is rejected (Unix ms). Saving+ /// the credential again replaces the entry, so a reconnect clears it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ rejected_ms: Option<u64>,}impl std::fmt::Debug for Stored {@@ -310,6 +315,11 @@ impl Stored {self.expires_ms.is_some_and(|e| e <= now_ms())}+ /// Whether runs may be given it: not past its expiry and not rejected.+ fn usable(&self) -> bool {+ !self.expired() && self.rejected_ms.is_none()+ }+fn info(&self) -> KeyInfo {let n = self.value.chars().count();let last4 = if n >= 12 {@@ -325,7 +335,8 @@ impl Stored {label: self.label.clone(),source: self.source.clone(),expires_ms: self.expires_ms,- expired: self.expired(),+ // A rejected credential reads like an expired one: it no longer works, Reconnect.+ expired: !self.usable(),}}}@@ -500,6 +511,7 @@ impl AgentKeys {label: None,source: None,expires_ms: None,+ rejected_ms: None,};let info = stored.info();keys.push(stored);@@ -560,6 +572,7 @@ impl AgentKeys {label: Some(label.into()),source: Some(source.into()),expires_ms,+ rejected_ms: None,};let info = stored.info();keys.push(stored);@@ -606,7 +619,7 @@ impl AgentKeys {match self.read(&mut g, false) {Ok(keys) => keys.into_iter()- .filter(|k| !k.expired())+ .filter(Stored::usable).map(|k| k.env).collect(),Err(e) => {@@ -628,7 +641,7 @@ impl AgentKeys {.into_iter()// A sign-in past its expiry is not forwarded: the run would// only be told 401 by the provider.- .filter(|k| names.contains(&k.env.as_str()) && !k.expired())+ .filter(|k| names.contains(&k.env.as_str()) && k.usable()).map(|k| (k.env, k.value)).collect(),Err(e) => {@@ -639,6 +652,209 @@ impl AgentKeys {}}+impl AgentKeys {+ /// Notes that the credentials named in `envs` were rejected by their provider (a run of an+ /// agent got an authentication failure with them): they read as needing a reconnect and no run+ /// gets them until they are saved again. Returns the names that changed.+ pub fn mark_rejected(&self, envs: &[&str]) -> Result<Vec<String>> {+ self.set_rejected(envs.iter().map(|e| (*e, None)), Some(now_ms()))+ }++ /// Sets (`Some`) or clears (`None`) the rejection of each `(env, only if added at)`; a+ /// credential saved again since (a different `added_ms`) is left alone.+ fn set_rejected<'a>(+ &self,+ which: impl Iterator<Item = (&'a str, Option<u64>)>,+ at: Option<u64>,+ ) -> Result<Vec<String>> {+ if self.store.is_none() {+ return Ok(vec![]);+ }+ let which: Vec<(&str, Option<u64>)> = which.collect();+ let mut g = self.lock();+ let mut keys = self.read(&mut g, true)?;+ let mut changed = vec![];+ for k in keys.iter_mut() {+ let Some((_, added)) = which.iter().find(|(e, _)| *e == k.env) else {+ continue;+ };+ if added.is_some_and(|a| a != k.added_ms) || k.rejected_ms.is_some() == at.is_some() {+ continue;+ }+ k.rejected_ms = at;+ changed.push(k.env.clone());+ }+ if !changed.is_empty() {+ self.write(&mut g, keys)?;+ }+ Ok(changed)+ }++ /// The API keys to check against their provider: `(env, added_ms, value)`. A sign-in token+ /// (`CLAUDE_CODE_OAUTH_TOKEN`, `CODEX_AUTH_JSON`) has no check that is known to accept it,+ /// so it is not asked about.+ fn checkable(&self) -> Vec<(String, u64, String)> {+ let mut g = self.lock();+ match self.read(&mut g, true) {+ Ok(keys) => keys+ .into_iter()+ .filter(|k| endpoint_for(&k.env).is_some() && !k.expired())+ .map(|k| (k.env, k.added_ms, k.value))+ .collect(),+ Err(_) => vec![],+ }+ }+}++/// What the provider said of a key.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum KeyCheck {+ /// The provider accepted it.+ Valid,+ /// The provider refused it (HTTP 401 or 403): it does not work.+ Rejected,+ /// No answer worth acting on (offline, rate limited, a server error): leave it as it was.+ Unknown,+}++/// The providers' read-only "list models" requests: free, about 100 ms, and they answer 401 for a+/// key that does not work. Only API keys are asked about (see [`AgentKeys::checkable`]).+#[derive(Clone, Debug)]+pub struct CheckEndpoints {+ pub anthropic: String,+ pub openai: String,+}++impl Default for CheckEndpoints {+ fn default() -> Self {+ Self {+ anthropic: "https://api.anthropic.com/v1/models?limit=1".into(),+ openai: "https://api.openai.com/v1/models".into(),+ }+ }+}++/// Which provider's request checks `env`, if it is an API key we can check.+fn endpoint_for(env: &str) -> Option<&'static str> {+ match env {+ "ANTHROPIC_API_KEY" => Some("anthropic"),+ "OPENAI_API_KEY" => Some("openai"),+ _ => None,+ }+}++/// How long an answer is reused (Settings opens and the Agents page opens ask often).+const CHECK_CACHE: Duration = Duration::from_secs(5 * 60);++type CheckCache = Mutex<BTreeMap<(String, u64), (Instant, KeyCheck)>>;++fn check_cache() -> &'static CheckCache {+ static CACHE: OnceLock<CheckCache> = OnceLock::new();+ CACHE.get_or_init(|| Mutex::new(BTreeMap::new()))+}++/// Asks the provider about one key. The value only goes into the request's header; nothing here+/// logs it, and an error is reported without its text.+async fn ask_provider(+ client: &reqwest::Client,+ ep: &CheckEndpoints,+ env: &str,+ value: &str,+) -> KeyCheck {+ let request = match endpoint_for(env) {+ Some("anthropic") => client+ .get(&ep.anthropic)+ .header("x-api-key", value)+ .header("anthropic-version", "2023-06-01"),+ Some(_) => client.get(&ep.openai).bearer_auth(value),+ None => return KeyCheck::Unknown,+ };+ match request.send().await {+ Ok(r) if r.status().is_success() => KeyCheck::Valid,+ Ok(r) if matches!(r.status().as_u16(), 401 | 403) => KeyCheck::Rejected,+ _ => KeyCheck::Unknown,+ }+}++impl AgentKeys {+ /// Asks each provider whether the saved API keys still work (a cheap read-only request,+ /// answers reused for five minutes, never logged), notes a refused key as needing a reconnect+ /// and clears the note on one that is accepted again. Sign-in tokens are not asked about.+ /// Never fails the caller: the list that follows says what is known.+ pub async fn recheck(&self, ep: &CheckEndpoints) -> Result<KeysReport> {+ let todo = self.checkable();+ if !todo.is_empty() {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(6))+ .build()+ .map_err(|e| Error::Agent(e.to_string()))?;+ let mut rejected: Vec<(String, u64)> = vec![];+ let mut accepted: Vec<(String, u64)> = vec![];+ for (env, added, value) in todo {+ let cached = check_cache()+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .get(&(env.clone(), added))+ .filter(|(at, _)| at.elapsed() < CHECK_CACHE)+ .map(|(_, c)| *c);+ let answer = match cached {+ Some(c) => c,+ None => {+ let c = ask_provider(&client, ep, &env, &value).await;+ if c != KeyCheck::Unknown {+ check_cache()+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .insert((env.clone(), added), (Instant::now(), c));+ }+ c+ }+ };+ match answer {+ KeyCheck::Rejected => rejected.push((env, added)),+ KeyCheck::Valid => accepted.push((env, added)),+ KeyCheck::Unknown => {}+ }+ }+ self.set_rejected(+ rejected.iter().map(|(e, a)| (e.as_str(), Some(*a))),+ Some(now_ms()),+ )?;+ self.set_rejected(accepted.iter().map(|(e, a)| (e.as_str(), Some(*a))), None)?;+ }+ self.report()+ }+}++/// Notes that an agent run got an authentication failure: the saved credentials of `provider`+/// that `harness` reads (and only those) read as needing a reconnect.+pub fn mark_rejected_for_run(harness: &str, provider: &str) {+ let Some(h) = super::harness::harness(harness) else {+ return;+ };+ let envs: Vec<&str> = h+ .keys+ .iter()+ .copied()+ .filter(|k| provider_envs(provider).contains(k))+ .collect();+ if envs.is_empty() {+ return;+ }+ if let Err(e) = global().mark_rejected(&envs) {+ tracing::warn!(error = %e, "agent keys: could not note a rejected credential");+ }+}++/// The variables that hold a provider's credentials (a key, a sign-in token).+fn provider_envs(provider: &str) -> &'static [&'static str] {+ match provider {+ "anthropic" => &["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"],+ "openai" => &["OPENAI_API_KEY", "CODEX_AUTH_JSON"],+ _ => &[],+ }+}+fn store_err(e: cua_auth::Error) -> Error {Error::Agent(format!("the Keychain refused the agent keys: {e}"))}@@ -704,7 +920,8 @@ pub fn app_call(r.and_then(|r| serde_json::to_value(r).map_err(|e| Error::Agent(e.to_string())))};Some(match name {- "agent_keys.list" => report(keys.report()),+ // The check needs the network: `app_tool_async` does it; a synchronous caller gets the list.+ "agent_keys.list" | "agent_keys.check" => report(keys.report()),"agent_keys.set" => report(serde_json::from_value::<SetArgs>(args).map_err(|e| {@@ -755,6 +972,25 @@ pub fn app_tool(name: &str, args: serde_json::Value) -> Option<crate::mcp::ToolO})}+/// [`app_tool`] for a caller that can wait: `agent_keys.check` asks the providers whether the saved+/// API keys still work, then answers like `agent_keys.list`.+#[cfg(feature = "mcp")]+pub async fn app_tool_async(+ name: &str,+ args: serde_json::Value,+) -> Option<crate::mcp::ToolOutcome> {+ if name != "agent_keys.check" {+ return app_tool(name, args);+ }+ Some(match global().recheck(&CheckEndpoints::default()).await {+ Ok(report) => match serde_json::to_value(report) {+ Ok(v) => crate::mcp::ToolOutcome::json(&v),+ Err(e) => crate::mcp::ToolOutcome::error(&Error::Agent(e.to_string())),+ },+ Err(e) => crate::mcp::ToolOutcome::error(&e),+ })+}+/// A serde error without the input it quotes (it could be the key).fn redact_serde(e: &serde_json::Error) -> String {let s = e.to_string();@@ -887,6 +1123,155 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}+ /// A tiny local provider: answers 200 to the key `good`, 401 to anything else, 500 to `flaky`;+ /// counts the requests it got.+ async fn provider() -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}/v1/models", listener.local_addr().unwrap());+ let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let counted = hits.clone();+ tokio::spawn(async move {+ loop {+ let Ok((mut sock, _)) = listener.accept().await else {+ return;+ };+ counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ let mut buf = vec![0u8; 4096];+ let n = sock.read(&mut buf).await.unwrap_or(0);+ let req = String::from_utf8_lossy(&buf[..n]).to_ascii_lowercase();+ let status = if req.contains("good") {+ "200 OK"+ } else if req.contains("flaky") {+ "500 Internal Server Error"+ } else {+ "401 Unauthorized"+ };+ let _ = sock+ .write_all(+ format!("HTTP/1.1 {status}\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{{}}")+ .as_bytes(),+ )+ .await;+ }+ });+ (url, hits)+ }++ /// A key the provider refuses reads as needing a reconnect and reaches no run; one it accepts+ /// stays; a key saved again clears the note; sign-in tokens are not asked about; the answer is+ /// reused, never logged and never returned.+ #[tokio::test]+ async fn a_saved_key_the_provider_refuses_needs_a_reconnect() {+ let (keys, dir) = temp_keys();+ let (url, hits) = provider().await;+ let ep = CheckEndpoints {+ anthropic: url.clone(),+ openai: url,+ };+ keys.set("anthropic", None, "sk-ant-stale-0000-abcd")+ .unwrap();+ keys.set("openai", None, "sk-good-1111-wxyz").unwrap();+ keys.import(+ "claude-code",+ "CLAUDE_CODE_OAUTH_TOKEN",+ "Claude sign-in",+ "sk-ant-oat01-whatever",+ None,+ )+ .unwrap();+ let report = keys.recheck(&ep).await.unwrap();+ let by = |env: &str| report.keys.iter().find(|k| k.env == env).unwrap().expired;+ assert!(by("ANTHROPIC_API_KEY"), "the refused key needs a reconnect");+ assert!(!by("OPENAI_API_KEY"));+ // The sign-in token is not asked about: no request for it, and it stays as it was.+ assert!(!by("CLAUDE_CODE_OAUTH_TOKEN"));+ assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 2);+ // The refused key reaches no run; the others do.+ assert_eq!(keys.names(), ["CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY"]);+ assert!(keys.values(&["ANTHROPIC_API_KEY"]).is_empty());+ // Opened again a moment later: the answers are reused.+ keys.recheck(&ep).await.unwrap();+ assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 2);+ // The report never carries a value.+ let text = serde_json::to_string(&report).unwrap();+ assert!(+ !text.contains("sk-ant-stale") && !text.contains("sk-good"),+ "{text}"+ );+ // Reconnecting (saving it again) clears the note.+ keys.set("anthropic", None, "sk-good-2222-abcd").unwrap();+ assert!(!keys.list().unwrap().iter().any(|k| k.expired));+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A provider that cannot answer is no reason to flag a key.+ #[tokio::test]+ async fn an_unreachable_provider_flags_nothing() {+ let (keys, dir) = temp_keys();+ let (url, _) = provider().await;+ let ep = CheckEndpoints {+ anthropic: url.clone(),+ openai: url,+ };+ keys.set("openai", None, "sk-flaky-3333-wxyz").unwrap();+ assert!(!keys.recheck(&ep).await.unwrap().keys[0].expired);+ let offline = CheckEndpoints {+ anthropic: "http://127.0.0.1:1/x".into(),+ openai: "http://127.0.0.1:1/x".into(),+ };+ keys.set("anthropic", None, "sk-ant-offline-4444").unwrap();+ assert!(+ !keys+ .recheck(&offline)+ .await+ .unwrap()+ .keys+ .iter()+ .any(|k| k.expired)+ );+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A run's authentication failure marks only the credentials its harness reads, for its provider.+ #[test]+ fn a_run_that_fails_to_authenticate_marks_what_it_was_given() {+ let (keys, dir) = temp_keys();+ keys.set("anthropic", None, "sk-ant-api-0000-abcd").unwrap();+ keys.import(+ "claude-code",+ "CLAUDE_CODE_OAUTH_TOKEN",+ "Claude sign-in",+ "sk-ant-oat01-whatever",+ None,+ )+ .unwrap();+ keys.set("openai", None, "sk-openai-1111-wxyz").unwrap();+ // Hermes read the API key (not the sign-in token), and said Anthropic refused it.+ let h = super::super::harness::harness("hermes").unwrap();+ let envs: Vec<&str> = h+ .keys+ .iter()+ .copied()+ .filter(|k| provider_envs("anthropic").contains(k))+ .collect();+ assert!(envs.contains(&"ANTHROPIC_API_KEY"));+ keys.mark_rejected(&envs).unwrap();+ let expired = |env: &str| {+ keys.list()+ .unwrap()+ .iter()+ .find(|k| k.env == env)+ .unwrap()+ .expired+ };+ assert!(expired("ANTHROPIC_API_KEY"));+ assert!(!expired("OPENAI_API_KEY"));+ // Noting it twice changes nothing more.+ assert!(keys.mark_rejected(&envs).unwrap().is_empty());+ let _ = std::fs::remove_dir_all(&dir);+ }+#[test]fn a_short_key_shows_no_characters() {let (keys, dir) = temp_keys();diff --git a/libs/cua/spaces-contract/manifest.json b/libs/cua/spaces-contract/manifest.jsonindex fd76026bdc..8ee6fcaf29 100644--- a/libs/cua/spaces-contract/manifest.json+++ b/libs/cua/spaces-contract/manifest.json@@ -3220,7 +3220,7 @@"sdk_symbol": "space.thread().read(after:limit:)","rust_symbol": "thread::Thread::read","notes": [],- "result": "JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.",+ "result": "JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`, `since_ms`, `text`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`; `since_ms`: when its oldest open task was given; `text`: what it has said so far this turn, the whole text each time and only while it streams, replaced by its reply when the turn ends); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.","errors": [],"input_schema": {"properties": {diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex 9987ebc05f..50c5c0c440 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -2491,6 +2491,20 @@"subcommands": [],"usage": "cua agent keys set [OPTIONS] <PROVIDER>"},+ {+ "abstract": "Ask each provider whether the saved API keys still work (a cheap read-only request; nothing is sent that is not a key's own request). A key the provider refuses is listed as needing a reconnect, and runs are not given it until it is saved again",+ "after_help": "Examples:\n cua agent keys check",+ "aliases": [],+ "arguments": [],+ "flags": [],+ "hidden": false,+ "hidden_aliases": [],+ "name": "check",+ "options": [],+ "subcommand_optional": false,+ "subcommands": [],+ "usage": "cua agent keys check [OPTIONS]"+ },{"abstract": "Remove the key a run gets as ENV","after_help": "Examples:\n cua agent keys rm ANTHROPIC_API_KEY",@@ -16591,7 +16605,7 @@"usage": "cua devices approve [OPTIONS] [CODE]"},{- "abstract": "Your devices and their state",+ "abstract": "Your signed-in machines and their state","after_help": "Examples:\n cua devices ls\n cua devices ls --json","aliases": ["list"