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
fix(spaces): plain plan errors and a way to upgrade when adding a team computer (#5217)
Francesco Bonaccidb87d6676d82
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex 54f3ccefb1..f797137b8e 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -123,7 +123,7 @@ export type { TelemetryLinkNotice } from "./ops/telemetry";export { defaultTeam, eligibleTeams, teamName, useTeamChoices, type TeamChoices } from "./teams";export { joinFailureText, useJoinWithCode, type JoinHook, type JoinPhase } from "./join";export { displayPairingCode, normalizePairingCode, pairingLinkRelay } from "./pairing-code";-export { expiresInText, FINISHING_SETUP, PAIRING_POLL_MS, pairingUnsupported, usePairingCode, type PairingHook, type PairingPhase } from "./pairing";+export { BUY_PRO_URL, BUY_TEAMS_URL, expiresInText, FINISHING_SETUP, PAIRING_POLL_MS, pairingUnsupported, planFailure, usePairingCode, type PairingHook, type PairingPhase } from "./pairing";export { READY_STARTUP, type StartupAction, type StartupPhase, type StartupState } from "./ops/startup";export {CHECKLIST_STEPS,diff --git a/apps/cua-spaces-web/src/bridge/pairing.ts b/apps/cua-spaces-web/src/bridge/pairing.tsindex 0dd68bbbf3..a2a4c9016b 100644--- a/apps/cua-spaces-web/src/bridge/pairing.ts+++ b/apps/cua-spaces-web/src/bridge/pairing.ts@@ -10,8 +10,9 @@** With `team` (an organization id) the machine that used the code is then* made a team machine (`sharing.share` with `team:<id>`): pairing alone- * never puts a machine in a team. Right after a Teams checkout that can take- * up to a minute ("Finishing setup…"); the host retries meanwhile.+ * never puts a machine in a team. Right after a Teams checkout the host+ * waits a few seconds for the plan ("Finishing setup…"); a team that never+ * paid fails at once, with words and a way to upgrade (`planFailure`).*/import { useEffect, useRef, useState } from "react";@@ -36,7 +37,40 @@ export interface PairingState {* With a `team`, after the code was used: `adding` (show "Finishing* setup…"), `added`, or `failed` with the reason. Null otherwise.*/- team?: { phase: "adding" | "added" | "failed"; error: string | null } | null;+ team?: { phase: "adding" | "added" | "failed"; error: string | null; upgradeUrl?: string | null } | null;+}++/** Where a team owner buys Teams, and where anyone buys Pro. */+export const BUY_TEAMS_URL = "https://app.cua.ai/buy/teams";+export const BUY_PRO_URL = "https://app.cua.ai/buy/pro";++const BUY_URL = /\s*https:\/\/app\.cua\.ai\/buy\/(?:teams|pro)\b\S*/;++/**+ * A failed team step in words. The host already words plan errors: an owner+ * gets the checkout link last in the message (it becomes an Upgrade button),+ * anyone else is told to ask the owner. A raw plan error from an older host+ * (`HTTP 402 (feature_required: team_machines)`) is reworded here, without a+ * button because the role is not known.+ */+export function planFailure(raw: string): { text: string; upgradeUrl: string | null } {+ const link = BUY_URL.exec(raw);+ if (link) return { text: raw.replace(BUY_URL, "").trim(), upgradeUrl: link[0].trim() };+ const feature = /feature_required(?::\s*(\w+))?/.exec(raw)?.[1];+ if (/feature_required/.test(raw)) {+ const what =+ feature === "team_machines"+ ? "Team computers need the Teams plan."+ : feature === "team_roles"+ ? "Admin roles need the Teams plan."+ : feature === "device_approval"+ ? "Approving devices needs the Teams plan."+ : "This needs the Teams plan.";+ return { text: `${what} Ask the team owner to upgrade.`, upgradeUrl: null };+ }+ if (/add_seats/.test(raw)) return { text: "Your team has no free seats. Ask the team owner to add seats.", upgradeUrl: null };+ if (/machine_limit/.test(raw)) return { text: "Your team has as many computers as it has seats. Ask the team owner to add seats.", upgradeUrl: null };+ return { text: raw, upgradeUrl: null };}/** What "Add a machine" shows while a paired machine joins its team. */@@ -177,7 +211,8 @@ export function usePairingCode({await adapter.call("sharing.share", { spaceId: `relay:${machine}`, who: `team:${team}`, role: "editor" });setState((s) => ({ ...s, team: { phase: "added", error: null } }));} catch (e: unknown) {- setState((s) => ({ ...s, team: { phase: "failed", error: e instanceof Error ? e.message : String(e) } }));+ const { text, upgradeUrl } = planFailure(e instanceof Error ? e.message : String(e));+ setState((s) => ({ ...s, team: { phase: "failed", error: text, upgradeUrl } }));}};diff --git a/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx b/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsxindex ff2d8deefa..e90437cfec 100644--- a/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx+++ b/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx@@ -106,6 +106,38 @@ describe("Add a computer by link or QR code", () => {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>[] = [];@@ -150,7 +182,7 @@ describe("Add a computer by link or QR code", () => {"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 });+ 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 () => {diff --git a/apps/cua-spaces-web/src/components/add-machine-dialog.tsx b/apps/cua-spaces-web/src/components/add-machine-dialog.tsxindex e3b12e07c8..99c2efc3bb 100644--- a/apps/cua-spaces-web/src/components/add-machine-dialog.tsx+++ b/apps/cua-spaces-web/src/components/add-machine-dialog.tsx@@ -144,6 +144,7 @@ function Notice({ children }: { children: ReactNode }) {/** The link, its QR code, the commands, and how long it lasts. */function PairingPanel({ pairing, machines }: { pairing: PairingHook; machines: Machine[] }) {const [shell, setShell] = useState<Shell>("sh");+ const { openExternal } = useSession();const { phase, code } = pairing;if (phase === "idle" || phase === "minting" || !code) {@@ -167,14 +168,19 @@ function PairingPanel({ pairing, machines }: { pairing: PairingHook; machines: Mreturn (<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>+ <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 isn't on your team yet. ${team.error ?? "Something went wrong."}`: "It shows in your computers."}</span>+ {team?.phase === "failed" && team.upgradeUrl ? (+ <Button size="sm" data-pairing-upgrade="" onClick={() => void openExternal(team.upgradeUrl!).catch(() => {})}>+ Upgrade+ </Button>+ ) : null}</div>);}diff --git a/libs/cua/crates/cua-host/src/pairing.rs b/libs/cua/crates/cua-host/src/pairing.rsindex 1ae13b64c7..36a041b581 100644--- a/libs/cua/crates/cua-host/src/pairing.rs+++ b/libs/cua/crates/cua-host/src/pairing.rs@@ -313,13 +313,18 @@ impl RelayClient {Some(_) => tokio::time::sleep(poll).await,}};- api.finishing_setup(- token,- crate::spaces_api::SETUP_RETRY_WINDOW,- waiting,- || api.add_org_machine(token, org, &machine, "", &name),- )- .await?;+ if let Err(e) = api+ .finishing_setup_org(+ token,+ org,+ crate::spaces_api::SETUP_RETRY_WINDOW,+ waiting,+ || api.add_org_machine(token, org, &machine, "", &name),+ )+ .await+ {+ return Err(api.explain_plan_error(token, org, e).await);+ }Ok(machine)}}diff --git a/libs/cua/crates/cua-host/src/spaces_api.rs b/libs/cua/crates/cua-host/src/spaces_api.rsindex e2014f4c67..01e0fc8f5e 100644--- a/libs/cua/crates/cua-host/src/spaces_api.rs+++ b/libs/cua/crates/cua-host/src/spaces_api.rs@@ -208,6 +208,61 @@ pub fn is_feature_required(e: &Error) -> bool {e.to_string().contains("HTTP 402 (feature_required")}+/// Where an owner buys Teams (team machines, roles, device approval, seats).+pub const BUY_TEAMS_URL: &str = "https://app.cua.ai/buy/teams";++/// Where someone buys Pro.+pub const BUY_PRO_URL: &str = "https://app.cua.ai/buy/pro";++/// How long a team operation keeps retrying a `402 feature_required` when+/// the org does pay (its features are on their way). An org that never paid+/// for Teams does not wait at all.+pub const PAID_RETRY_WINDOW: Duration = Duration::from_secs(20);++/// The feature a `402 feature_required` names (`team_machines`), if `e` is one.+pub fn feature_required_detail(e: &Error) -> Option<String> {+ let text = e.to_string();+ let rest = text.split("HTTP 402 (feature_required").nth(1)?;+ let rest = rest.trim_start_matches(':').trim_start();+ let name: String = rest+ .chars()+ .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')+ .collect();+ Some(name)+}++/// What a plan error says in plain words, or `None` when `e` is not about+/// the plan. Covers `feature_required` (`team_machines`, `team_roles`,+/// `device_approval`), `add_seats` and `machine_limit`. An owner gets the+/// link to buy ([`BUY_TEAMS_URL`], last, on its own so an app can turn it+/// into a button); anyone else is told to ask the owner.+pub fn plan_error_text(e: &Error, owner: bool) -> Option<String> {+ let text = e.to_string();+ let what = if let Some(feature) = feature_required_detail(e) {+ match feature.as_str() {+ "team_machines" => "Team computers need the Teams plan.",+ "team_roles" => "Admin roles need the Teams plan.",+ "device_approval" => "Approving devices needs the Teams plan.",+ "space_sharing" => "Sharing with a team needs the Teams plan.",+ _ => "This needs the Teams plan.",+ }+ } else if text.contains("add_seats") {+ "Your team has no free seats."+ } else if text.contains("machine_limit") {+ "Your team has as many computers as it has seats."+ } else {+ return None;+ };+ let seats = text.contains("add_seats") || text.contains("machine_limit");+ Some(if owner {+ format!("{what} {BUY_TEAMS_URL}")+ } else if seats {+ format!("{what} Ask the team owner to add seats.")+ } else {+ format!("{what} Ask the team owner to upgrade.")+ })+}+/// Whether `e` says Teams are not available on this server (see/// [`TEAMS_NOT_AVAILABLE`]).pub fn is_teams_unavailable(e: &Error) -> bool {@@ -902,6 +957,66 @@ impl SpacesApiClient {}}+ /// [`Self::finishing_setup`] for an operation on `org`. A `402+ /// feature_required` on an org that never paid for Teams (plan free) is+ /// returned at once: nothing is on its way. An org that pays keeps+ /// retrying, for at most [`PAID_RETRY_WINDOW`].+ pub async fn finishing_setup_org<T, F, Fut>(+ &self,+ token: &str,+ org: &str,+ window: Duration,+ mut waiting: impl FnMut(Duration),+ mut op: F,+ ) -> Result<T>+ where+ F: FnMut() -> Fut,+ Fut: std::future::Future<Output = Result<T>>,+ {+ let window = window.min(PAID_RETRY_WINDOW);+ let start = std::time::Instant::now();+ let mut pause = Duration::from_millis(500);+ let mut checked = false;+ loop {+ let res = op().await;+ let Err(e) = &res else { return res };+ if !is_retryable(e) {+ return res;+ }+ if is_feature_required(e) && !checked {+ checked = true;+ let never_paid = matches!(+ self.org(token, org).await,+ Ok(d) if matches!(d.plan.as_str(), "" | "free")+ );+ if never_paid {+ return res;+ }+ }+ let spent = start.elapsed();+ if spent >= window {+ return res;+ }+ waiting(spent);+ let _ = self.entitlements(token).await;+ tokio::time::sleep(pause.min(window.saturating_sub(start.elapsed()))).await;+ pause = (pause * 2).min(Duration::from_secs(8));+ }+ }++ /// Rewrites a plan error of an operation on `org` into plain words (see+ /// [`plan_error_text`]); any other error is returned as is.+ pub async fn explain_plan_error(&self, token: &str, org: &str, e: Error) -> Error {+ if plan_error_text(&e, false).is_none() {+ return e;+ }+ let owner = matches!(self.org(token, org).await, Ok(d) if d.role == "owner");+ match plan_error_text(&e, owner) {+ Some(text) => Error::PermissionDenied(text),+ None => e,+ }+ }+/// The account's Teams: `/v1/me`, then each org's members and pending/// invites. A plain member cannot list invites (403): they read as/// none. An org whose people cannot be read keeps its row without them.@@ -1226,6 +1341,96 @@ mod tests {assert!(is_feature_required(&e), "{e}");}+ #[tokio::test]+ async fn an_org_that_never_paid_does_not_wait() {+ let api = crate::testing::FakeSpacesApi::start().await;+ api.add_account("ada", "sub-ada", "[email protected]");+ let free = api.add_org("free", "Free", "sub-ada", &[]);+ let c = SpacesApiClient::new(&api.url).unwrap();+ let start = std::time::Instant::now();+ let mut waits = 0;+ let e = c+ .finishing_setup_org(+ "ada",+ &free,+ SETUP_RETRY_WINDOW,+ |_| waits += 1,+ || c.add_org_machine("ada", &free, "m1", "linux", ""),+ )+ .await+ .unwrap_err();+ assert!(is_feature_required(&e), "{e}");+ assert_eq!(waits, 0);+ assert!(start.elapsed() < Duration::from_secs(2));++ // An org that pays still waits for its features.+ let paid = api.add_org("acme", "Acme", "sub-ada", &["team_machines"]);+ api.feature_lag(1);+ c.finishing_setup_org(+ "ada",+ &paid,+ SETUP_RETRY_WINDOW,+ |_| waits += 1,+ || c.add_org_machine("ada", &paid, "m1", "linux", ""),+ )+ .await+ .unwrap();+ assert_eq!(waits, 1);+ }++ #[test]+ fn plan_errors_read_in_plain_words() {+ let e = org_error(+ 402,+ r#"{"error":"feature_required","detail":"team_machines"}"#,+ );+ assert_eq!(+ feature_required_detail(&e).as_deref(),+ Some("team_machines")+ );+ assert_eq!(+ plan_error_text(&e, true).unwrap(),+ "Team computers need the Teams plan. https://app.cua.ai/buy/teams"+ );+ assert_eq!(+ plan_error_text(&e, false).unwrap(),+ "Team computers need the Teams plan. Ask the team owner to upgrade."+ );+ for (feature, words) in [+ ("team_roles", "Admin roles need"),+ ("device_approval", "Approving devices needs"),+ ] {+ let e = org_error(+ 402,+ &format!(r#"{{"error":"feature_required","detail":"{feature}"}}"#),+ );+ assert!(plan_error_text(&e, true).unwrap().starts_with(words));+ }+ let e = org_error(402, r#"{"error":"add_seats"}"#);+ assert_eq!(+ plan_error_text(&e, false).unwrap(),+ "Your team has no free seats. Ask the team owner to add seats."+ );+ let e = org_error(403, r#"{"error":"machine_limit"}"#);+ assert!(plan_error_text(&e, true).unwrap().ends_with("/buy/teams"));+ assert_eq!(plan_error_text(&org_error(409, "{}"), true), None);+ }++ #[tokio::test]+ async fn a_plan_error_is_explained_by_the_callers_role() {+ let api = crate::testing::FakeSpacesApi::start().await;+ api.add_account("ada", "sub-ada", "[email protected]");+ let free = api.add_org("free", "Free", "sub-ada", &[]);+ let c = SpacesApiClient::new(&api.url).unwrap();+ let e = c+ .add_org_machine("ada", &free, "m1", "linux", "")+ .await+ .unwrap_err();+ let e = c.explain_plan_error("ada", &free, e).await;+ assert!(!e.to_string().contains("HTTP 402"), "{e}");+ assert!(e.to_string().contains("Teams plan"), "{e}");+ }+#[tokio::test]async fn a_server_without_teams_says_so() {let api = crate::testing::FakeSpacesApi::start().await;diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rsindex f6b1159e9f..ecef1c53e4 100644--- a/libs/cua/crates/cua-spaces/src/share.rs+++ b/libs/cua/crates/cua-spaces/src/share.rs@@ -759,14 +759,19 @@ impl Spaces {.await?;let machine = self.ensure_shared_machine(&canonical).await?;let token = relay.tokens.access_token().await?;- api.finishing_setup(- &token,- cua_host::spaces_api::SETUP_RETRY_WINDOW,- waiting,- || api.add_org_machine_as(&token, &org.id, &machine, &os, &label, role.as_str()),- )- .await- .map_err(team_err)?;+ if let Err(e) = api+ .finishing_setup_org(+ &token,+ &org.id,+ cua_host::spaces_api::SETUP_RETRY_WINDOW,+ waiting,+ || api.add_org_machine_as(&token, &org.id, &machine, &os, &label, role.as_str()),+ )+ .await+ {+ let e = api.explain_plan_error(&token, &org.id, e).await;+ return Err(team_err(e));+ }self.audit_share("share",&canonical,