Skip to content

armgit / cua

Public Imported from GitHub
0

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

fix(spaces): explain a refused new computer and offer a code from another computer (#6710)

cua-agents[bot]327f41c89be3
diff --git a/apps/cua-spaces-desktop/src/bridge/host.ts b/apps/cua-spaces-desktop/src/bridge/host.ts
index b6f23c47fd..dd87d891f7 100644
--- a/apps/cua-spaces-desktop/src/bridge/host.ts
+++ b/apps/cua-spaces-desktop/src/bridge/host.ts
@@ -32,6 +32,10 @@ export interface PresentedFailure {
title: string;
details: string;
actionLabel: string;
+ /** Which failure it is (`HostFailureKind`), for a page that answers it with a screen of its own. */
+ kind?: string;
+ /** The relay's code for a refusal, when it gave one. */
+ refusalCode?: string;
}
/** A method's failure, with the code the page reads. */
@@ -73,6 +77,8 @@ export interface BridgeError {
title?: string;
details?: string;
actionLabel?: string;
+ kind?: string;
+ refusalCode?: string;
}
export type BridgeResponse = { id: string; ok: true; result: unknown } | { id: string; ok: false; error: BridgeError };
@@ -83,6 +89,8 @@ export function reply(id: string, error: Failure): BridgeResponse {
e.title = error.presented.title;
e.details = error.presented.details;
e.actionLabel = error.presented.actionLabel;
+ if (error.presented.kind) e.kind = error.presented.kind;
+ if (error.presented.refusalCode) e.refusalCode = error.presented.refusalCode;
}
return { id, ok: false, error: e };
}
diff --git a/apps/cua-spaces-desktop/src/model/host-failure.ts b/apps/cua-spaces-desktop/src/model/host-failure.ts
index 07d87cbefe..0285d71027 100644
--- a/apps/cua-spaces-desktop/src/model/host-failure.ts
+++ b/apps/cua-spaces-desktop/src/model/host-failure.ts
@@ -9,7 +9,7 @@
// that runs the host service.
import type { PresentedFailure } from "../bridge/host";
-export type HostFailureKind = "download" | "network" | "throttled" | "guiSession" | "signedOut" | "service" | "other";
+export type HostFailureKind = "download" | "network" | "throttled" | "guiSession" | "signedOut" | "service" | "needsProof" | "other";
export interface HostSetupFailure extends PresentedFailure {
kind: HostFailureKind;
@@ -18,6 +18,17 @@ export interface HostSetupFailure extends PresentedFailure {
export const RETRY_LABEL = "Retry";
export const SIGN_IN_LABEL = "Sign In";
+export const USE_CODE_LABEL = "Use a code from another computer";
+
+/** The relay's code for a new computer that came with no proof it is the
+ * owner adding it (`cua_host::NEW_COMPUTER_NEEDS_PROOF`). */
+export const NEW_COMPUTER_NEEDS_PROOF = "new_computer_needs_proof";
+
+/** The relay's code for a refusal, as `cua_host::refusal_code` reads it: the
+ * raw error ends with `[code: <lowercase_word>]`. */
+export function refusalCode(raw: string): string | undefined {
+ return /\s\[code: ([a-z_]+)\]\s*$/.exec(raw)?.[1];
+}
/** What the app calls the computer it runs on, mid-sentence. */
export function thisComputer(platform: NodeJS.Platform): string {
@@ -42,6 +53,8 @@ export function throttledWait(raw: string): number | null | undefined {
/** Which kind of failure the raw setup error is. */
export function classify(raw: string): HostFailureKind {
+ // The relay's own code first: it says which refusal it is, whatever the words.
+ if (refusalCode(raw) === NEW_COMPUTER_NEEDS_PROOF) return "needsProof";
if (throttledWait(raw) !== undefined) return "throttled";
const s = raw.toLowerCase();
const any = (needles: string[]) => needles.some((n) => s.includes(n));
@@ -116,6 +129,12 @@ export function failureWords(kind: HostFailureKind, platform: NodeJS.Platform =
? "if it keeps failing, open Cua Spaces as administrator (right-click it, Run as administrator) and set up access once more."
: `if it keeps failing, restart ${here}.`),
];
+ case "needsProof":
+ return [
+ "Confirm it’s you",
+ `To add ${here} to your account, enter a code from a computer you already added. ` +
+ "On that computer, open Cua Spaces, go to Machines and click Add machine.",
+ ];
case "other":
return [`Couldn’t set up ${here} for access`, "Something went wrong. Try again, or open Details to see what happened."];
}
@@ -124,5 +143,6 @@ export function failureWords(kind: HostFailureKind, platform: NodeJS.Platform =
/** The failure for a raw error (its kind read from the words, or given: the account refused, whatever its words). */
export function presentHostFailure(raw: string, platform: NodeJS.Platform = "darwin", kind: HostFailureKind = classify(raw)): HostSetupFailure {
const [title, message] = failureWords(kind, platform, raw);
- return { kind, title, message, details: raw, actionLabel: kind === "signedOut" ? SIGN_IN_LABEL : RETRY_LABEL };
+ const actionLabel = kind === "signedOut" ? SIGN_IN_LABEL : kind === "needsProof" ? USE_CODE_LABEL : RETRY_LABEL;
+ return { kind, title, message, details: raw, actionLabel, refusalCode: refusalCode(raw) };
}
diff --git a/apps/cua-spaces-desktop/test/host-failure.test.ts b/apps/cua-spaces-desktop/test/host-failure.test.ts
index 4d45feace6..5eb89ab510 100644
--- a/apps/cua-spaces-desktop/test/host-failure.test.ts
+++ b/apps/cua-spaces-desktop/test/host-failure.test.ts
@@ -6,7 +6,8 @@
// 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 machine.
import { describe, expect, it } from "vitest";
-import { classify, presentHostFailure } from "../src/model/host-failure";
+import { classify, presentHostFailure, refusalCode } from "../src/model/host-failure";
+import { Failure, reply } from "../src/bridge/host";
const MISSING_RELEASE =
"http: download: https://github.com/trycua/cua/releases/download/cua-spacesd-v0.2.0/cua-spacesd-aarch64-apple-darwin.tar.gz: HTTP 404";
@@ -98,6 +99,28 @@ describe("host setup failures", () => {
expect(f.details).toBe("something odd failed\nmore");
});
+ it("a new computer that needs proof asks for a code from another computer, in plain words", () => {
+ const raw = "permission denied: relay: add computers from a computer you already added, or with a pairing code [code: new_computer_needs_proof]";
+ const f = presentHostFailure(raw, "win32");
+ expect(f.kind).toBe("needsProof");
+ expect(f.refusalCode).toBe("new_computer_needs_proof");
+ expect(f.title).toBe("Confirm it’s you");
+ expect(f.message).toContain("To add this PC to your account, enter a code from a computer you already added.");
+ expect(f.actionLabel).toBe("Use a code from another computer");
+ expect(f.details).toBe(raw);
+ for (const word of ["relay", "enrol", "MFA", "token", "pairing"]) expect(`${f.title} ${f.message}`).not.toContain(word);
+ // The kind and the code reach the page.
+ const e = reply("1", new Failure("failed", f.message, f));
+ expect(e).toMatchObject({ ok: false, error: { kind: "needsProof", refusalCode: "new_computer_needs_proof", actionLabel: "Use a code from another computer" } });
+ });
+
+ it("reads a refusal code only from the end of the error", () => {
+ expect(refusalCode("relay: no [code: phone]")).toBe("phone");
+ expect(refusalCode("relay: that host is shared with you to watch only")).toBeUndefined();
+ expect(refusalCode("relay: x [code: Bad-Code]")).toBeUndefined();
+ expect(classify("relay: x [code: phone]")).toBe("other");
+ });
+
it("a port number is not a status code", () => {
expect(classify("listen 0.0.0.0:14041 failed")).toBe("other");
});
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift
index 877b91885d..78ba2d866e 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift
@@ -24,7 +24,26 @@ public struct HostSetupFailure: Equatable, Sendable {
/// of them, or with a pairing code (the relay's rule for an
/// account with phone support).
case addFromAnotherComputer
+ /// The account already has other computers, and this one came with
+ /// no proof that it is the owner adding it (the relay's
+ /// `new_computer_needs_proof`): a code from one of them adds it.
+ case needsProof
case other
+
+ /// The kind's name on the bridge (`HostFailure.kind` on the page).
+ public var wireName: String {
+ switch self {
+ case .download: "download"
+ case .network: "network"
+ case .throttled: "throttled"
+ case .guiSession: "guiSession"
+ case .signedOut: "signedOut"
+ case .service: "service"
+ case .addFromAnotherComputer: "addFromAnotherComputer"
+ case .needsProof: "needsProof"
+ case .other: "other"
+ }
+ }
}
public let kind: Kind
@@ -32,12 +51,30 @@ public struct HostSetupFailure: Equatable, Sendable {
public let message: String
/// The raw error, as the setup reported it.
public let details: String
+ /// The relay's code for the refusal (`[code: …]` in the raw error), when
+ /// it gave one: what the page matches on, whatever the words.
+ public var refusalCode: String? { Self.refusalCode(details) }
public static let retryLabel = "Retry"
public static let retryingLabel = "Retrying\u{2026}"
public static let detailsLabel = "Details"
public static let copyLabel = "Copy"
public static let signInLabel = "Sign In"
+ public static let useCodeLabel = "Use a code from another computer"
+
+ /// The relay's code `cua_host::refusal_code` reads: the raw error ends
+ /// with `[code: <lowercase_word>]`.
+ static func refusalCode(_ raw: String) -> String? {
+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard let open = trimmed.range(of: " [code: ", options: .backwards), trimmed.hasSuffix("]") else { return nil }
+ let code = trimmed[open.upperBound..<trimmed.index(before: trimmed.endIndex)]
+ guard !code.isEmpty, code.allSatisfy({ $0 == "_" || ("a"..."z").contains($0) }) else { return nil }
+ return String(code)
+ }
+
+ /// The relay's code for a new computer that needs proof it is the owner
+ /// adding it (`cua_host::NEW_COMPUTER_NEEDS_PROOF`).
+ public static let newComputerNeedsProof = "new_computer_needs_proof"
/// A failure whose kind the error itself says (the account refused,
/// whatever its words), with the raw error as details.
@@ -48,7 +85,13 @@ public struct HostSetupFailure: Equatable, Sendable {
/// The failure's button: Sign In when the account is what is missing
/// (it signs in inline, then sets up), Retry otherwise.
- public var actionLabel: String { kind == .signedOut ? Self.signInLabel : Self.retryLabel }
+ public var actionLabel: String {
+ switch kind {
+ case .signedOut: Self.signInLabel
+ case .needsProof: Self.useCodeLabel
+ default: Self.retryLabel
+ }
+ }
/// Maps the raw setup error to what the sheet shows.
public static func presenting(_ raw: String) -> HostSetupFailure {
@@ -88,6 +131,9 @@ public struct HostSetupFailure: Equatable, Sendable {
}
static func classify(_ raw: String) -> Kind {
+ // The relay's own code first: it says which refusal it is, whatever
+ // the words around it.
+ if refusalCode(raw) == newComputerNeedsProof { return .needsProof }
if throttledWait(raw) != nil { return .throttled }
let s = raw.lowercased()
func any(_ needles: [String]) -> Bool { needles.contains { s.contains($0) } }
@@ -152,6 +198,10 @@ public struct HostSetupFailure: Equatable, Sendable {
return ("Add this Mac from another computer",
"Your account already has computers, so a new Mac is added from one of them or with a pairing code. "
+ "Open Cua Spaces on one of your computers and add this Mac from there.")
+ case .needsProof:
+ return ("Confirm it\u{2019}s you",
+ "To add this Mac to your account, enter a code from a computer you already added. "
+ + "On that computer, open Cua Spaces, go to Machines and click Add machine.")
case .other:
return ("Couldn\u{2019}t set up this Mac for access",
"Something went wrong. Try again, or open Details to see what happened.")
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 178aa1a324..c50303baf4 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -221,8 +221,9 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
let code: String
let message: String
/// A failed host setup or This machine button in plain words: the
- /// error then also carries its `title`, `details` (the raw error)
- /// and `actionLabel` (Retry, or Sign In).
+ /// error then also carries its `title`, `details` (the raw error),
+ /// `actionLabel` (Retry, Sign In, or Use a code from another
+ /// computer), its `kind` and the relay's `refusalCode`, if any.
var presented: HostSetupFailure?
static func unimplemented(_ method: String) -> Failure {
Failure(code: "unimplemented", message: "\(method) is not available in this host")
@@ -285,6 +286,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
e["title"] = p.title
e["details"] = p.details
e["actionLabel"] = p.actionLabel
+ e["kind"] = p.kind.wireName
+ if let code = p.refusalCode { e["refusalCode"] = code }
}
return ["id": id, "ok": false, "error": e]
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift
index 1c094c0a01..9f3dfb1ff4 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift
@@ -218,6 +218,32 @@ struct HostSetupFailureTests {
model.openForm()
#expect(model.setupFailure == nil)
}
+
+ /// The relay refuses a new computer that came with no proof it is the
+ /// owner adding it; the error keeps the relay's code, and the page asks
+ /// the person to confirm it is them with a code from another computer.
+ @Test func aNewComputerThatNeedsProofAsksForACodeInPlainWords() {
+ let raw = "permission denied: relay: add computers from a computer you already added, "
+ + "or with a pairing code [code: new_computer_needs_proof]"
+ let f = HostSetupFailure.presenting(raw)
+ #expect(f.kind == .needsProof)
+ #expect(f.refusalCode == "new_computer_needs_proof")
+ #expect(f.title == "Confirm it\u{2019}s you")
+ #expect(f.message.contains("enter a code from a computer you already added"))
+ #expect(f.actionLabel == "Use a code from another computer")
+ #expect(f.details == raw, "details stay raw")
+ for word in ["relay", "enrol", "MFA", "token", "pairing"] {
+ #expect(!f.title.contains(word) && !f.message.contains(word), "no jargon: \(word)")
+ }
+ }
+
+ @Test func aRefusalCodeIsReadOnlyFromTheEnd() {
+ #expect(HostSetupFailure.refusalCode("relay: no [code: phone]") == "phone")
+ #expect(HostSetupFailure.refusalCode("relay: that host is shared with you to watch only") == nil)
+ #expect(HostSetupFailure.refusalCode("relay: x [code: Bad-Code]") == nil)
+ #expect(HostSetupFailure.presenting("relay: x [code: phone]").kind == .other)
+ #expect(HostSetupFailure.presenting("relay: x [code: phone]").refusalCode == "phone")
+ }
}
/// A host whose setup can fail or wait until released (no service, no
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
index 1580563178..4c2dcb96f8 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
@@ -658,6 +658,22 @@ struct WebUIHostTests {
}
}
+ @Test func aRefusedNewComputerCarriesItsKindAndCodeToThePage() throws {
+ let f = HostSetupFailure.presenting(
+ "relay: add computers from a computer you already added, or with a pairing code [code: new_computer_needs_proof]")
+ let e = try #require(WebUIBridge.reply(id: "1", error: WebUIBridge.hostFailure(f))["error"] as? [String: Any])
+ #expect(e["kind"] as? String == "needsProof")
+ #expect(e["refusalCode"] as? String == "new_computer_needs_proof")
+ #expect(e["title"] as? String == "Confirm it\u{2019}s you")
+ #expect(e["actionLabel"] as? String == "Use a code from another computer")
+ // Any other failure says its kind, and no code it does not have.
+ let other = try #require(
+ WebUIBridge.reply(id: "2", error: WebUIBridge.hostFailure(HostSetupFailure.presenting("boom")))["error"]
+ as? [String: Any])
+ #expect(other["kind"] as? String == "other")
+ #expect(other["refusalCode"] == nil)
+ }
+
@Test func aFailedButtonIsWordedWithTheRawErrorAsDetails() async throws {
let host = FixtureHost()
let (bridge, _) = bridge(host: host)
diff --git a/apps/cua-spaces-web/src/__tests__/first-run-new.test.tsx b/apps/cua-spaces-web/src/__tests__/first-run-new.test.tsx
index 16dace08ca..ff81ace4eb 100644
--- a/apps/cua-spaces-web/src/__tests__/first-run-new.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/first-run-new.test.tsx
@@ -86,7 +86,19 @@ describe("screen 2, signed in", () => {
drawWhere({ ...base, thisState: "failed", addError: "The relay didn't answer." }, { onAddThis });
expect(document.querySelector("[data-new-run-this-status]")!.textContent).toBe("Couldn't add it to your account. The relay didn't answer.");
fireEvent.click(document.querySelector("[data-new-run-add-this=retry-add]")!);
- expect(onAddThis).toHaveBeenCalled();
+ expect(onAddThis).toHaveBeenCalledWith("retry-add");
+ });
+
+ it("when the account wants proof, asks to confirm it's you with a code from another computer", () => {
+ const onAddThis = vi.fn();
+ const message = "To add this Mac to your account, enter a code from a computer you already added. On that computer, open Cua Spaces, go to Machines and click Add machine.";
+ drawWhere({ ...base, thisState: "failed", addError: message, addNeedsProof: true }, { onAddThis });
+ expect(document.querySelector("[data-new-run-this-status]")!.textContent).toBe(`Confirm it's you. ${message}`);
+ expect(document.querySelector("[data-new-run-add-this=retry-add]")).toBeNull();
+ const button = document.querySelector<HTMLElement>("[data-new-run-add-this=use-code]")!;
+ expect(button.textContent).toBe("Use a code from another computer");
+ fireEvent.click(button);
+ expect(onAddThis).toHaveBeenCalledWith("use-code");
});
});
diff --git a/apps/cua-spaces-web/src/bridge/adapter.ts b/apps/cua-spaces-web/src/bridge/adapter.ts
index 1a8164067f..fd204be499 100644
--- a/apps/cua-spaces-web/src/bridge/adapter.ts
+++ b/apps/cua-spaces-web/src/bridge/adapter.ts
@@ -95,6 +95,12 @@ export interface PresentedFailure {
title?: string;
details?: string;
actionLabel?: string;
+ /** Which failure it is (`HostSetupFailure.Kind`): `needsProof` is a new
+ * computer the account wants proof for, answered with a code from
+ * another computer. */
+ kind?: string;
+ /** The relay's code for a refusal (`new_computer_needs_proof`, ...), when it gave one. */
+ refusalCode?: string;
}
/** A host answered with an error. `code` is the host's, when it gave one. */
diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
index 13df0d7a3c..749e230320 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
@@ -549,7 +549,7 @@ export function createWebkitAdapter(
else if (r.ok) resolve(r.result as T);
else {
const e = r.error;
- reject(new HostError(e?.message ?? `${method} failed`, e?.code, e && { title: e.title, details: e.details, actionLabel: e.actionLabel }));
+ reject(new HostError(e?.message ?? `${method} failed`, e?.code, e && { title: e.title, details: e.details, actionLabel: e.actionLabel, kind: e.kind, refusalCode: e.refusalCode }));
}
},
(e: unknown) => {
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index cb3327cdbe..9f0807530b 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -147,7 +147,7 @@ export { useWindowDropTarget } from "./window-drop";
export { useSpaceFiles, parseDropped, dropSendingText, dropSentText, sendFiles, splitDrop, type DropStatus, type SpaceFilesHook } from "./space-files";
export { agentRunLines, useDesktopCover, useSpaceDetail, type AgentRunLine, type DetailFor, type DetailReadings, type PipOutcome, type SpaceDetailHook } from "./space-detail";
export type * from "./ops/space-detail";
-export { useThisMachine, type HostFailure, type HostFormView as HostSetupFormView, type ThisMachineHook } from "./this-machine";
+export { isNeedsProof, useThisMachine, type HostFailure, type HostFormView as HostSetupFormView, type ThisMachineHook } from "./this-machine";
export type { HostFormAction, HostSetupRequest } from "./ops/host-setup";
export type { TelemetrySignal } from "./ops/telemetry";
export { useStartup, type StartupHook } from "./startup";
diff --git a/apps/cua-spaces-web/src/bridge/join.ts b/apps/cua-spaces-web/src/bridge/join.ts
index 6d54ed32d1..976a08b69e 100644
--- a/apps/cua-spaces-web/src/bridge/join.ts
+++ b/apps/cua-spaces-web/src/bridge/join.ts
@@ -8,9 +8,10 @@
* (`host.joinWithCode`) and answers once the machine has joined.
*/
-import { useCallback, useState } from "react";
+import { useCallback, useContext, useState } from "react";
import { isUnsupported } from "./adapter";
+import { BridgeContext } from "./BridgeProvider";
import { useBridge } from "./hooks";
import { plainJoinError } from "./friendly-errors";
import { normalizePairingCode, pairingLinkRelay } from "./pairing-code";
@@ -36,6 +37,7 @@ export function useJoinWithCode({ onJoined }: { onJoined?: () => void } = {}): J
const { data: adapter } = useBridge();
const [phase, setPhase] = useState<JoinPhase>("idle");
const [error, setError] = useState<string | null>(null);
+ const thisMachine = useContext(BridgeContext)?.store?.thisMachine;
const join = useCallback(
async (input: string, relay?: string | null) => {
@@ -51,6 +53,8 @@ export function useJoinWithCode({ onJoined }: { onJoined?: () => void } = {}): J
try {
await adapter.call("host.joinWithCode", { code, relay: relay ?? pairingLinkRelay(input) });
setPhase("joined");
+ // A setup refused for want of proof ("Use a code from another computer") is answered.
+ thisMachine?.joinedWithCode();
onJoined?.();
return true;
} catch (e) {
@@ -59,7 +63,7 @@ export function useJoinWithCode({ onJoined }: { onJoined?: () => void } = {}): J
return false;
}
},
- [adapter, onJoined],
+ [adapter, onJoined, thisMachine],
);
return { phase, error, join, reset: useCallback(() => (setPhase("idle"), setError(null)), []) };
diff --git a/apps/cua-spaces-web/src/bridge/this-machine.ts b/apps/cua-spaces-web/src/bridge/this-machine.ts
index 15f6dadf1b..3bb95a3b86 100644
--- a/apps/cua-spaces-web/src/bridge/this-machine.ts
+++ b/apps/cua-spaces-web/src/bridge/this-machine.ts
@@ -61,10 +61,20 @@ export interface HostFailure {
message: string;
/** The raw error, unchanged. */
details?: string;
- /** The retry button: "Retry", or "Sign In" when the account is missing. */
+ /** The button: "Retry", "Sign In" when the account is missing, or "Use a
+ * code from another computer" when the account wants proof (`needsProof`). */
actionLabel?: string;
+ /** Which failure it is, as the host classed it (`HostSetupFailure.Kind`). */
+ kind?: string;
+ /** The relay's code for a refusal, when it gave one. */
+ refusalCode?: string;
}
+/** The failure is a new computer the account wants proof for: its button
+ * opens "Enter a code" instead of trying again. */
+export const NEEDS_PROOF = "needsProof";
+export const isNeedsProof = (f: HostFailure | null | undefined): boolean => f?.kind === NEEDS_PROOF;
+
export interface ThisMachineState {
/** The setup form's state; null while the page shows. */
form: HostFormState | null;
@@ -84,7 +94,7 @@ const IDLE: ThisMachineState = { form: null, busy: false, error: null, setupErro
export function hostFailure(e: unknown): HostFailure {
const message = e instanceof Error ? e.message : String(e);
const p = e instanceof HostError ? e.presented : undefined;
- if (p) return { title: p.title, message, details: p.details, actionLabel: p.actionLabel };
+ if (p) return { title: p.title, message, details: p.details, actionLabel: p.actionLabel, ...(p.kind ? { kind: p.kind } : {}), ...(p.refusalCode ? { refusalCode: p.refusalCode } : {}) };
// A host that only says the error: the server's "slow down" in plain words.
const throttled = plainThrottleError(message);
return throttled ? { title: "Too many attempts right now", message: throttled.replace(/^Too many attempts right now\. Wait (\d+) (seconds?), then try again\./, "Trying again in $1 $2.").replace("Wait a few seconds, then try again.", "Trying again in a few seconds."), details: message } : { message };
@@ -116,6 +126,14 @@ export class ThisMachineStore {
for (const l of [...this.listeners]) l();
}
+ /** This computer joined another way (a code from another computer): the
+ * failure that asked for it is answered, so it no longer shows. */
+ joinedWithCode(): void {
+ this.failedRequest = null;
+ this.failedAction = null;
+ this.set({ error: null, setupError: null, form: null });
+ }
+
/** Opens the form, with a setup choice's profile (`desktop`, `spare`). */
openForm(profile?: string): void {
let form = hostFormInitial(this.core);
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index dc4ca6f22a..d6f7069d82 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -16,8 +16,9 @@
*
* `code`: `unimplemented`, `bad_args`, `not_found`, `cancelled`,
* `native_only`, `forbidden` or `failed`. A failed host setup or This
- * machine button also says `title`, `details` (the raw error) and
- * `actionLabel` (`HostSetupFailure`), and `message` is then the plain words.
+ * machine button also says `title`, `details` (the raw error),
+ * `actionLabel`, `kind` (`HostSetupFailure.Kind`, e.g. `needsProof`) and the
+ * relay's `refusalCode` when it gave one, and `message` is then the plain words.
*
* Host -> page events: `window.dispatchEvent(new CustomEvent("cua:event",
* { detail: { event, payload } }))`, where `event` is one of `WEBKIT_EVENTS`.
@@ -277,7 +278,7 @@ export interface WebkitRequest {
export type WebkitResponse =
| { id: string; ok: true; result: unknown }
- | { id: string; ok: false; error: { code: string; message: string; title?: string; details?: string; actionLabel?: string } };
+ | { id: string; ok: false; error: { code: string; message: string; title?: string; details?: string; actionLabel?: string; kind?: string; refusalCode?: string } };
/** `CustomEvent("cua:event").detail`. */
export interface WebkitEventDetail {
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.tsx
index e599ddcec6..c3bad97263 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
@@ -174,6 +174,72 @@ describe("a failed This machine button", () => {
});
});
+describe("a new computer the account wants proof for", () => {
+ /** The relay refused this Mac (no enrolled device, no sign-in with a second factor, no code). */
+ const refused = () =>
+ new HostError("To add this Mac to your account, enter a code from a computer you already added. On that computer, open Cua Spaces, go to Machines and click Add machine.", "failed", {
+ title: "Confirm it’s you",
+ details: "permission denied: relay: add computers from a computer you already added, or with a pairing code [code: new_computer_needs_proof]",
+ actionLabel: "Use a code from another computer",
+ kind: "needsProof",
+ refusalCode: "new_computer_needs_proof",
+ });
+
+ it("says confirm it's you in plain words and offers a code from another computer, not Retry", async () => {
+ const { adapter, actions } = host(refused);
+ const useCode = vi.fn();
+ render(
+ <BridgeProvider adapter={adapter} core={unavailableCore("test: no core")}>
+ <Press action="stop-sharing" />
+ <ThisMachineExtras panel={sharing} part="alerts" onUseCode={useCode} />
+ </BridgeProvider>,
+ );
+ await act(() => new Promise((r) => setTimeout(r, 10)));
+ fireEvent.click(document.querySelector('[data-press="stop-sharing"]')!);
+ const failure = await waitFor(() => {
+ const f = document.querySelector<HTMLElement>('[data-host-failure="needs-proof"]');
+ if (!f) throw new Error("no failure");
+ return f;
+ });
+ expect(failure.querySelector("[data-host-failure-title]")?.textContent).toBe("Confirm it’s you");
+ const message = failure.querySelector("[data-host-failure-message]")?.textContent ?? "";
+ expect(message).toMatch(/enter a code from a computer you already added/);
+ for (const word of ["relay", "enrol", "MFA", "token"]) expect(message).not.toContain(word);
+ expect(failure.querySelector("[data-host-retry]")).toBeNull();
+ const button = failure.querySelector<HTMLButtonElement>("[data-host-use-code]")!;
+ expect(button.textContent).toBe("Use a code from another computer");
+ fireEvent.click(button);
+ expect(useCode).toHaveBeenCalledTimes(1);
+ expect(actions).toEqual(["stop-sharing"]);
+ // The raw refusal stays under Details.
+ fireEvent.click(failure.querySelector("[data-host-details]")!);
+ expect(failure.querySelector("[data-host-details-text]")?.textContent).toContain("[code: new_computer_needs_proof]");
+ });
+
+ it("a code that joined answers it, so it no longer shows", async () => {
+ const { adapter } = host(refused);
+ const store = new ThisMachineStore(adapter, unavailableCore("test"), async () => {});
+ await store.run("stop-sharing");
+ expect(store.get().error?.kind).toBe("needsProof");
+ expect(store.get().error?.refusalCode).toBe("new_computer_needs_proof");
+ store.joinedWithCode();
+ expect(store.get().error).toBeNull();
+ });
+
+ it("without a way to enter a code, falls back to Retry", () => {
+ render(
+ <HostSetupForm
+ view={form}
+ host={{ send: () => {}, submit: async () => false, closeForm: () => {} }}
+ failure={{ title: "Confirm it’s you", message: "To add this Mac…", details: "x [code: new_computer_needs_proof]", actionLabel: "Use a code from another computer", kind: "needsProof" }}
+ onRetry={() => {}}
+ />,
+ );
+ expect(document.querySelector("[data-host-use-code]")).toBeNull();
+ expect(document.querySelector("[data-host-retry]")?.textContent).toBe("Retry");
+ });
+});
+
/* ---- Host setup --------------------------------------------------------------------- */
const form: HostSetupFormView = {
diff --git a/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx b/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx
index 79743ddea5..ac416479f8 100644
--- a/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx
+++ b/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx
@@ -13,7 +13,7 @@ import { useNavigate } from "@tanstack/react-router";
import { CheckIcon, ChevronRightIcon, CopyIcon, LoaderCircleIcon, MonitorIcon, PlusIcon, ShieldIcon, UserPlusIcon } from "lucide-react";
import { useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
-import { folderLabel, newPendingId, useMachines, useSession, useSettings, useSpaces, type SignInPhase } from "@/bridge";
+import { folderLabel, isNeedsProof, newPendingId, useMachines, useSession, useSettings, useSpaces, type SignInPhase } from "@/bridge";
import { BridgeContext } from "@/bridge/BridgeProvider";
import { useAppPermissions, type AppPermissionsState } from "@/bridge/app-permissions";
import { readFirstRun, useFirstRunSaved, writeFirstRun } from "@/bridge/first-run";
@@ -308,7 +308,7 @@ export function WhereScreen({
}: {
view: WhereView;
onToggle: (id: string) => void;
- onAddThis: () => void;
+ onAddThis: (action: "add" | "retry-add" | "use-code") => void;
onSignIn: () => void;
onAddAnother: () => void;
onSeparate: () => void;
@@ -347,7 +347,7 @@ export function WhereScreen({
className={cn(GLASS_CHIP, "mr-1 h-[30px] px-3.5 text-[13.5px]")}
onClick={(e) => {
e.stopPropagation();
- onAddThis();
+ onAddThis(t.action!.id);
}}
data-new-run-add-this={t.action.id}
>
@@ -662,8 +662,11 @@ export function NewFirstRun() {
const [connectError, setConnectError] = useState<string | null>(null);
const [thisState, setThisState] = useState<"adding" | "added" | "failed">("adding");
const [addError, setAddError] = useState<string | null>(null);
+ const [addNeedsProof, setAddNeedsProof] = useState(false);
const [explain, setExplain] = useState(false);
const [addOpen, setAddOpen] = useState(false);
+ // "Use a code from another computer": the sheet opens on "Enter a code".
+ const [addEnter, setAddEnter] = useState(false);
const [appsOpen, setAppsOpen] = useState(false);
const mainRef = useRef<HTMLElement>(null);
useFadeUnder(mainRef, s.screen);
@@ -721,10 +724,15 @@ export function NewFirstRun() {
const n = ++addRun.current;
setThisState("adding");
setAddError(null);
+ setAddNeedsProof(false);
const ok = await store.addThisComputer(session.data?.identity ?? null).catch(() => false);
if (n !== addRun.current) return;
setThisState(ok ? "added" : "failed");
- if (!ok) setAddError(store.thisMachine.get().setupError?.message ?? null);
+ if (!ok) {
+ const failure = store.thisMachine.get().setupError;
+ setAddError(failure?.message ?? null);
+ setAddNeedsProof(isNeedsProof(failure));
+ }
};
useEffect(() => {
if (s.screen === "where" && signedIn) void addThis();
@@ -807,6 +815,7 @@ export function NewFirstRun() {
thisState: signedIn ? thisState : ("signed-out" as const),
addedInRun: s.addedInRun,
addError,
+ addNeedsProof,
model: machines.data?.find((m) => m.current)?.model ?? null,
machines: machines.data ?? null,
picks: s.picks,
@@ -927,7 +936,13 @@ export function NewFirstRun() {
<WhereScreen
view={where}
onToggle={(id) => save({ picks: togglePick(s.picks, id, where.others ?? []) })}
- onAddThis={() => (signedIn ? void addThis() : startSignIn())}
+ onAddThis={(action) => {
+ if (action === "use-code") {
+ setAddEnter(true);
+ setAddOpen(true);
+ } else if (signedIn) void addThis();
+ else startSignIn();
+ }}
onSignIn={startSignIn}
onAddAnother={() => setAddOpen(true)}
onSeparate={makeSeparate}
@@ -1002,7 +1017,21 @@ export function NewFirstRun() {
<div className="relative z-20 flex h-[38px] shrink-0 flex-col justify-end" data-new-run-dots-row="">
{dots ? <StepDots dots={dots} onGo={goDot} /> : null}
</div>
- <AddComputerSheet open={addOpen} onOpenChange={setAddOpen} />
+ <AddComputerSheet
+ open={addOpen}
+ onOpenChange={(open) => {
+ setAddOpen(open);
+ if (open) return;
+ setAddEnter(false);
+ // Joined with a code: this computer is in the account now.
+ if (addNeedsProof && store?.thisMachine.get().setupError === null) {
+ setAddNeedsProof(false);
+ setAddError(null);
+ setThisState("added");
+ }
+ }}
+ initialView={addEnter ? "enter" : "pick"}
+ />
</div>
);
}
diff --git a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
index e3e13bb3aa..b632c4c503 100644
--- a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
+++ b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
+import { useState } from "react";
+
import { setFlagOverride, useAbout, useBridge, useExperiments, useFlag, useMachines, useSession, useSettings, useThisMachine, type SettingsRow as CoreRow } from "@/bridge";
import { aboutView } from "@/bridge/settings-derive";
import { SettingsGroup } from "@/components/settings-group";
@@ -9,6 +11,7 @@ import { SharingSettings } from "@/components/links/sharing-settings";
import { SettingRow } from "@/components/ui/grouped";
import { CoreSettingsRow } from "@/components/settings/core-section";
import { RuntimeKindRows } from "@/components/settings/runtime-rows";
+import { AddComputerSheet } from "@/components/add-computer-sheet";
import { HostSetupForm } from "@/components/this-machine";
import { Button } from "@/components/ui/button";
import { toastError } from "@/components/ui/toast";
@@ -214,10 +217,13 @@ function OwnConnection() {
const { data: machines } = useMachines();
const host = useThisMachine(session?.identity ?? null);
const form = host.formView?.advancedOpen ? host.formView : null;
+ // "Use a code from another computer", when the server wants proof it's the owner adding this computer.
+ const [enterCode, setEnterCode] = useState(false);
return (
<SettingsGroup title="Connection">
+ <AddComputerSheet open={enterCode} onOpenChange={setEnterCode} initialView="enter" />
{form ? (
- <HostSetupForm view={form} host={host} failure={host.setupError} progress={machines?.find((m) => m.current)?.hostProgress} onRetry={() => void host.retrySetUp()} />
+ <HostSetupForm view={form} host={host} failure={host.setupError} progress={machines?.find((m) => m.current)?.hostProgress} onRetry={() => void host.retrySetUp()} onUseCode={() => setEnterCode(true)} />
) : (
<SettingRow
data-self-hosting=""
diff --git a/apps/cua-spaces-web/src/components/this-machine.tsx b/apps/cua-spaces-web/src/components/this-machine.tsx
index a26389eee4..0a5509f4c6 100644
--- a/apps/cua-spaces-web/src/components/this-machine.tsx
+++ b/apps/cua-spaces-web/src/components/this-machine.tsx
@@ -1,10 +1,11 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-import { CheckIcon, ChevronDownIcon, ChevronRightIcon, CopyIcon, LoaderCircleIcon, TriangleAlertIcon } from "lucide-react";
+import { CheckIcon, ChevronDownIcon, ChevronRightIcon, CopyIcon, LoaderCircleIcon, ShieldCheckIcon, TriangleAlertIcon } from "lucide-react";
import { useEffect, useRef, useState, type ReactNode } from "react";
import {
+ isNeedsProof,
useSession,
useThisMachine,
type HostAccessRow,
@@ -38,9 +39,10 @@ type HostLog = "access" | "activity";
* the owner now (`alerts`: a running setup's progress, permissions to
* grant, a failed action, a log that does not verify) and the access and
* Spaces logs (`logs`, under Details). The switches, Spaces, Details and
- * Remove are `machines_view::view`'s, drawn by the page.
+ * Remove are `machines_view::view`'s, drawn by the page. `onUseCode` opens
+ * "Enter a code": the answer to a failure the account wants proof for.
*/
-export function ThisMachineExtras({ panel, progress, part }: { panel: HostPanelView | null; progress?: string; part?: "alerts" | "logs" }) {
+export function ThisMachineExtras({ panel, progress, part, onUseCode }: { panel: HostPanelView | null; progress?: string; part?: "alerts" | "logs"; onUseCode?: () => void }) {
const { data: session } = useSession();
const host = useThisMachine(session?.identity ?? null);
// Screen Recording and Accessibility: Cua Spaces' own, the same rows and live status as the first run and the Cua Driver page.
@@ -50,7 +52,7 @@ export function ThisMachineExtras({ panel, progress, part }: { panel: HostPanelV
if (!part) {
return host.formView ? (
- <HostSetupForm view={host.formView} host={host} failure={host.setupError} progress={progress} onRetry={() => void host.retrySetUp()} />
+ <HostSetupForm view={host.formView} host={host} failure={host.setupError} progress={progress} onRetry={() => void host.retrySetUp()} onUseCode={onUseCode} />
) : null;
}
if (!panel) return null;
@@ -88,7 +90,7 @@ export function ThisMachineExtras({ panel, progress, part }: { panel: HostPanelV
// the raw error under Details.
<GroupedSection className="mb-6">
<div className="px-4 py-3">
- <FailureView failure={host.error} retrying={host.busy} onRetry={() => void host.retry()} />
+ <FailureView failure={host.error} retrying={host.busy} onRetry={() => void host.retry()} onUseCode={onUseCode} />
</div>
</GroupedSection>
) : null}
@@ -141,19 +143,22 @@ const TEXT_ACTION: Record<string, (text: string) => Parameters<FormHost["send"]>
/** The host setup form: the core's fields in order, Advanced ones under
* Advanced. A failed setup shows in plain words with Retry (the same
* request again) and the raw error under Details; `progress` is what a
- * running setup waits for (the sign-in in the browser). */
+ * running setup waits for (the sign-in in the browser). `onUseCode`
+ * answers a setup the account wants proof for (see `FailureView`). */
export function HostSetupForm({
view,
host,
failure,
progress,
onRetry,
+ onUseCode,
}: {
view: HostSetupFormView;
host: FormHost;
failure?: HostFailure | null;
progress?: string;
onRetry?: () => void;
+ onUseCode?: () => void;
}) {
const basic = view.fields.filter((f) => !f.advanced);
const advanced = view.fields.filter((f) => f.advanced);
@@ -180,7 +185,7 @@ export function HostSetupForm({
))}
{failure && onRetry ? (
<div data-host-form-error className="px-4 py-2.5">
- <FailureView failure={failure} retrying={view.busy} onRetry={onRetry} />
+ <FailureView failure={failure} retrying={view.busy} onRetry={onRetry} onUseCode={onUseCode} />
</div>
) : view.error ? (
<div data-host-form-error className="flex items-start gap-2 px-4 py-2.5 text-[13px] text-destructive">
@@ -335,14 +340,21 @@ function Progress({ text }: { text: string }) {
/** A failed setup or button, as the SwiftUI app's `HostSetupFailureView`:
* a warning and a short title, Retry, one line saying what to do, and the
- * raw error under a collapsed Details (selectable, with Copy). */
-export function FailureView({ failure, retrying, onRetry }: { failure: HostFailure; retrying: boolean; onRetry: () => void }) {
+ * raw error under a collapsed Details (selectable, with Copy).
+ *
+ * A new computer the account wants proof for (`needsProof`: the relay
+ * refused it with no enrolled device, no sign-in with a second factor and no
+ * pairing code) is not something to retry: it says "Confirm it's you" and
+ * its button, "Use a code from another computer", calls `onUseCode` (the
+ * page's "Enter a code"). Without `onUseCode` it falls back to Retry. */
+export function FailureView({ failure, retrying, onRetry, onUseCode }: { failure: HostFailure; retrying: boolean; onRetry: () => void; onUseCode?: () => void }) {
+ const proof = isNeedsProof(failure) && Boolean(onUseCode);
const [open, setOpen] = useState(false);
const [copied, setCopied] = useState(false);
const details = failure.details && failure.details !== failure.message ? failure.details : null;
// One automatic retry per setup: a second throttle waits for the user.
const autoRetried = useRef(false);
- const wait = autoRetried.current ? null : throttleSeconds(failure.details ?? failure.message);
+ const wait = autoRetried.current || proof ? null : throttleSeconds(failure.details ?? failure.message);
const [left, setLeft] = useState<number | null>(wait);
// A throttled setup counts down live, then tries again once.
useEffect(() => {
@@ -365,15 +377,21 @@ export function FailureView({ failure, retrying, onRetry }: { failure: HostFailu
const manual = autoRetried.current ? throttleSeconds(failure.details ?? failure.message) : null;
const message = manual ? `Wait ${manual} ${manual === 1 ? "second" : "seconds"}, then try again.` : left === null ? failure.message : `Trying again in ${left} ${left === 1 ? "second" : "seconds"}.`;
return (
- <div data-host-failure className="text-[13px]">
+ <div data-host-failure={proof ? "needs-proof" : ""} className="text-[13px]">
<div className="flex items-center gap-2">
- <TriangleAlertIcon className="size-3.5 shrink-0 text-amber-500" />
+ {proof ? <ShieldCheckIcon className="size-3.5 shrink-0 text-muted-foreground" /> : <TriangleAlertIcon className="size-3.5 shrink-0 text-amber-500" />}
<span data-host-failure-title className={cn("min-w-0 flex-1 break-words", failure.title ? "font-medium" : "text-destructive")}>
{failure.title ?? failure.message}
</span>
- <Button size="sm" variant="secondary" data-host-retry="" disabled={retrying} onClick={onRetry}>
- {retrying ? "Retrying…" : (failure.actionLabel ?? "Retry")}
- </Button>
+ {proof ? (
+ <Button size="sm" variant="secondary" data-host-use-code="" onClick={onUseCode}>
+ {failure.actionLabel ?? "Use a code from another computer"}
+ </Button>
+ ) : (
+ <Button size="sm" variant="secondary" data-host-retry="" disabled={retrying} onClick={onRetry}>
+ {retrying ? "Retrying…" : isNeedsProof(failure) ? "Retry" : (failure.actionLabel ?? "Retry")}
+ </Button>
+ )}
</div>
{failure.title ? (
<p data-host-failure-message className="mt-1 text-xs text-muted-foreground">
diff --git a/apps/cua-spaces-web/src/lib/first-run-new.ts b/apps/cua-spaces-web/src/lib/first-run-new.ts
index 2c3642e1b5..2e5ee92d95 100644
--- a/apps/cua-spaces-web/src/lib/first-run-new.ts
+++ b/apps/cua-spaces-web/src/lib/first-run-new.ts
@@ -162,7 +162,7 @@ export interface WhereView {
modelFirst: boolean;
picked: boolean;
/** Signed out: Add (opens 1b). Adding failed: Try again. */
- action: { id: "add" | "retry-add"; label: string } | null;
+ action: { id: "add" | "retry-add" | "use-code"; label: string } | null;
};
/** Signed in: the account's other computers (empty: `emptyLine`). Signed out: null, and `signInLine` shows instead. */
others: ComputerRow[] | null;
@@ -184,6 +184,10 @@ export interface WhereInput {
thisState: "adding" | "added" | "failed" | "signed-out";
addedInRun: boolean;
addError: string | null;
+ /** The add failed because the account wants proof it's the owner adding
+ * this computer (`needsProof`): its button is "Use a code from another
+ * computer", not Try again. */
+ addNeedsProof?: boolean;
model: string | null;
machines: Pick<Machine, "id" | "name" | "os" | "online" | "lastSeen" | "current" | "device" | "notSharing">[] | null;
picks: string[];
@@ -273,7 +277,9 @@ export function whereView(input: WhereInput): WhereView {
input.thisState === "adding"
? "Adding to your account…"
: input.thisState === "failed"
- ? `Couldn't add it to your account.${input.addError ? ` ${input.addError}` : ""}`
+ ? input.addNeedsProof && input.addError
+ ? `Confirm it's you. ${input.addError}`
+ : `Couldn't add it to your account.${input.addError ? ` ${input.addError}` : ""}`
: input.addedInRun
? "Added to your account just now"
: "In your account";
@@ -287,7 +293,12 @@ export function whereView(input: WhereInput): WhereView {
model: input.model,
modelFirst: false,
picked: thisPicked,
- action: input.thisState === "failed" ? { id: "retry-add", label: "Try again" } : null,
+ action:
+ input.thisState !== "failed"
+ ? null
+ : input.addNeedsProof
+ ? { id: "use-code", label: "Use a code from another computer" }
+ : { id: "retry-add", label: "Try again" },
},
others,
offlineFold: offlineFold(others),
diff --git a/apps/cua-spaces-web/src/routes/machines/index.tsx b/apps/cua-spaces-web/src/routes/machines/index.tsx
index d4a8e414e2..86ea2e87a0 100644
--- a/apps/cua-spaces-web/src/routes/machines/index.tsx
+++ b/apps/cua-spaces-web/src/routes/machines/index.tsx
@@ -110,10 +110,18 @@ function MachinesPage() {
const { add, join, relay } = Route.useSearch();
const navigate = Route.useNavigate();
const [adding, setAddingState] = useState(add === true || join !== undefined);
+ // "Use a code from another computer" (This Mac's setup refused for want of
+ // proof): the sheet opens on "Enter a code".
+ const [enterCode, setEnterCode] = useState(false);
const setAdding = (open: boolean) => {
setAddingState(open);
+ if (!open) setEnterCode(false);
if (!open && (add || join)) void navigate({ search: {}, replace: true });
};
+ const openEnterCode = () => {
+ setEnterCode(true);
+ setAddingState(true);
+ };
useEffect(() => {
if (add || join) setAddingState(true);
}, [add, join]);
@@ -182,14 +190,14 @@ function MachinesPage() {
) : 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)} />
+ <MachineDetail key={selected.id} machine={selected} row={row(selected.id)} onRemoved={() => setSelectedId(null)} onUseCode={openEnterCode} />
) : null}
</div>
</div>
)}
<EnrollSheet />
{actions.notMeDialog((machine) => remove(machine, null))}
- <AddComputerSheet open={adding} onOpenChange={setAdding} initialView={join !== undefined ? "enter" : "pick"} initialCode={join ?? ""} initialRelay={relay ?? null} />
+ <AddComputerSheet open={adding} onOpenChange={setAdding} initialView={join !== undefined || enterCode ? "enter" : "pick"} initialCode={join ?? ""} initialRelay={relay ?? null} />
</Page>
);
}
@@ -481,7 +489,7 @@ function MachineRow({
/* ---- A machine's page --------------------------------------------------------------- */
-function MachineDetail({ machine: m, row, onRemoved }: { machine: MachinesViewMachine; row: Machine | undefined; onRemoved: () => void }) {
+function MachineDetail({ machine: m, row, onRemoved, onUseCode }: { machine: MachinesViewMachine; row: Machine | undefined; onRemoved: () => void; onUseCode?: () => void }) {
const { data: session } = useSession();
const { account, now, devices } = useMachinesAccount();
const host = useThisMachine(session?.identity ?? null);
@@ -526,7 +534,7 @@ function MachineDetail({ machine: m, row, onRemoved }: { machine: MachinesViewMa
if (m.current && host.formView) {
return (
<section aria-label={`${m.name} details`} className="min-w-0">
- <ThisMachineExtras panel={row?.panel ?? null} progress={row?.hostProgress} />
+ <ThisMachineExtras panel={row?.panel ?? null} progress={row?.hostProgress} onUseCode={onUseCode} />
</section>
);
}
@@ -596,7 +604,7 @@ function MachineDetail({ machine: m, row, onRemoved }: { machine: MachinesViewMa
) : null}
</div>
- {m.current ? <ThisMachineExtras panel={row?.panel ?? null} progress={row?.hostProgress} part="alerts" /> : null}
+ {m.current ? <ThisMachineExtras panel={row?.panel ?? null} progress={row?.hostProgress} part="alerts" onUseCode={onUseCode} /> : null}
{m.spacesTitle ? (
<>
diff --git a/libs/cua-spacesd/crates/cua-relay/src/api.rs b/libs/cua-spacesd/crates/cua-relay/src/api.rs
index c04ec7a641..8ff36aec85 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/api.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/api.rs
@@ -155,6 +155,26 @@ pub(crate) fn error(status: StatusCode, message: impl Into<String>) -> Response
(status, Json(serde_json::json!({"error": message.into()}))).into_response()
}
+/// [`error`] with a stable `code` next to the reason, for a refusal the
+/// apps answer with a screen of their own (the reason stays for people and
+/// older apps; the code is what an app matches on).
+pub(crate) fn coded_error(
+ status: StatusCode,
+ code: &'static str,
+ message: impl Into<String>,
+) -> Response {
+ (
+ status,
+ Json(serde_json::json!({"error": message.into(), "code": code})),
+ )
+ .into_response()
+}
+
+/// The `code` of the refusal of a new computer that arrived with neither an
+/// enrolled device's signature, a sign-in that proved a second factor, nor
+/// a pairing code (S5): the apps ask the person to confirm it is them.
+pub const NEW_COMPUTER_NEEDS_PROOF: &str = "new_computer_needs_proof";
+
fn directory_error(e: DirectoryError) -> Response {
let status = match &e {
DirectoryError::Invalid(_) => StatusCode::BAD_REQUEST,
@@ -558,8 +578,9 @@ async fn register(
}
}
if is_new && !proven {
- return error(
+ return coded_error(
StatusCode::FORBIDDEN,
+ NEW_COMPUTER_NEEDS_PROOF,
"add computers from a computer you already added, or with a pairing code",
);
}
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/phone_security.rs b/libs/cua-spacesd/crates/cua-relay/tests/phone_security.rs
index d7eaf27121..dfcbd3367b 100644
--- a/libs/cua-spacesd/crates/cua-relay/tests/phone_security.rs
+++ b/libs/cua-spacesd/crates/cua-relay/tests/phone_security.rs
@@ -1849,3 +1849,33 @@ async fn revoking_phones_cuts_phone_streams_and_not_computer_streams() {
assert!(chunk.is_some(), "the computer's stream was cut");
}
}
+
+/// A new computer added with the account token alone is refused (S5) with a
+/// stable code next to the reason, so the apps can ask the person to confirm
+/// it is them instead of showing a bare failure.
+#[tokio::test]
+async fn a_new_computer_from_a_token_alone_is_refused_with_a_code() {
+ let env = start(true).await;
+ let id = format!("space-{}", &uuid::Uuid::new_v4().simple().to_string()[..16]);
+ let r = env
+ .http
+ .post(format!("{}/v1/machines", env.base))
+ .bearer_auth(env.token("ada", "cua-cli"))
+ .json(&json!({"id": id, "name": "new mac"}))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), StatusCode::FORBIDDEN);
+ let body: Value = r.json().await.unwrap();
+ assert_eq!(
+ body["code"].as_str(),
+ Some(cua_relay::api::NEW_COMPUTER_NEEDS_PROOF),
+ "{body}"
+ );
+ assert!(
+ body["error"]
+ .as_str()
+ .is_some_and(|e| e.contains("pairing code")),
+ "{body}"
+ );
+}
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index 09e31890b8..2ca21babe4 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -2991,6 +2991,17 @@ pub async fn run_host_to(
opts.max_spaces = max_spaces;
opts.allow_any_address = allow_any_address;
opts.dedicated = dedicated;
+ // A computer paused because it was set up for another account
+ // (the app's "Use a code from another computer"): the code
+ // moves it to the code's account, keeping its setup. A plain
+ // setup would resume the old account's registration instead.
+ if let Some(code) = pair.as_deref() {
+ let code = cua_host::PairingCodeToken::parse(code).map_err(host_err)?;
+ if let Some(s) = host.rejoin_with_code(&code).await.map_err(host_err)? {
+ emit(&s, json, out)?;
+ return Ok(0);
+ }
+ }
let spaces_only = !opts.share_desktop && host.resolve_provide_spaces(&opts);
// Running it again changes nothing when this machine already
// is that host; a host whose service stopped is started again
diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rs
index ca6cbdccc1..f189aa2efb 100644
--- a/libs/cua/crates/cua-host/src/host.rs
+++ b/libs/cua/crates/cua-host/src/host.rs
@@ -2564,6 +2564,26 @@ impl Host {
self.resume_signed_in(account).await
}
+ /// `cua host setup --pair` on a computer whose relay sharing is paused
+ /// because it was set up for another account: the pairing code stands
+ /// in for the account it was made in, and this computer is registered
+ /// again for that account the way a sign-in as it would
+ /// ([`Host::resume_or_switch_account`]), with no remove and set up.
+ /// The relay registers the computer to the account that made the code
+ /// (and refuses a code that is used, expired or revoked). `None` when
+ /// this computer is not paused like that: a plain setup applies.
+ pub async fn rejoin_with_code(
+ &self,
+ code: &crate::pairing::PairingCodeToken,
+ ) -> Result<Option<HostStatus>> {
+ match self.config()? {
+ Some(c) if c.mode == "relay" && c.paused_signed_out && self.policy()?.is_some() => {
+ self.switch_account(code).await.map(Some)
+ }
+ _ => Ok(None),
+ }
+ }
+
/// Registers this computer again for the account behind `tokens`, which
/// is not the one it was set up for. The old registration belongs to
/// the previous account (the relay refuses its id, and the machine's
diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rs
index 803954b5c2..296ef8f5a4 100644
--- a/libs/cua/crates/cua-host/src/lib.rs
+++ b/libs/cua/crates/cua-host/src/lib.rs
@@ -81,8 +81,8 @@ pub use provided::{
pub use relay::{
AccountTokens, AuditEvent, ConnectedClient, DEFAULT_RELAY_URL, DefaultSpace, DefaultSpaceStep,
DeviceListing, DeviceState, DeviceView, Enrollment, Identity, LinkProbe, Machine, MachinePatch,
- NoAccount, RelayClient, RelayUsage, RelayUsageTeam, SpacesSettings, StaticToken,
- TcpShareRequest, TcpShareView, relay_url_from_env,
+ NEW_COMPUTER_NEEDS_PROOF, NoAccount, RelayClient, RelayUsage, RelayUsageTeam, SpacesSettings,
+ StaticToken, TcpShareRequest, TcpShareView, refusal_code, relay_url_from_env,
};
pub use service::{RunnerKind, ServiceManager, ServiceSpec, ServiceState};
diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rs
index 043c739ede..73274cb013 100644
--- a/libs/cua/crates/cua-host/src/relay.rs
+++ b/libs/cua/crates/cua-host/src/relay.rs
@@ -1334,14 +1334,50 @@ fn plan_limit(h: &reqwest::header::HeaderMap) -> Option<cua_home::plan_limit::Pl
)
}
+/// The `code` the relay sends with a refusal of a new computer that came
+/// with no proof it is the account's owner (an enrolled device, a sign-in
+/// with a second factor, or a pairing code). Mirrors the relay's
+/// `api::NEW_COMPUTER_NEEDS_PROOF`.
+pub const NEW_COMPUTER_NEEDS_PROOF: &str = "new_computer_needs_proof";
+
+/// What a relay from before the code said for [`NEW_COMPUTER_NEEDS_PROOF`].
+const NEW_COMPUTER_NEEDS_PROOF_REASON: &str =
+ "add computers from a computer you already added, or with a pairing code";
+
+/// The code a refusal carries (see [`refusal_code`]), in the error's own
+/// words: `relay: <reason> [code: <code>]`.
+const CODE_OPEN: &str = " [code: ";
+
+/// The relay's code for a refusal (HTTP 403), when it gave one: the
+/// machine-readable half of the error, which survives every layer that
+/// passes errors on as text (the SDK, the FFI, the apps' bridges).
+pub fn refusal_code(message: &str) -> Option<&str> {
+ let start = message.rfind(CODE_OPEN)? + CODE_OPEN.len();
+ let code = message[start..].strip_suffix(']')?;
+ (!code.is_empty() && code.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')).then_some(code)
+}
+
fn http_error(status: u16, body: &str) -> Error {
- let message = serde_json::from_str::<serde_json::Value>(body)
- .ok()
+ let json = serde_json::from_str::<serde_json::Value>(body).ok();
+ let message = json
+ .as_ref()
.and_then(|v| v["error"].as_str().map(str::to_string))
.unwrap_or_else(|| body.chars().take(300).collect());
+ let code = json
+ .as_ref()
+ .and_then(|v| v["code"].as_str().map(str::to_string))
+ .filter(|c| !c.is_empty() && c.bytes().all(|b| b.is_ascii_lowercase() || b == b'_'))
+ // A relay from before the code: the same refusal, by its words.
+ .or_else(|| {
+ (status == 403 && message == NEW_COMPUTER_NEEDS_PROOF_REASON)
+ .then(|| NEW_COMPUTER_NEEDS_PROOF.to_string())
+ });
match status {
401 => Error::Unauthenticated(format!("relay: {message}")),
- 403 => Error::PermissionDenied(format!("relay: {message}")),
+ 403 => Error::PermissionDenied(match code {
+ Some(code) => format!("relay: {message}{CODE_OPEN}{code}]"),
+ None => format!("relay: {message}"),
+ }),
404 => Error::NotFound(format!("relay: {message}")),
409 => Error::Conflict(format!("relay: {message}")),
_ => Error::Relay(format!("HTTP {status}: {message}")),
@@ -1473,6 +1509,53 @@ mod tests {
use super::*;
+ /// A refusal keeps the relay's code next to its reason, so an app can
+ /// tell which refusal it was after the error has crossed into text.
+ #[test]
+ fn a_refusal_keeps_the_relays_code() {
+ let e = http_error(
+ 403,
+ r#"{"error":"add computers from a computer you already added, or with a pairing code","code":"new_computer_needs_proof"}"#,
+ );
+ assert!(matches!(&e, Error::PermissionDenied(_)), "{e:?}");
+ let m = e.to_string();
+ assert!(m.starts_with("relay: add computers from"), "{m}");
+ assert_eq!(refusal_code(&m), Some(NEW_COMPUTER_NEEDS_PROOF));
+ assert_eq!(e.http_status(), Some(403));
+
+ // A relay from before the code: the same refusal, by its words.
+ let old = http_error(
+ 403,
+ r#"{"error":"add computers from a computer you already added, or with a pairing code"}"#,
+ );
+ assert_eq!(
+ refusal_code(&old.to_string()),
+ Some(NEW_COMPUTER_NEEDS_PROOF)
+ );
+
+ // Any other refusal keeps its own code; one without a code has none.
+ let other = http_error(
+ 403,
+ r#"{"error":"a phone does not host computers","code":"phone"}"#,
+ );
+ assert_eq!(refusal_code(&other.to_string()), Some("phone"));
+ let bare = http_error(
+ 403,
+ r#"{"error":"that host is shared with you to watch only"}"#,
+ );
+ assert_eq!(
+ bare.to_string(),
+ "relay: that host is shared with you to watch only"
+ );
+ assert_eq!(refusal_code(&bare.to_string()), None);
+ // A code that is not a plain word is not echoed.
+ let odd = http_error(403, r#"{"error":"no","code":"<b>x</b>"}"#);
+ assert_eq!(refusal_code(&odd.to_string()), None);
+ // Other statuses are unchanged.
+ let missing = http_error(404, r#"{"error":"no such device","code":"not_found"}"#);
+ assert_eq!(missing.to_string(), "relay: no such device");
+ }
+
#[test]
fn normalizes_relay_urls() {
assert_eq!(
diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rs
index fe537f80de..8780ab991b 100644
--- a/libs/cua/crates/cua-host/src/tests.rs
+++ b/libs/cua/crates/cua-host/src/tests.rs
@@ -1818,6 +1818,51 @@ fn jwt(user: &str) -> String {
format!("{}.{}.sig", b("{}"), b(&format!(r#"{{"sub":"{user}"}}"#)))
}
+/// A computer paused for another account joins the account that made a
+/// pairing code (the app's "Use a code from another computer"): it is
+/// registered again for that account, keeping its setup. A computer that
+/// is not paused like that is left to a plain setup.
+#[tokio::test]
+async fn a_pairing_code_moves_a_paused_computer_to_the_codes_account() {
+ let relay = FakeRelay::start().await;
+ relay.add_account(&jwt("user-1"), "user-1", Some("[email protected]"));
+ relay.add_account(&jwt("user-2"), "user-2", Some("[email protected]"));
+ // Made on a computer already in user-2's account.
+ let minted = RelayClient::new(&relay.url)
+ .unwrap()
+ .create_pairing_code(
+ &jwt("user-2"),
+ &crate::pairing::PairingCodeRequest::default(),
+ )
+ .await
+ .unwrap()
+ .code
+ .unwrap();
+ let code = crate::pairing::PairingCodeToken::parse(&minted).unwrap();
+ let f = fixture();
+ let host = f.host();
+ let before = host
+ .setup(f.relay_opts(&relay.url), &StaticToken(jwt("user-1")))
+ .await
+ .unwrap();
+ let old_id = before.machine_id.clone().unwrap();
+
+ // Sharing (not paused): nothing to move, a plain setup applies.
+ assert!(host.rejoin_with_code(&code).await.unwrap().is_none());
+
+ host.pause_signed_out().await.unwrap();
+ let moved = host.rejoin_with_code(&code).await.unwrap().expect("moved");
+ assert!(!moved.paused_signed_out);
+ assert!(moved.service.installed && moved.service.running);
+ assert_eq!(moved.owner.as_deref(), Some("user-2"));
+ assert_ne!(moved.machine_id.as_deref(), Some(old_id.as_str()));
+ assert_eq!(moved.name.as_deref(), Some("mini"));
+ let on_relay = relay
+ .machine(moved.machine_id.as_deref().unwrap())
+ .expect("registered");
+ assert_eq!(on_relay.owner.id, "user-2");
+}
+
/// Signing in as another account re-registers this computer for it: a new
/// machine id and mesh key, while the name and the Provide Spaces setting
/// stay.