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: share only with people in your team (CUA-1883) (#5544)
Francesco Bonacci898da78b1fb7
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex d1a7e4aab6..120504e171 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -24,6 +24,7 @@ export const METHODS = ["teleport.catalog", "teleport.entryForPath", "teleport.windows", "teleport.remoteWindows","teleport.icon", "teleport.thumbnail", "teleport.plan", "teleport.run", "teleport.sites","teleport.remembered", "teleport.streamWindow", "sharing.list", "sharing.share", "sharing.unshare",+ "sharing.removals", "sharing.ackRemovals","volume.overview", "volume.storage", "volume.storageSet", "volume.mount", "volume.unmount","volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal","agents.setupDriver",diff --git a/apps/cua-spaces-desktop/src/bridge/sharing.ts b/apps/cua-spaces-desktop/src/bridge/sharing.tsindex c7b2352ebe..31eed0780e 100644--- a/apps/cua-spaces-desktop/src/bridge/sharing.ts+++ b/apps/cua-spaces-desktop/src/bridge/sharing.ts@@ -1,7 +1,11 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-// Share a Space (`sharing.list`, `sharing.share`, `sharing.unshare`): the+// Share a Space (`sharing.list`, `sharing.share`, `sharing.unshare`) and the+// owner's note that sharing is for teams now (`sharing.removals`,+// `sharing.ackRemovals`: the Spaces app export's `appShareRemovals` and+// `appAckShareRemovals` with the account's token, as the SwiftUI host reads+// them; empty when signed out or from a server that predates it). The// SDK's `Space.shares`, `share` and `unshare`, as the SwiftUI host calls// them for its Share sheet. Who it is shared with comes back as the core's// share rows; the sheet's words, the experiment gate and the usage events@@ -13,9 +17,19 @@ import type { Handlers } from "./host";import { encode } from "./value";export function sharingMethods({ model }: BridgeContext): Handlers {+ const token = async () => (model.servicesIn && model.identity && model.account ? model.account.accessToken(false) : null);return {"sharing.list": async (args) => encode(await model.backend.shares(string(args, "spaceId"))),"sharing.share": async (args) => encode(await model.backend.share(string(args, "spaceId"), string(args, "who"), string(args, "role"))),"sharing.unshare": async (args) => encode(await model.backend.unshare(string(args, "spaceId"), string(args, "who"))),+ "sharing.removals": async () => {+ const t = await token();+ return t ? encode(await model.native.appShareRemovals(t)) : [];+ },+ "sharing.ackRemovals": async () => {+ const t = await token();+ if (t) await model.native.appAckShareRemovals(t);+ return null;+ },};}diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.tsindex 00bd6bfd22..e1a645edae 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts@@ -417,6 +417,11 @@ const DEFINITIONS = {ret: FfiType.RustBuffer,hasRustCallStatus: true,},+ "uniffi_cua_spaces_ffi_fn_func_app_ack_share_removals": {+ args: [FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_spaces_ffi_fn_func_app_agent_key_form": {args: [FfiType.RustBuffer, FfiType.RustBuffer],ret: FfiType.RustBuffer,@@ -1377,6 +1382,16 @@ const DEFINITIONS = {ret: FfiType.RustBuffer,hasRustCallStatus: true,},+ "uniffi_cua_spaces_ffi_fn_func_app_share_error_words": {+ args: [FfiType.RustBuffer, FfiType.RustBuffer],+ ret: FfiType.RustBuffer,+ hasRustCallStatus: true,+ },+ "uniffi_cua_spaces_ffi_fn_func_app_share_gate": {+ args: [FfiType.RustBuffer],+ ret: FfiType.RustBuffer,+ hasRustCallStatus: true,+ },"uniffi_cua_spaces_ffi_fn_func_app_share_initial": {args: [],ret: FfiType.RustBuffer,@@ -1392,6 +1407,16 @@ const DEFINITIONS = {ret: FfiType.RustBuffer,hasRustCallStatus: true,},+ "uniffi_cua_spaces_ffi_fn_func_app_share_removal_note": {+ args: [FfiType.RustBuffer],+ ret: FfiType.RustBuffer,+ hasRustCallStatus: true,+ },+ "uniffi_cua_spaces_ffi_fn_func_app_share_removals": {+ args: [FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_spaces_ffi_fn_func_app_share_state_from_json": {args: [FfiType.RustBuffer],ret: FfiType.RustBuffer,@@ -2132,6 +2157,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_spaces_ffi_checksum_func_app_ack_share_removals": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form": {args: [],ret: FfiType.UInt16,@@ -3092,6 +3122,16 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_spaces_ffi_checksum_func_app_share_error_words": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },+ "uniffi_cua_spaces_ffi_checksum_func_app_share_gate": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_spaces_ffi_checksum_func_app_share_initial": {args: [],ret: FfiType.UInt16,@@ -3107,6 +3147,16 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_spaces_ffi_checksum_func_app_share_removal_note": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },+ "uniffi_cua_spaces_ffi_checksum_func_app_share_removals": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_spaces_ffi_checksum_func_app_share_state_from_json": {args: [],ret: FfiType.UInt16,@@ -4019,6 +4069,7 @@ interface NativeModuleInterface {uniffi_cua_spaces_ffi_fn_func_app_about_restart_daemon(check: Uint8Array, uniffi_out_err: UniffiRustCallStatus): number;uniffi_cua_spaces_ffi_fn_func_app_about_view(input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_spaces_ffi_fn_func_app_account_app_url(uniffi_out_err: UniffiRustCallStatus): Uint8Array;+ uniffi_cua_spaces_ffi_fn_func_app_ack_share_removals(accountToken: Uint8Array): bigint;uniffi_cua_spaces_ffi_fn_func_app_agent_key_form(input: Uint8Array, form: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_spaces_ffi_fn_func_app_agent_key_form_input_from_json(json: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_spaces_ffi_fn_func_app_agent_key_name_problem(name: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;@@ -4211,9 +4262,13 @@ interface NativeModuleInterface {uniffi_cua_spaces_ffi_fn_func_app_settings_save(path: Uint8Array, settings: Uint8Array, uniffi_out_err: UniffiRustCallStatus): void;uniffi_cua_spaces_ffi_fn_func_app_settings_with_storage(page: Uint8Array, storage: Uint8Array, experiments: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_spaces_ffi_fn_func_app_share_action_from_json(json: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;+ uniffi_cua_spaces_ffi_fn_func_app_share_error_words(error: Uint8Array, who: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;+ uniffi_cua_spaces_ffi_fn_func_app_share_gate(hasTeam: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_spaces_ffi_fn_func_app_share_initial(uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_spaces_ffi_fn_func_app_share_input_from_json(json: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_spaces_ffi_fn_func_app_share_reduce(input: Uint8Array, state: Uint8Array, action: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;+ uniffi_cua_spaces_ffi_fn_func_app_share_removal_note(removals: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;+ uniffi_cua_spaces_ffi_fn_func_app_share_removals(accountToken: Uint8Array): bigint;uniffi_cua_spaces_ffi_fn_func_app_share_state_from_json(json: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_spaces_ffi_fn_func_app_share_view(input: Uint8Array, state: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_spaces_ffi_fn_func_app_sidebar(spaces: Uint8Array, query: Uint8Array, selectedId: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;@@ -4362,6 +4417,7 @@ interface NativeModuleInterface {uniffi_cua_spaces_ffi_checksum_func_app_about_restart_daemon(): number;uniffi_cua_spaces_ffi_checksum_func_app_about_view(): number;uniffi_cua_spaces_ffi_checksum_func_app_account_app_url(): number;+ uniffi_cua_spaces_ffi_checksum_func_app_ack_share_removals(): number;uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form(): number;uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form_input_from_json(): number;uniffi_cua_spaces_ffi_checksum_func_app_agent_key_name_problem(): number;@@ -4554,9 +4610,13 @@ interface NativeModuleInterface {uniffi_cua_spaces_ffi_checksum_func_app_settings_save(): number;uniffi_cua_spaces_ffi_checksum_func_app_settings_with_storage(): number;uniffi_cua_spaces_ffi_checksum_func_app_share_action_from_json(): number;+ uniffi_cua_spaces_ffi_checksum_func_app_share_error_words(): number;+ uniffi_cua_spaces_ffi_checksum_func_app_share_gate(): number;uniffi_cua_spaces_ffi_checksum_func_app_share_initial(): number;uniffi_cua_spaces_ffi_checksum_func_app_share_input_from_json(): number;uniffi_cua_spaces_ffi_checksum_func_app_share_reduce(): number;+ uniffi_cua_spaces_ffi_checksum_func_app_share_removal_note(): number;+ uniffi_cua_spaces_ffi_checksum_func_app_share_removals(): number;uniffi_cua_spaces_ffi_checksum_func_app_share_state_from_json(): number;uniffi_cua_spaces_ffi_checksum_func_app_share_view(): number;uniffi_cua_spaces_ffi_checksum_func_app_sidebar(): number;diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.tsindex 583ec4cc28..36e0873522 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts@@ -164,6 +164,35 @@ export function appAccountAppUrl(): string {));}+/**+ * The owner has seen the note: it is not shown again.+ */+export async function appAckShareRemovals(accountToken: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_ack_share_removals(FfiConverterString.lower(accountToken, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_poll_void,+ /*cancelFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_cancel_void,+ /*completeFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_complete_void,+ /*freeFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_free_void,+ /*liftFunc:*/ (_v) => {},+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** The add or replace sheet.*/@@ -4152,6 +4181,50 @@ export function appShareActionFromJson(json: string): AppShareSheetAction /*thro));}+/**+ * A refused share in plain words (`share_outside_team`,+ * `sharing_needs_team`); `None` for any other error.+ */+export function appShareErrorWords(error: string, who: string): string | undefined {+ return ((__rb: Uint8Array) => {+ try {+ return FfiConverterOptionalString.lift(__rb);+ } finally {+ nativeModule().rustbuffer_free(__rb);+ }+ })(uniffiCaller.rustCall(+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_share_error_words(+ FfiConverterString.lower(error, nativeModule().rustbuffer_alloc),+ FfiConverterString.lower(who, nativeModule().rustbuffer_alloc),+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }++/**+ * Why the Share sheet is closed, from whether the account is in a team+ * that can share (`None`: the host could not say, so the sheet stays open+ * and the server decides). Sharing is for teams (CUA-1883).+ */+export function appShareGate(hasTeam: boolean | undefined): AppShareGate | undefined {+ return ((__rb: Uint8Array) => {+ try {+ return FfiConverterOptionalTypeAppShareGate.lift(__rb);+ } finally {+ nativeModule().rustbuffer_free(__rb);+ }+ })(uniffiCaller.rustCall(+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_share_gate(+ FfiConverterOptionalBoolean.lower(hasTeam, nativeModule().rustbuffer_alloc),+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }+/*** A new Share sheet.*/@@ -4214,6 +4287,62 @@ export function appShareReduce(input: AppShareInput, state: AppShareSheetState,));}+/**+ * The owner's one-line note about people removed from shared computers.+ */+export function appShareRemovalNote(removals: Array<AppShareRemovalInput>): AppShareRemovalNote | undefined {+ return ((__rb: Uint8Array) => {+ try {+ return FfiConverterOptionalTypeAppShareRemovalNote.lift(__rb);+ } finally {+ nativeModule().rustbuffer_free(__rb);+ }+ })(uniffiCaller.rustCall(+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_share_removal_note(+ FfiConverterSequenceTypeAppShareRemovalInput.lower(removals, nativeModule().rustbuffer_alloc),+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }++/**+ * People removed from the account's shared computers because sharing is+ * for teams now, until [`app_ack_share_removals`]. Empty on a server that+ * predates it.+ */+export async function appShareRemovals(accountToken: string, asyncOpts_?: { signal: AbortSignal }): Promise<Array<AppShareRemovalInput>> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_share_removals(FfiConverterString.lower(accountToken, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterSequenceTypeAppShareRemovalInput.lift.bind(FfiConverterSequenceTypeAppShareRemovalInput),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** The Share sheet's state from JSON (fixtures, parity).*/@@ -35232,6 +35361,55 @@ const FfiConverterTypeAppSettingsPage = (() => {return new FFIConverter();})();+export type AppShareActionView = {+ /**+ * The button's words.+ */+ label: string,+ /**+ * Where it opens.+ */+ url: string+}++/**+ * Generated factory for {@link AppShareActionView} record objects.+ */+export const AppShareActionView = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<AppShareActionView, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<AppShareActionView>,+ });+})();++const FfiConverterTypeAppShareActionView = (() => {+ type TypeName = AppShareActionView;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ label: FfiConverterString.read(from),+ url: FfiConverterString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.label, into);+ FfiConverterString.write(value.url, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.label) ++ FfiConverterString.allocationSize(value.url);++ }+ };+ return new FFIConverter();+})();+export type AppShareEntryInput = {/*** Email or account id.@@ -35288,6 +35466,55 @@ const FfiConverterTypeAppShareEntryInput = (() => {return new FFIConverter();})();+export type AppShareGate = {+ /**+ * "Sharing is for teams. Start a team to share this Space."+ */+ reason: string,+ /**+ * "See Teams": where Teams starts, at one seat.+ */+ action: AppShareActionView+}++/**+ * Generated factory for {@link AppShareGate} record objects.+ */+export const AppShareGate = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<AppShareGate, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<AppShareGate>,+ });+})();++const FfiConverterTypeAppShareGate = (() => {+ type TypeName = AppShareGate;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ reason: FfiConverterString.read(from),+ action: FfiConverterTypeAppShareActionView.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.reason, into);+ FfiConverterTypeAppShareActionView.write(value.action, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.reason) ++ FfiConverterTypeAppShareActionView.allocationSize(value.action);++ }+ };+ return new FFIConverter();+})();+export type AppShareInput = {/*** The Space's id.@@ -35358,6 +35585,111 @@ const FfiConverterTypeAppShareInput = (() => {return new FFIConverter();})();+export type AppShareRemovalInput = {+ /**+ * The person (an email or account id).+ */+ who: string,+ /**+ * The computer's name.+ */+ machineName: string+}++/**+ * Generated factory for {@link AppShareRemovalInput} record objects.+ */+export const AppShareRemovalInput = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<AppShareRemovalInput, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<AppShareRemovalInput>,+ });+})();++const FfiConverterTypeAppShareRemovalInput = (() => {+ type TypeName = AppShareRemovalInput;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ who: FfiConverterString.read(from),+ machineName: FfiConverterString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.who, into);+ FfiConverterString.write(value.machineName, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.who) ++ FfiConverterString.allocationSize(value.machineName);++ }+ };+ return new FFIConverter();+})();++export type AppShareRemovalNote = {+ /**+ * One line: who can no longer open what, and why.+ */+ text: string,+ /**+ * "Invite to your team".+ */+ action: AppShareActionView,+ /**+ * Dismiss.+ */+ dismiss: string+}++/**+ * Generated factory for {@link AppShareRemovalNote} record objects.+ */+export const AppShareRemovalNote = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<AppShareRemovalNote, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<AppShareRemovalNote>,+ });+})();++const FfiConverterTypeAppShareRemovalNote = (() => {+ type TypeName = AppShareRemovalNote;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ text: FfiConverterString.read(from),+ action: FfiConverterTypeAppShareActionView.read(from),+ dismiss: FfiConverterString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.text, into);+ FfiConverterTypeAppShareActionView.write(value.action, into);+ FfiConverterString.write(value.dismiss, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.text) ++ FfiConverterTypeAppShareActionView.allocationSize(value.action) ++ FfiConverterString.allocationSize(value.dismiss);++ }+ };+ return new FFIConverter();+})();+export type AppShareRowView = {/*** Email or account id.@@ -61865,6 +62197,15 @@ const FfiConverterOptionalTypeAppRelayUsageView = new FfiConverterOptional(FfiCo// FfiConverter for Array<AppSpaceRow>const FfiConverterSequenceTypeAppSpaceRow = new FfiConverterArray(FfiConverterTypeAppSpaceRow);+// FfiConverter for AppShareGate | undefined+const FfiConverterOptionalTypeAppShareGate = new FfiConverterOptional(FfiConverterTypeAppShareGate);++// FfiConverter for Array<AppShareRemovalInput>+const FfiConverterSequenceTypeAppShareRemovalInput = new FfiConverterArray(FfiConverterTypeAppShareRemovalInput);++// FfiConverter for AppShareRemovalNote | undefined+const FfiConverterOptionalTypeAppShareRemovalNote = new FfiConverterOptional(FfiConverterTypeAppShareRemovalNote);+// FfiConverter for AppSpaceUsage | undefinedconst FfiConverterOptionalTypeAppSpaceUsage = new FfiConverterOptional(FfiConverterTypeAppSpaceUsage);@@ -61929,6 +62270,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_account_app_url() !== 9943) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_account_app_url");}+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_ack_share_removals() !== 16071) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_ack_share_removals");+ }if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form() !== 42778) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form");}@@ -62505,6 +62849,12 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_share_action_from_json() !== 61097) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_share_action_from_json");}+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_share_error_words() !== 56839) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_share_error_words");+ }+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_share_gate() !== 9867) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_share_gate");+ }if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_share_initial() !== 65098) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_share_initial");}@@ -62514,6 +62864,12 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_share_reduce() !== 46853) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_share_reduce");}+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_share_removal_note() !== 63359) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_share_removal_note");+ }+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_share_removals() !== 49780) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_share_removals");+ }if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_share_state_from_json() !== 38498) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_share_state_from_json");}@@ -63266,8 +63622,12 @@ export default Object.freeze({FfiConverterTypeAppSettingsRow,FfiConverterTypeAppSettingsRowKind,FfiConverterTypeAppSettingsSection,+ FfiConverterTypeAppShareActionView,FfiConverterTypeAppShareEntryInput,+ FfiConverterTypeAppShareGate,FfiConverterTypeAppShareInput,+ FfiConverterTypeAppShareRemovalInput,+ FfiConverterTypeAppShareRemovalNote,FfiConverterTypeAppShareRequest,FfiConverterTypeAppShareRowView,FfiConverterTypeAppShareSheetAction,diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.tsindex 45ac65d4e4..1c7a36febd 100644--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts@@ -179,7 +179,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {expect(problems).toEqual([]);// Every ported method has its case (or is checked below).// (Teleport and the Keyvault: vault-native.test.ts; This machine, Devices, Settings and the rest: host-bridge.test.ts; the relay allowance: relay-usage.test.ts; resource numbers: resources.test.ts; presence: presence-bridge.test.ts; the Windows runtime fix: below.)- const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "resources.get", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);+ const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);const ported = bridge.registry.methods.filter((m) => !NOT_YET.includes(m) && !elsewhere.has(m));expect(ported.filter((m) => !cases.some(([c]) => c === m))).toEqual([]);});@@ -563,7 +563,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {"checklist.send": { action: { type: "done", step: "teleport" } },};// This machine, Devices, Settings and the rest: host-bridge.test.ts reads them with their arguments.- const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "resources.get", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", ...VAULT_OPS, ...(HOST_OPS as OpName[])]);+ const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", ...VAULT_OPS, ...(HOST_OPS as OpName[])]);const problems: string[] = [];const checked: string[] = [];for (const op of OPERATIONS) {diff --git a/apps/cua-spaces-desktop/test/share-removals.test.ts b/apps/cua-spaces-desktop/test/share-removals.test.tsnew file mode 100644index 0000000000..82468151dc--- /dev/null+++ b/apps/cua-spaces-desktop/test/share-removals.test.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// `sharing.removals` and `sharing.ackRemovals`: the Spaces app export's+// `appShareRemovals` and `appAckShareRemovals` with the account's token (the+// owner's one-line note that sharing is for teams now), as the page's shape,+// checked against the web contract.+import { describe, expect, it, vi } from "vitest";+import { OP_SHAPES, SHAPE_DEFS } from "../../cua-spaces-web/src/bridge/contracts/shapes";+import { validate } from "../../cua-spaces-web/src/bridge/contracts/schema";+import type { BridgeContext } from "../src/bridge/context";+import { sharingMethods } from "../src/bridge/sharing";++const REMOVALS = [+ { who: "[email protected]", machineName: "Design" },+ { who: "[email protected]", machineName: "Design" },+];++function context(o: { signedIn?: boolean } = {}) {+ const accessToken = vi.fn(async () => "acct-token");+ const appShareRemovals = vi.fn(async (_token: string) => REMOVALS);+ const appAckShareRemovals = vi.fn(async (_token: string) => {});+ const ctx = {+ model: {+ servicesIn: true,+ identity: o.signedIn === false ? null : "[email protected]",+ account: { accessToken },+ native: { appShareRemovals, appAckShareRemovals },+ },+ } as unknown as BridgeContext;+ return { ctx, appShareRemovals, appAckShareRemovals };+}++const handlers = (ctx: BridgeContext) => sharingMethods(ctx);++describe("sharing.removals and sharing.ackRemovals", () => {+ it("reads who was removed with the account's token, in the page's shape", async () => {+ const { ctx, appShareRemovals } = context();+ const out = await handlers(ctx)["sharing.removals"]!({}, {});+ expect(appShareRemovals).toHaveBeenCalledWith("acct-token");+ expect(out).toEqual(REMOVALS);+ expect(validate(OP_SHAPES["sharing.removals"], out, SHAPE_DEFS)).toEqual([]);+ });++ it("acknowledges with the account's token and answers null", async () => {+ const { ctx, appAckShareRemovals } = context();+ expect(await handlers(ctx)["sharing.ackRemovals"]!({}, {})).toBeNull();+ expect(appAckShareRemovals).toHaveBeenCalledWith("acct-token");+ });++ it("reads nothing and acknowledges nothing when signed out", async () => {+ const out = context({ signedIn: false });+ expect(await handlers(out.ctx)["sharing.removals"]!({}, {})).toEqual([]);+ expect(await handlers(out.ctx)["sharing.ackRemovals"]!({}, {})).toBeNull();+ expect(out.appShareRemovals).not.toHaveBeenCalled();+ expect(out.appAckShareRemovals).not.toHaveBeenCalled();+ });+});diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swiftindex 5b0b1cba79..c8435d1792 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift@@ -129,6 +129,9 @@ public final class AppModel {public var teamsReader: TeamsReading?/// Where Settings' Teams stand: not read yet, read, or failed.public private(set) var teamsState: AppTeamsState = .signedOut+ /// The owner's one-line note that sharing is for teams now and some+ /// people can no longer open a shared computer; shown once.+ public private(set) var shareRemovalNote: AppShareRemovalNote?/// This app as a login item (nil: no Launch at login row).let loginItem: LoginItemControlling?/// What the system reports for it (nil until read).@@ -1188,6 +1191,7 @@ public final class AppModel {// owner (another account is asked to set it up again).await host.reconcileAccount()await reloadTeams()+ await reloadShareRemovals()} catch {guard signInAttempt == current, signIn != .idle else { return }signInFailed(LiveSpacesBackend.words(error))@@ -1248,6 +1252,31 @@ public final class AppModel {currentTeamId: settings.currentTeamId)}+ /// The account is in a team on the Teams plan, which sharing needs: nil+ /// until Teams are read, so the server decides.+ public var hasSharingTeam: Bool? {+ if case .ready(let list) = teamsState { return list.contains { $0.plan == "teams" } }+ return nil+ }++ /// Reads who lost access to a shared computer (sharing is for teams) and+ /// words the one-line note. Nothing when signed out or when there is no one.+ public func reloadShareRemovals() async {+ guard identity != nil, let teamsReader else {+ shareRemovalNote = nil+ return+ }+ let removals = (try? await teamsReader.shareRemovals()) ?? []+ shareRemovalNote = appShareRemovalNote(removals: removals)+ }++ /// Closes the note and tells the account it was seen, so it shows once.+ public func dismissShareRemovalNote() {+ shareRemovalNote = nil+ guard let teamsReader else { return }+ Task { try? await teamsReader.ackShareRemovals() }+ }+/// Reads the account's Teams (Settings, Teams). A failure says so in the/// row; the account app's links stay.func reloadTeams() async {diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swiftindex 218674073f..61967eeadf 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift@@ -383,6 +383,16 @@ public final class FixtureBilling: BillingRunning, @unchecked Sendable {/// roles and billing are the account app's (app.cua.ai).public protocol TeamsReading: AnyObject, Sendable {func teams() async throws -> AppTeamsInput+ /// People removed from the account's shared computers because sharing is+ /// for teams now, until acknowledged (none from a server that predates it).+ func shareRemovals() async throws -> [AppShareRemovalInput]+ /// The owner has seen the removal note.+ func ackShareRemovals() async throws+}++public extension TeamsReading {+ func shareRemovals() async throws -> [AppShareRemovalInput] { [] }+ func ackShareRemovals() async throws {}}/// Reads Teams with the account's access token (`force`: refresh it).@@ -396,13 +406,26 @@ public final class LiveTeams: TeamsReading, @unchecked Sendable {}return try await appTeams(accountToken: token)}++ public func shareRemovals() async throws -> [AppShareRemovalInput] {+ guard let token = try await token(false) else { return [] }+ return try await appShareRemovals(accountToken: token)+ }++ public func ackShareRemovals() async throws {+ guard let token = try await token(false) else { return }+ try await appAckShareRemovals(accountToken: token)+ }}/// A fixture account's team (captures, tests).public final class FixtureTeams: TeamsReading, @unchecked Sendable {public var current: AppTeamsInput+ /// Who the fixture's owner has not been told was removed yet.+ public var removals: [AppShareRemovalInput]- public init(_ teams: [AppTeamInput]? = nil) {+ public init(_ teams: [AppTeamInput]? = nil, removals: [AppShareRemovalInput] = []) {+ self.removals = removalscurrent = AppTeamsInput(accountAppUrl: "https://app.cua.ai", state: .ready(teams: teams ?? [AppTeamInput(id: "o1", alias: "acme", name: "Acme Inc", role: "owner", plan: "teams", seats: 3,@@ -413,6 +436,8 @@ public final class FixtureTeams: TeamsReading, @unchecked Sendable {}public func teams() async throws -> AppTeamsInput { current }+ public func shareRemovals() async throws -> [AppShareRemovalInput] { removals }+ public func ackShareRemovals() async throws { removals = [] }}/// Opens the website billing page (Settings' Manage billing, a refuseddiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/ShareModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/ShareModel.swiftindex 9e95da5691..37106745e0 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/ShareModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/ShareModel.swift@@ -15,6 +15,9 @@ public final class ShareModel {public let spaceName: Stringpublic var signedIn: Boolpublic var shareable: Bool+ /// In a team that can share; nil until read, or when it cannot be said+ /// (the server decides). Set by whoever opens the sheet.+ public var hasTeam: Bool?public private(set) var shares: [AppShareEntryInput] = []public private(set) var state = appShareInitial()private let backend: SpacesBackend@@ -33,6 +36,11 @@ public final class ShareModel {public var view: AppShareSheetView { appShareView(input: input, state: state) }+ /// Why the sheet is closed: sharing is for teams, so an account known to+ /// be in none is sent to Teams. This only explains; the control plane+ /// and the relay refuse an outside share either way.+ public var gate: AppShareGate? { signedIn && shareable ? appShareGate(hasTeam: hasTeam) : nil }+public func load() async {guard signedIn else { return }if let rows = try? await backend.shares(id: spaceId) { shares = rows }@@ -59,7 +67,12 @@ public final class ShareModel {if case .share = request { onShared?() }state = appShareReduce(input: input, state: state, action: .done)} catch {- let failed = AppShareSheetAction.failed(error: "\(error.localizedDescription)")+ // A refusal for who is not in the team (or no team) reads in plain words.+ var who = ""+ if case let .share(_, w, _) = request { who = w }+ let raw = "\(error.localizedDescription) \(error)"+ let words = appShareErrorWords(error: raw, who: who) ?? error.localizedDescription+ let failed = AppShareSheetAction.failed(error: words)telemetry?.record(appTelemetryShare(input: before, state: state, action: failed))state = appShareReduce(input: input, state: state, action: failed)}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/DevicesViews.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/DevicesViews.swiftindex 2d6db9d3b1..2096ec7f9d 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/DevicesViews.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/DevicesViews.swift@@ -438,6 +438,43 @@ struct RelayAllowanceBanner: View {}}+/// Sharing is for teams (CUA-1883): one line, once, saying who can no longer+/// open a shared computer, with "Invite to your team". The words are the+/// app core's; closing it tells the account it was seen.+struct ShareRemovalBanner: View {+ @Bindable var model: AppModel+ @Environment(\.openURL) private var openURL++ var body: some View {+ if let note = model.shareRemovalNote {+ HStack(spacing: 8) {+ Text(note.text).lineLimit(2).foregroundStyle(.secondary).help(note.text)+ Spacer(minLength: 8)+ if let url = URL(string: note.action.url) {+ Button(note.action.label) { openURL(url) }+ .controlSize(.small)+ .accessibilityIdentifier("share-removal-invite")+ }+ Button {+ model.dismissShareRemovalNote()+ } label: {+ Image(systemName: "xmark")+ }+ .buttonStyle(.borderless)+ .controlSize(.small)+ .accessibilityLabel(note.dismiss)+ .accessibilityIdentifier("share-removal-dismiss")+ }+ .font(.callout)+ .padding(.horizontal, 12)+ .padding(.vertical, 7)+ .background(.bar)+ .overlay(alignment: .bottom) { Divider() }+ .accessibilityIdentifier("share-removal")+ }+ }+}+/// Settings → Account: the plan and the relay allowance this month, where/// it applies. The plan card is always there, never a prompt: Free offers/// Pro and a team; each button opens its checkout on the account app.diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swiftindex 11d8d096ee..b6d495df7b 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift@@ -27,6 +27,7 @@ public struct MainWindow: View {.safeAreaInset(edge: .top, spacing: 0) {VStack(spacing: 0) {DevicesBanner(devices: model.devices)+ ShareRemovalBanner(model: model)RelayAllowanceBanner(devices: model.devices)if let error = model.rosterError {SpacesDiscoveryNotice(error: error)@@ -74,6 +75,7 @@ public struct MainWindow: View {.task {await model.refresh()await model.keyvault.refresh()+ await model.reloadShareRemovals()}// The relay allowance: at once (and on every sign-in or out), every// 5 minutes, and when the app comes to the front.diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ShareSheetView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ShareSheetView.swiftindex 0260d422d1..39add1b504 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ShareSheetView.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ShareSheetView.swift@@ -10,23 +10,31 @@ import SwiftUIstruct ShareSheetView: View {@Bindable var model: ShareModellet onDone: () -> Void+ @Environment(\.openURL) private var openURLvar body: some View {let v = model.view+ let gate = model.gate+ let closed = v.disabledReason != nil || gate != nilForm {- if let reason = v.disabledReason {+ if let reason = v.disabledReason ?? gate?.reason {Text(reason).foregroundStyle(.secondary)}+ if v.disabledReason == nil, let gate, let url = URL(string: gate.action.url) {+ Button(gate.action.label) { openURL(url) }+ .accessibilityIdentifier("share-see-teams")+ }Section {HStack {TextField(v.whoPlaceholder, text: Binding(get: { v.who },set: { who in Task { await model.send(.setWho(who: who)) } })).textFieldStyle(.roundedBorder)+ .disabled(closed).onSubmit { Task { await model.send(.submit) } }roleMenu(v, selection: v.role) { role in Task { await model.send(.setRole(role: role)) } }Button(v.shareLabel) { Task { await model.send(.submit) } }- .disabled(!v.canShare)+ .disabled(!v.canShare || closed).keyboardShortcut(.defaultAction)}if let hint = v.hint { Text(hint).foregroundStyle(.secondary) }@@ -63,6 +71,6 @@ struct ShareSheetView: View {}.labelsHidden().fixedSize()- .disabled(v.busy || v.disabledReason != nil)+ .disabled(v.busy || v.disabledReason != nil || model.gate != nil)}}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SpaceDetailView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SpaceDetailView.swiftindex 1e03631762..5c456be948 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SpaceDetailView.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SpaceDetailView.swift@@ -336,6 +336,12 @@ struct SpaceDetailView: View {backend: model.backend, spaceId: space.id, spaceName: space.name,signedIn: model.identity != nil,shareable: space.id.hasPrefix("relay:") || (space.sdk?.features.contains("relay_attach") ?? false))+ sharing?.hasTeam = model.hasSharingTeam+ Task { [weak model] in+ // Teams may not have been read yet: the sheet closes or stays open once they are.+ await model?.reloadTeams()+ sharing?.hasTeam = model?.hasSharingTeam+ }sharing?.telemetry = model.telemetrySinksharing?.onShared = { [weak model] in model?.checklist.done(.share) }model.recordFeature("share_open")diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex 16b8d34f01..93cb949610 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -45,6 +45,15 @@ extension WebUIBridge {case "sharing.unshare":return BridgeValue.encode(try await model.backend.unshare(id: try spaceId(args), who: try string(args, "who")))+ // Sharing is for teams: who lost access, and "seen" (empty when signed+ // out or from a server that predates it).+ case "sharing.removals":+ guard model.identity != nil, let reader = model.teamsReader else { return [] as [Any] }+ return BridgeValue.encode(try await reader.shareRemovals())+ case "sharing.ackRemovals":+ if model.identity != nil { try await model.teamsReader?.ackShareRemovals() }+ return NSNull()+// Settings, Agents: 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")diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex 1702716b60..0150ea2604 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -85,7 +85,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"spaces.add", "clouds.status", "clouds.test", "clouds.connect","teleport.catalog", "teleport.entryForPath", "teleport.windows", "teleport.remoteWindows","teleport.icon", "teleport.thumbnail", "teleport.plan", "teleport.run", "teleport.sites",- "teleport.remembered", "teleport.streamWindow", "sharing.list", "sharing.share", "sharing.unshare",+ "teleport.remembered", "teleport.streamWindow", "sharing.list", "sharing.share", "sharing.unshare", "sharing.removals", "sharing.ackRemovals","volume.overview", "volume.storage", "volume.storageSet", "volume.mount", "volume.unmount","volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal","agents.setupDriver",diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex c9a2121187..cfda904d46 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -225,6 +225,7 @@ struct BridgeContractTests {("clouds.connect", ["target": ["provider": "aws", "region": "us-west-2"], "makeDefault": false]),("sharing.list", ["spaceId": space]), ("sharing.share", ["spaceId": space, "who": "[email protected]", "role": "viewer"]),("sharing.unshare", ["spaceId": space, "who": "[email protected]"]),+ ("sharing.removals", [:]), ("sharing.ackRemovals", [:]),("volume.overview", [:]), ("volume.storage", [:]), ("volume.mount", [:]), ("volume.unmount", [:]),("volume.storageSet", ["update": ["backend": "fs", "dry_run": true]]),("about.get", [:]), ("about.set", ["channel": "beta"]), ("about.checkNow", [:]),diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swiftindex 6291b39998..be01a1fea4 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift@@ -1334,6 +1334,40 @@ struct ViewModelTests {#expect(notch.view.phase == .closed)}+ /// Sharing is for teams (CUA-1883): the owner sees one line, once, naming+ /// who can no longer open a shared computer, and closing it acknowledges it.+ @Test func ownerSeesTheRemovalNoteOnceAndItIsAcknowledged() async throws {+ let model = makeModel(account: FixtureAccount(identity: "[email protected]"))+ let teams = FixtureTeams(removals: [+ AppShareRemovalInput(who: "[email protected]", machineName: "Design"),+ AppShareRemovalInput(who: "[email protected]", machineName: "Design"),+ ])+ model.teamsReader = teams+ await model.reloadShareRemovals()+ let note = try #require(model.shareRemovalNote)+ #expect(note.text == "[email protected] and [email protected] can no longer open \u{201c}Design\u{201d}, because they're not in your team.")+ #expect(note.action.label == "Invite to your team")+ model.dismissShareRemovalNote()+ #expect(model.shareRemovalNote == nil)+ try await Task.sleep(for: .milliseconds(100))+ #expect(teams.removals.isEmpty, "acknowledged, so it does not come back")+ await model.reloadShareRemovals()+ #expect(model.shareRemovalNote == nil)+ }++ /// The Share sheet explains and links to Teams for an account in no team;+ /// it stays open in a team, and when it cannot tell (the server decides).+ @Test func shareSheetIsClosedOnlyWhenKnownToBeInNoTeam() {+ let model = ShareModel(backend: FixtureSpacesBackend(), spaceId: "local:studio", spaceName: "studio",+ signedIn: true, shareable: true)+ #expect(model.gate == nil, "unknown: the server decides")+ model.hasTeam = true+ #expect(model.gate == nil)+ model.hasTeam = false+ #expect(model.gate?.reason == "Sharing is for teams. Start a team to share this Space.")+ #expect(model.gate?.action.label == "See Teams")+ }+/// Settings hides Cua Cloud billing and shows the real Teams section/// (the Spaces API: name with alias fallback, members, pending invites/// marked "(Invited)", the account app for invites and billing); a clouddiff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex 34835a4446..022ad2e2cf 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -79,6 +79,8 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"sharing.list": { spaceId: SPACE },"sharing.share": { spaceId: SPACE, who: "[email protected]", role: "viewer" },"sharing.unshare": { spaceId: SPACE, who: "[email protected]" },+ "sharing.removals": {},+ "sharing.ackRemovals": {},"agentKeys.list": {},"agentKeys.set": { provider: "anthropic", value: "sk-ant-test-0000" },"agentKeys.remove": { env: "ANTHROPIC_API_KEY" },diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex 146ff99b18..ed08d5001d 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -76,6 +76,8 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {"sharing.list": { spaceId: "s1" },"sharing.share": { spaceId: "s1", who: "[email protected]", role: "viewer" },"sharing.unshare": { spaceId: "s1", who: "[email protected]" },+ "sharing.removals": {},+ "sharing.ackRemovals": {},"volume.overview": {},"volume.storage": {},"volume.storageSet": { update: { backend: "fs", s3: null, access_key_id: null, secret_access_key: null, dry_run: true } },diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/share.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/share.tsindex 5366547a32..8d148697ef 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/share.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/share.ts@@ -26,6 +26,8 @@ export function demoShareHandlers({ wait, stepMs }: { wait(ms: number): Promise<shares.set(spaceId, [...rest, { who, role, connected: was?.connected ?? false }]);return list(spaceId);},+ "sharing.removals": async () => [],+ "sharing.ackRemovals": async () => null,"sharing.unshare": async ({ spaceId, who }) => {shares.set(spaceId,diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex e604387bd2..afebb643ea 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -2479,6 +2479,21 @@"role"]},+ "ShareRemoval": {+ "type": "object",+ "properties": {+ "who": {+ "type": "string"+ },+ "machineName": {+ "type": "string"+ }+ },+ "required": [+ "who",+ "machineName"+ ]+ },"SpaceProgress": {"type": "object","properties": {@@ -5130,12 +5145,21 @@"settings.set": {"$ref": "#/$defs/SettingsSnapshot"},+ "sharing.ackRemovals": {+ "type": "null"+ },"sharing.list": {"type": "array","items": {"$ref": "#/$defs/ShareEntry"}},+ "sharing.removals": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/ShareRemoval"+ }+ },"sharing.share": {"type": "array","items": {@@ -6684,12 +6708,21 @@"settings.get": {"$ref": "#/$defs/WkSettings"},+ "sharing.ackRemovals": {+ "type": "null"+ },"sharing.list": {"type": "array","items": {"$ref": "#/$defs/ShareEntry"}},+ "sharing.removals": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/ShareRemoval"+ }+ },"sharing.share": {"type": "array","items": {diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex d782d0d521..046d097782 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -53,7 +53,7 @@ import type {} from "./new-space";import type { NotificationInput } from "./notifications";import type { AboutInput, DriveCheckInput, DriveStorageInput, LoginItemReport, StorageInput, UpdateState } from "./settings";-import type { ShareEntry } from "./share";+import type { ShareEntry, ShareRemoval } from "./share";import type { SpaceProgress, SpaceRow } from "./spaces";import type { CatalogEntry, ConsentItem, KvDomainCount, KvInventory, OpenWindow, PlanStep, RemoteWindow, RunReport, TeleportPlan } from "./teleport";import type { AgentSetupOutcome, DriveGrantInput, DriveMountInput, DriveRequestInput, Experiments, VolumeOverview } from "./volume";@@ -670,6 +670,8 @@ const AgentOpenFileShape = ref(}),);const shares = list(ShareShape);+const ShareRemovalShape = ref("ShareRemoval", obj<ShareRemoval>()({ who: str, machineName: str }));+const shareRemovals = list(ShareRemovalShape);const PresenceParticipantShape = ref("PresenceParticipant",obj<PresenceParticipantWire>()({ participantId: str, principalId: str, displayName: str, color: str, kind: str }),@@ -849,6 +851,8 @@ export const OP_SHAPES: Record<OpName, Schema> = {"sharing.list": shares,"sharing.share": shares,"sharing.unshare": shares,+ "sharing.removals": shareRemovals,+ "sharing.ackRemovals": nul,"agentKeys.list": AgentKeysShape,"agentKeys.set": AgentKeysShape,@@ -1243,6 +1247,8 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"sharing.list": shares,"sharing.share": shares,"sharing.unshare": shares,+ "sharing.removals": shareRemovals,+ "sharing.ackRemovals": nul,"volume.overview": VolumeShape,"volume.storage": nullable(DriveStorageShape),"volume.storageSet": DriveCheckShape,diff --git a/apps/cua-spaces-web/src/bridge/contracts/share.ts b/apps/cua-spaces-web/src/bridge/contracts/share.tsindex bab057bdce..6764a08f58 100644--- a/apps/cua-spaces-web/src/bridge/contracts/share.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/share.ts@@ -25,6 +25,27 @@ export interface ShareInput {shareable: boolean;}+/** Why the sheet cannot share and what to do about it (`share::ShareGate`):+ * sharing is for teams, so an account without one is sent to Teams. */+export interface ShareGate {+ reason: string;+ action: { label: string; url: string };+}++/** Someone who lost access to a computer because sharing became team-only+ * (`sharing.removals`). */+export interface ShareRemoval {+ who: string;+ machineName: string;+}++/** The owner's one-line note about them (`share::ShareRemovalNote`). */+export interface ShareRemovalNote {+ text: string;+ action: { label: string; url: string };+ dismiss: string;+}+/** The command the host runs next (`share::ShareRequest`). */export type ShareRequest =| { kind: "share"; space: string; who: string; role: string }diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex 7259afbfea..82d984283a 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -54,6 +54,7 @@ export type {export type { TranscriptItem, TranscriptStep } from "./transcript";export { GRID_COLUMNS, iconKey, thumbnailKey, useTeleport, type TeleportHook, type TeleportSession, type TeleportStore } from "./teleport";export { useShareSheet, type ShareHook, type ShareSession } from "./share";+export { useShareRemovalNote, type ShareRemovalNoteHook } from "./removal-note";export {agentKeyForm,agentKeysView,diff --git a/apps/cua-spaces-web/src/bridge/ops/share.ts b/apps/cua-spaces-web/src/bridge/ops/share.tsindex d506e67f54..e0116499f5 100644--- a/apps/cua-spaces-web/src/bridge/ops/share.ts+++ b/apps/cua-spaces-web/src/bridge/ops/share.ts@@ -15,20 +15,29 @@* | `sharing.list` `{spaceId}` | `space_shares` |* | `sharing.share` `{spaceId, who, role}` | `share_space` (also changes a role) |* | `sharing.unshare` `{spaceId, who}` | `unshare_space` |+ * | `sharing.removals` `{}` | `share_removals` |+ * | `sharing.ackRemovals` `{}` | `ack_share_removals` |*- * Each answers the people the Space is shared with afterwards.+ * The first three answer the people the Space is shared with afterwards.+ * `sharing.removals` answers who lost access to which computer when sharing+ * became team-only (the owner's one-line note, worded by `share.removalNote`);+ * `sharing.ackRemovals` marks them seen. A host without them shows no note.** **Native hosts** (the Electron shell answers the Swift host's methods): (`WebUIBridge+Pages.swift`): `sharing.list/share/unshare`* with the same args go to `SpacesBackend.shares/share/unshare(id:...)`, as* `ShareModel` calls them.*/-import type { ShareEntry } from "../contracts/share";+import type { ShareEntry, ShareRemoval } from "../contracts/share";export interface ShareOperations {"sharing.list": { args: { spaceId: string }; result: ShareEntry[] };"sharing.share": { args: { spaceId: string; who: string; role: string }; result: ShareEntry[] };"sharing.unshare": { args: { spaceId: string; who: string }; result: ShareEntry[] };+ /** People removed from the account's shared computers (sharing became team-only), until acknowledged. */+ "sharing.removals": { args: Record<string, never>; result: ShareRemoval[] };+ /** The owner has seen the note: it is not shown again. */+ "sharing.ackRemovals": { args: Record<string, never>; result: null };}export type ShareOpName = keyof ShareOperations;@@ -36,7 +45,7 @@ export type ShareHandlers = {[K in ShareOpName]: (args: ShareOperations[K]["args"]) => Promise<ShareOperations[K]["result"]>;};-export const SHARE_OPERATIONS = ["sharing.list", "sharing.share", "sharing.unshare"] as const satisfies readonly ShareOpName[];+export const SHARE_OPERATIONS = ["sharing.list", "sharing.share", "sharing.unshare", "sharing.removals", "sharing.ackRemovals"] as const satisfies readonly ShareOpName[];const row = <K extends ShareOpName>(op: K, tauri: string) => ({webkit: { methods: [op] as const },@@ -47,6 +56,8 @@ export const SHARE_COVERAGE = {"sharing.list": row("sharing.list", "space_shares"),"sharing.share": row("sharing.share", "share_space"),"sharing.unshare": row("sharing.unshare", "unshare_space"),+ "sharing.removals": row("sharing.removals", "share_removals"),+ "sharing.ackRemovals": row("sharing.ackRemovals", "ack_share_removals"),} as const;/** `cua_spaces::share::SpaceShares`: the people are its `shares`. */@@ -60,5 +71,10 @@ export function tauriShareOps(invoke: Invoke): ShareHandlers {"sharing.list": async ({ spaceId }) => people(await invoke("space_shares", { spaceId })),"sharing.share": async ({ spaceId, who, role }) => people(await invoke("share_space", { spaceId, who, role })),"sharing.unshare": async ({ spaceId, who }) => people(await invoke("unshare_space", { spaceId, who })),+ "sharing.removals": async () => (await invoke<ShareRemoval[] | null>("share_removals")) ?? [],+ "sharing.ackRemovals": async () => {+ await invoke("ack_share_removals");+ return null;+ },};}diff --git a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.tsindex c9b99eda9e..98fdb20058 100644--- a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts+++ b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts@@ -53,6 +53,8 @@ export const WEBKIT_PAGE_OPS = ["sharing.list","sharing.share","sharing.unshare",+ "sharing.removals",+ "sharing.ackRemovals","volume.overview","volume.storage","volume.storageSet",@@ -228,6 +230,8 @@ export function webkitPageOps(request: Request, toHostStatus: (h: WkHostState) ="sharing.list": list("sharing.list"),"sharing.share": list("sharing.share"),"sharing.unshare": list("sharing.unshare"),+ "sharing.removals": list("sharing.removals"),+ "sharing.ackRemovals": none("sharing.ackRemovals"),"volume.overview": call("volume.overview"),"volume.storage": call("volume.storage"),diff --git a/apps/cua-spaces-web/src/bridge/removal-note.ts b/apps/cua-spaces-web/src/bridge/removal-note.tsnew file mode 100644index 0000000000..5040e67611--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/removal-note.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * `useShareRemovalNote()`: the owner's one-line note that sharing became+ * team-only and some people can no longer open a shared computer (CUA-1883).+ * The host says who was removed (`sharing.removals`); the app core words the+ * line (`share.removalNote`); dismissing it acknowledges it+ * (`sharing.ackRemovals`), so it shows once.+ *+ * Reads the adapter directly: a host without the operation, a signed-out+ * account or a failed read shows nothing.+ */++import { useCallback, useContext, useEffect, useState } from "react";++import { BridgeContext } from "./BridgeProvider";+import type { ShareRemoval, ShareRemovalNote } from "./contracts/share";++export interface ShareRemovalNoteHook {+ /** The note while there is someone to name and it is not dismissed; null otherwise. */+ note: ShareRemovalNote | null;+ /** Closes the note and tells the host it was seen. */+ dismiss(): Promise<void>;+}++export function useShareRemovalNote(signedIn: boolean): ShareRemovalNoteHook {+ const ctx = useContext(BridgeContext);+ if (!ctx) throw new Error("bridge hooks need a <BridgeProvider> above them");+ const { adapter, core } = ctx;+ const [note, setNote] = useState<ShareRemovalNote | null>(null);++ useEffect(() => {+ if (!adapter || !signedIn) return;+ let live = true;+ void adapter.call("sharing.removals", {}).then(+ (removals: ShareRemoval[]) => {+ if (!live) return;+ setNote(core.tryCall<ShareRemovalNote | null>("share.removalNote", { removals }) ?? null);+ },+ () => undefined,+ );+ return () => {+ live = false;+ };+ }, [adapter, core, signedIn]);++ const dismiss = useCallback(async () => {+ setNote(null);+ try {+ await adapter?.call("sharing.ackRemovals", {});+ } catch {+ /* shown again next time, which is better than losing it */+ }+ }, [adapter]);++ return { note, dismiss };+}diff --git a/apps/cua-spaces-web/src/bridge/share.ts b/apps/cua-spaces-web/src/bridge/share.tsindex 00f3b4e799..9e74b5e020 100644--- a/apps/cua-spaces-web/src/bridge/share.ts+++ b/apps/cua-spaces-web/src/bridge/share.ts@@ -15,7 +15,7 @@ import type { DataAdapter } from "./adapter";import { BridgeContext } from "./BridgeProvider";import { checklistDone } from "./checklist";import type { CoreClient } from "./core";-import type { ShareEntry, ShareInput, ShareSheetAction, ShareSheetState, ShareSheetView } from "./contracts/share";+import type { ShareEntry, ShareGate, ShareInput, ShareSheetAction, ShareSheetState, ShareSheetView } from "./contracts/share";import type { Space } from "./contracts/spaces";import type { BridgeStore } from "./store";import { telemetryShare, type TelemetrySignal } from "./telemetry";@@ -35,12 +35,16 @@ export interface ShareSession {input: ShareInput;state: ShareSheetState;view: ShareSheetView;+ /** Closed because the account is in no team (null: open, or not known). */+ gate: ShareGate | null;}const words = (e: unknown) => (e instanceof Error ? e.message : String(e));export class ShareStore {private session: { input: ShareInput; state: ShareSheetState } | null = null;+ /** In a team that can share; null until the host says. */+ private hasTeam: boolean | null = null;private view: ShareSession | null = null;private listeners = new Set<() => void>();@@ -62,7 +66,8 @@ export class ShareStore {private publish(): void {const s = this.session;- this.view = s ? { ...s, view: shareView(this.core, s.input, s.state) } : null;+ const gate = this.core.tryCall<ShareGate | null>("share.gate", { hasTeam: this.hasTeam }) ?? null;+ this.view = s ? { ...s, view: shareView(this.core, s.input, s.state), gate } : null;for (const l of [...this.listeners]) l();}@@ -87,6 +92,13 @@ export class ShareStore {);}+ /** Whether the account is in a team that can share (null: not known). */+ setHasTeam(hasTeam: boolean | null): void {+ if (this.hasTeam === hasTeam) return;+ this.hasTeam = hasTeam;+ if (this.session) this.publish();+ }+close(): void {this.session = null;this.publish();@@ -120,7 +132,9 @@ export class ShareStore {if (request.who.includes("@")) noteTeammates();}} catch (e) {- outcome = { type: "failed", error: words(e) };+ // A refusal for who is not in the team (or no team) reads in plain words.+ const plain = this.core.tryCall<string | null>("share.errorWords", { error: words(e), who: request.who });+ outcome = { type: "failed", error: plain ?? words(e) };}this.track(telemetryShare(this.core, before, state, outcome));const now = this.session;diff --git a/apps/cua-spaces-web/src/bridge/teams.ts b/apps/cua-spaces-web/src/bridge/teams.tsindex e959bb33fb..ae5d193fea 100644--- a/apps/cua-spaces-web/src/bridge/teams.ts+++ b/apps/cua-spaces-web/src/bridge/teams.ts@@ -29,7 +29,15 @@ export function teamName(t: Pick<TeamChoice, "name" | "alias" | "id">): string {return t.name || t.alias || t.id;}+/** The account is in a team on the Teams plan, which is what sharing needs+ * (any role: a member shares with teammates). `null` until the list is read. */+export function hasSharingTeam(list: TeamsList | null | undefined): boolean | null {+ return list ? list.teams.some((t) => t.plan === "teams") : null;+}+export interface TeamChoices {+ /** In a team that can share; null until read, or when the host cannot say. */+ hasTeam: boolean | null;/** The teams offered (current team first). */teams: TeamChoice[];/** The current team, when it is offered. */@@ -38,7 +46,7 @@ export interface TeamChoices {all: TeamChoice[];}-const NONE: TeamChoices = { teams: [], current: null, all: [] };+const NONE: TeamChoices = { hasTeam: null, teams: [], current: null, all: [] };/** The teams to offer, read once while `enabled` (none on a host without Teams). */export function useTeamChoices(enabled: boolean): TeamChoices {@@ -52,7 +60,7 @@ export function useTeamChoices(enabled: boolean): TeamChoices {if (stopped) return;const current = defaultTeam(list);const teams = eligibleTeams(list).sort((a, b) => Number(b.id === current) - Number(a.id === current));- setChoices({ teams, current, all: list.teams });+ setChoices({ hasTeam: hasSharingTeam(list), teams, current, all: list.teams });},() => {if (!stopped) setChoices(NONE);diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 643b6421b2..71b2cf9d5a 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -91,6 +91,8 @@ export const WEBKIT_METHODS = ["sharing.list","sharing.share","sharing.unshare",+ "sharing.removals",+ "sharing.ackRemovals","volume.overview","volume.storage","volume.storageSet",diff --git a/apps/cua-spaces-web/src/components/__tests__/share-removal-notice.test.tsx b/apps/cua-spaces-web/src/components/__tests__/share-removal-notice.test.tsxnew file mode 100644index 0000000000..af185c9ecc--- /dev/null+++ b/apps/cua-spaces-web/src/components/__tests__/share-removal-notice.test.tsx@@ -0,0 +1,86 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import { BridgeProvider } from "@/bridge";+import type { DataAdapter } from "@/bridge/adapter";+import { createDemoAdapter } from "@/bridge/adapters/demo";+import type { CoreClient } from "@/bridge/core";+import { ShareRemovalNotice } from "@/components/shell/share-removal-notice";++afterEach(cleanup);++const NOTE = {+ text: "[email protected] and [email protected] can no longer open “Design”, because they're not in your team.",+ action: { label: "Invite to your team", url: "https://app.cua.ai/team" },+ dismiss: "Dismiss",+};++/** The core's `share.removalNote`, as far as these tests need it. */+const core = (): CoreClient => ({+ status: "ready",+ methods: ["share.removalNote"],+ call: () => {+ throw new Error("unused");+ },+ tryCall: <T,>(method: string, args: Record<string, unknown> = {}) =>+ (method === "share.removalNote" && (args.removals as unknown[]).length > 0 ? NOTE : null) as T,+});++function host(removals: { who: string; machineName: string }[], signedIn = true) {+ const base = createDemoAdapter({ latencyMs: 0, stepMs: 0, signedIn, onboarded: true });+ const calls: string[] = [];+ const adapter = Object.assign(Object.create(base) as DataAdapter, {+ call: ((op: string, args: unknown) => {+ if (op === "sharing.removals") {+ calls.push(op);+ return Promise.resolve(removals);+ }+ if (op === "sharing.ackRemovals") {+ calls.push(op);+ return Promise.resolve(null);+ }+ return (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args);+ }) as DataAdapter["call"],+ });+ return { adapter, calls };+}++const mount = (adapter: DataAdapter) =>+ render(+ <BridgeProvider adapter={adapter} core={core()}>+ <ShareRemovalNotice />+ </BridgeProvider>,+ );++describe("The note about people removed from shared computers", () => {+ it("shows one line with an invite button, and acknowledges it once dismissed", async () => {+ const { adapter, calls } = host([+ { who: "[email protected]", machineName: "Design" },+ { who: "[email protected]", machineName: "Design" },+ ]);+ mount(adapter);+ await waitFor(() => expect(screen.getByText(NOTE.text)).toBeTruthy());+ expect(screen.getByText("Invite to your team")).toBeTruthy();+ fireEvent.click(screen.getByLabelText("Dismiss"));+ await waitFor(() => expect(calls).toEqual(["sharing.removals", "sharing.ackRemovals"]));+ expect(document.querySelector("[data-share-removal]")).toBeNull();+ });++ it("shows nothing when nobody was removed", async () => {+ const { adapter, calls } = host([]);+ mount(adapter);+ await act(() => new Promise((r) => setTimeout(r, 20)));+ expect(calls).toEqual(["sharing.removals"]);+ expect(document.querySelector("[data-share-removal]")).toBeNull();+ });++ it("does not ask while signed out", async () => {+ const { adapter, calls } = host([{ who: "[email protected]", machineName: "Design" }], false);+ mount(adapter);+ await act(() => new Promise((r) => setTimeout(r, 20)));+ expect(calls).toEqual([]);+ });+});diff --git a/apps/cua-spaces-web/src/components/__tests__/share-sheet-teams.test.tsx b/apps/cua-spaces-web/src/components/__tests__/share-sheet-teams.test.tsxindex d1f280b98b..3ebb0a3d89 100644--- a/apps/cua-spaces-web/src/components/__tests__/share-sheet-teams.test.tsx+++ b/apps/cua-spaces-web/src/components/__tests__/share-sheet-teams.test.tsx@@ -72,15 +72,22 @@ function shareCore(): CoreClient {throw new Error(`no ${method}`);}};- return { status: "ready", methods: ["share.initial", "share.reduce", "share.view"], call, tryCall: () => undefined };+ // The core's `share.gate`: closed only when the account is known to be in no team.+ const tryCall = <T,>(method: string, args: Record<string, unknown> = {}): T | undefined =>+ method === "share.gate"+ ? ((args.hasTeam === false+ ? { reason: "Sharing is for teams. Start a team to share this Space.", action: { label: "See Teams", url: "https://app.cua.ai/buy/teams?from=app_share" } }+ : null) as T)+ : undefined;+ return { status: "ready", methods: ["share.initial", "share.reduce", "share.view", "share.gate"], call, tryCall };}-function host() {+function host(teams: typeof TEAMS | Record<string, never> = TEAMS) {const base = createDemoAdapter({ latencyMs: 0, stepMs: 0, signedIn: true, onboarded: true });const shared: Record<string, unknown>[] = [];const adapter = Object.assign(Object.create(base) as DataAdapter, {call: ((op: string, args: Record<string, unknown>) => {- if (op === "teams.list") return Promise.resolve(TEAMS);+ if (op === "teams.list") return Promise.resolve(teams);if (op === "sharing.list") return Promise.resolve([]);if (op === "sharing.share") {shared.push(args);@@ -129,4 +136,29 @@ describe("Teams in Share and Add a machine", () => {// Shared with Acme: only Beta is offered now.expect([...document.querySelectorAll("[data-share-team]")].map((b) => b.textContent)).toEqual(["Share with Beta"]);});++ it("without a team the sheet explains, links to Teams and offers nothing to share with", async () => {+ const opened: string[] = [];+ const { adapter } = host({ teams: [], currentTeamId: null } as never);+ const base = adapter.call as (o: string, a: unknown) => Promise<unknown>;+ (adapter as { call: unknown }).call = (op: string, args: Record<string, unknown>) => {+ if (op === "session.openExternal") {+ opened.push(String(args.url));+ return Promise.resolve(null);+ }+ return base(op, args);+ };+ render(+ <BridgeProvider adapter={adapter} core={shareCore()}>+ <Opener />+ <ShareSheet />+ </BridgeProvider>,+ );+ await act(() => new Promise((r) => setTimeout(r, 10)));+ fireEvent.click(screen.getByText("open"));+ await waitFor(() => expect(document.querySelector("[data-share-disabled]")?.textContent).toBe("Sharing is for teams. Start a team to share this Space."));+ expect(document.querySelector("[data-share-teams]")).toBeNull();+ expect((document.querySelector("[data-share-who]") as HTMLInputElement).disabled).toBe(true);+ expect(screen.getByText("See Teams")).toBeTruthy();+ });});diff --git a/apps/cua-spaces-web/src/components/share-sheet.tsx b/apps/cua-spaces-web/src/components/share-sheet.tsxindex c0ca3f67b8..987cea442f 100644--- a/apps/cua-spaces-web/src/components/share-sheet.tsx+++ b/apps/cua-spaces-web/src/components/share-sheet.tsx@@ -1,7 +1,15 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { teamName, useFeatureRecorded, useShareSheet, useTeamChoices } from "@/bridge";+import { useEffect } from "react";++import {+ teamName,+ useFeatureRecorded,+ useSession,+ useShareSheet,+ useTeamChoices,+} from "@/bridge";import { Button } from "@/components/ui/button";import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";@@ -15,15 +23,23 @@ import { cn } from "@/lib/utils";* core's (`share.view`); sharing asks for presence in the daemon before it* reaches the relay. "Share with team" offers the account's teams that can* take machines (owner or admin, Teams plan), the current team first: it- * shares with `team:<id>`, as typing it would.+ * shares with `team:<id>`, as typing it would, as "Can view" or "Can edit".+ * Sharing is for teams: without one the sheet says so and links to Teams.*/export default function ShareSheet() {const { session, sharing } = useShareSheet();useFeatureRecorded("share_open", Boolean(session));const choices = useTeamChoices(Boolean(session?.input.signedIn && session.input.shareable));+ const { openExternal } = useSession();+ const { hasTeam } = choices;+ useEffect(() => {+ sharing?.setHasTeam(hasTeam);+ }, [sharing, hasTeam, session?.input.spaceId]);if (!session || !sharing) return null;const v = session.view;- const locked = v.busy || v.disabledReason !== null;+ const gate = session.gate;+ const closed = v.disabledReason !== null || gate !== null;+ const locked = v.busy || closed;const roles = v.roles.map((r) => ({ value: r.id, label: r.label }));const send = sharing.send.bind(sharing);const shared = new Set(v.rows.map((r) => r.who));@@ -44,11 +60,16 @@ export default function ShareSheet() {<DialogTitle className="text-[15px] font-semibold" data-share-title>{v.title}</DialogTitle>- {v.disabledReason ? (+ {v.disabledReason || gate ? (<p className="mt-1.5 text-[13px] text-muted-foreground" data-share-disabled>- {v.disabledReason}+ {v.disabledReason ?? gate?.reason}</p>) : null}+ {!v.disabledReason && gate ? (+ <Button size="sm" variant="outline" className="mt-2" onClick={() => void openExternal(gate.action.url).catch(() => {})} data-share-action>+ {gate.action.label}+ </Button>+ ) : null}<formclassName="mt-4 flex items-center gap-2"@@ -61,18 +82,18 @@ export default function ShareSheet() {aria-label={v.whoPlaceholder}placeholder={v.whoPlaceholder}value={v.who}- disabled={v.disabledReason !== null}+ disabled={closed}onChange={(e) => void send({ type: "set-who", who: e.target.value })}data-share-who/><span data-share-role={v.role}><Select aria-label="Role" className="h-8 min-w-28" value={v.role} options={roles} onValueChange={(role) => void send({ type: "set-role", role })} /></span>- <Button type="submit" disabled={!v.canShare} data-share-submit>+ <Button type="submit" disabled={!v.canShare || closed} data-share-submit>{v.shareLabel}</Button></form>- {offered.length > 0 && v.disabledReason === null ? (+ {offered.length > 0 && !closed ? (<div className="mt-3 flex flex-wrap items-center gap-2" data-share-teams>{offered.map((t) => (<Button key={t.id} size="sm" variant="outline" disabled={v.busy} onClick={() => void shareWithTeam(t.id)} data-share-team={t.id}>diff --git a/apps/cua-spaces-web/src/components/shell/share-removal-notice.tsx b/apps/cua-spaces-web/src/components/shell/share-removal-notice.tsxnew file mode 100644index 0000000000..12e0e8fcac--- /dev/null+++ b/apps/cua-spaces-web/src/components/shell/share-removal-notice.tsx@@ -0,0 +1,30 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { XIcon } from "lucide-react";++import { useSession, useShareRemovalNote } from "@/bridge";+import { Button } from "@/components/ui/button";++/**+ * Sharing is for teams now (CUA-1883): the owner sees once, in one line,+ * who can no longer open a shared computer, with "Invite to your team".+ * The words are the app core's (`share.removalNote`); closing it tells the+ * host it was seen, so it does not come back.+ */+export function ShareRemovalNotice() {+ const { data: session, openExternal } = useSession();+ const { note, dismiss } = useShareRemovalNote(Boolean(session?.signedIn));+ if (!note) return null;+ return (+ <div role="status" data-share-removal="" className="flex shrink-0 items-center gap-3 border-b px-4 py-2 text-xs text-muted-foreground">+ <span className="min-w-0 flex-1">{note.text}</span>+ <Button size="sm" variant="outline" data-share-removal-invite="" onClick={() => void openExternal(note.action.url).catch(() => {})}>+ {note.action.label}+ </Button>+ <Button size="icon-sm" variant="ghost" aria-label={note.dismiss} data-share-removal-dismiss="" onClick={() => void dismiss()}>+ <XIcon className="size-3.5" />+ </Button>+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/routes/__root.tsx b/apps/cua-spaces-web/src/routes/__root.tsxindex 7146a62269..eac025e405 100644--- a/apps/cua-spaces-web/src/routes/__root.tsx+++ b/apps/cua-spaces-web/src/routes/__root.tsx@@ -12,6 +12,7 @@ import { CommandPalette } from "@/components/shell/command-palette";import { DevicesBanner } from "@/components/shell/devices-banner";import { Sidebar } from "@/components/shell/sidebar";import { RelayAllowanceNotice } from "@/components/shell/relay-allowance-notice";+import { ShareRemovalNotice } from "@/components/shell/share-removal-notice";import { SpacesNotice } from "@/components/shell/spaces-notice";import { SpaceSheets } from "@/components/space-sheets";import { UsageLinkNotice } from "@/components/usage-link-notice";@@ -70,6 +71,7 @@ function RootLayout() {<TopBar /><DevicesBanner /><SpacesNotice />+ <ShareRemovalNotice /><RelayAllowanceNotice /><main className="min-h-0 flex-1"><Outlet />diff --git a/apps/cua-spaces/src-tauri/src/commands.rs b/apps/cua-spaces/src-tauri/src/commands.rsindex d5c43530f6..3700439776 100644--- a/apps/cua-spaces/src-tauri/src/commands.rs+++ b/apps/cua-spaces/src-tauri/src/commands.rs@@ -1052,6 +1052,20 @@ pub async fn unshare_space(state.0.unshare_space(&space_id, &who).await}+/// Who lost access to the account's shared computers (sharing is for teams).+#[tauri::command]+pub async fn share_removals(+ state: State<'_, AppState>,+) -> CmdResult<Vec<crate::share::ShareRemovalView>> {+ state.0.share_removals().await+}++/// The owner has seen the removal note.+#[tauri::command]+pub async fn ack_share_removals(state: State<'_, AppState>) -> CmdResult<()> {+ state.0.ack_share_removals().await+}+// ------------------------------------------------------------- your cloud/// Runs one cloud tool (status, a test that creates nothing, connect) indiff --git a/apps/cua-spaces/src-tauri/src/lib.rs b/apps/cua-spaces/src-tauri/src/lib.rsindex 6842068fee..50c4cc15c4 100644--- a/apps/cua-spaces/src-tauri/src/lib.rs+++ b/apps/cua-spaces/src-tauri/src/lib.rs@@ -552,6 +552,8 @@ pub fn run() {commands::share_space,commands::cloud_tool,commands::unshare_space,+ commands::share_removals,+ commands::ack_share_removals,commands::agents_tool,commands::drive_reveal,tray::tray_set_menu,diff --git a/apps/cua-spaces/src-tauri/src/share.rs b/apps/cua-spaces/src-tauri/src/share.rsindex 5daf0e2a3e..ae44234df6 100644--- a/apps/cua-spaces/src-tauri/src/share.rs+++ b/apps/cua-spaces/src-tauri/src/share.rs@@ -29,6 +29,15 @@ impl ShareConsent for AppShareConsent {}}+/// Someone who lost access to a computer because sharing is for teams now+/// (the Share note's input; `share.removalNote` words it).+#[derive(Debug, Clone, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ShareRemovalView {+ pub who: String,+ pub machine_name: String,+}+fn msg(e: impl std::fmt::Display) -> String {e.to_string()}@@ -48,6 +57,27 @@ impl AppCore {.map_err(msg)}+ /// Who lost access to the account's shared computers since the owner+ /// last acknowledged (none on a server that predates team-only sharing).+ pub async fn share_removals(&self) -> CmdResult<Vec<ShareRemovalView>> {+ Ok(self+ .spaces()+ .share_removals()+ .await+ .map_err(msg)?+ .into_iter()+ .map(|r| ShareRemovalView {+ who: r.who,+ machine_name: r.machine_name,+ })+ .collect())+ }++ /// The owner has seen the note.+ pub async fn ack_share_removals(&self) -> CmdResult<()> {+ self.spaces().ack_share_removals().await.map_err(msg)+ }+/// Stops sharing `space` with `who`.pub async fn unshare_space(&self, space: &str, who: &str) -> CmdResult<SpaceShares> {self.spaces()diff --git a/apps/cua-spaces/src/components/ShareSheet.test.tsx b/apps/cua-spaces/src/components/ShareSheet.test.tsxindex a07023da10..2f3c762b9b 100644--- a/apps/cua-spaces/src/components/ShareSheet.test.tsx+++ b/apps/cua-spaces/src/components/ShareSheet.test.tsx@@ -5,7 +5,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { describe, expect, it } from 'vitest';import { createFakeShareBridge } from '../native/share';-import { ShareSheet } from './ShareSheet';+import { ShareRemovalBanner, ShareSheet } from './ShareSheet';const props = {spaceId: 'local:studio',@@ -55,4 +55,81 @@ describe('ShareSheet', () => {true);});++ it('explains that sharing is for teams, links to Teams and offers nothing, without a team', async () => {+ const opened: string[] = [];+ render(+ <ShareSheet+ bridge={createFakeShareBridge({ hasTeam: false })}+ {...props}+ onOpenExternal={(url) => opened.push(url)}+ />+ );+ expect(+ await screen.findByText('Sharing is for teams. Start a team to share this Space.')+ ).toBeTruthy();+ expect((screen.getByLabelText('Email or account ID') as HTMLInputElement).disabled).toBe(true);+ expect((screen.getByRole('button', { name: 'Share' }) as HTMLButtonElement).disabled).toBe(+ true+ );+ fireEvent.click(screen.getByRole('button', { name: 'See Teams' }));+ expect(opened).toEqual(['https://app.cua.ai/buy/teams?from=app_share']);+ });++ it('stays open in a team, and when it cannot tell (the server decides)', async () => {+ for (const hasTeam of [true, null]) {+ const { unmount } = render(+ <ShareSheet bridge={createFakeShareBridge({ hasTeam })} {...props} />+ );+ await screen.findByText('Only you');+ expect(screen.queryByRole('button', { name: 'See Teams' })).toBeNull();+ unmount();+ }+ });++ it('shows the server refusal in plain words: the sheet is not the only check', async () => {+ // The sheet lets the share through; the server says no.+ const bridge = createFakeShareBridge({ refuses: 'HTTP 403: share_outside_team', hasTeam: true });+ render(<ShareSheet bridge={bridge} {...props} />);+ fireEvent.change(screen.getByLabelText('Email or account ID'), {+ target: { value: '[email protected]' },+ });+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));+ expect((await screen.findByRole('alert')).textContent).toBe(+ "[email protected] isn't in your team. Invite them to your team first."+ );+ expect(bridge.calls).toContain('share:local:studio:[email protected]:viewer');+ });+});++describe('ShareRemovalBanner', () => {+ it('names who was removed once, offers the invite and acknowledges when closed', async () => {+ const bridge = createFakeShareBridge({+ removals: [+ { who: '[email protected]', machineName: 'Design' },+ { who: '[email protected]', machineName: 'Design' },+ ],+ });+ const opened: string[] = [];+ render(<ShareRemovalBanner bridge={bridge} signedIn onOpenExternal={(u) => opened.push(u)} />);+ expect(+ await screen.findByText(+ '[email protected] and [email protected] can no longer open \u201cDesign\u201d, because they\'re not in your team.'+ )+ ).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Invite to your team' }));+ expect(opened).toEqual(['https://app.cua.ai/team']);+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ await waitFor(() => expect(bridge.calls).toContain('ackRemovals'));+ expect(screen.queryByRole('status')).toBeNull();+ });++ it('shows nothing when nobody was removed or signed out', async () => {+ const bridge = createFakeShareBridge();+ const { rerender } = render(<ShareRemovalBanner bridge={bridge} signedIn onOpenExternal={() => {}} />);+ await waitFor(() => expect(bridge.calls).toContain('removals'));+ expect(screen.queryByRole('status')).toBeNull();+ rerender(<ShareRemovalBanner bridge={createFakeShareBridge({ removals: [{ who: '[email protected]', machineName: 'D' }] })} signedIn={false} onOpenExternal={() => {}} />);+ expect(screen.queryByRole('status')).toBeNull();+ });});diff --git a/apps/cua-spaces/src/components/ShareSheet.tsx b/apps/cua-spaces/src/components/ShareSheet.tsxindex 1d3590aedd..deddb044eb 100644--- a/apps/cua-spaces/src/components/ShareSheet.tsx+++ b/apps/cua-spaces/src/components/ShareSheet.tsx@@ -6,9 +6,13 @@ import { useCallback, useEffect, useState } from 'react';import {reduceShare,shareInitial,+ shareErrorWords,+ shareGate,+ shareRemovalNote,shareView,type ShareEntryInput,type ShareInput,+ type ShareRemovalNote,type ShareSheetAction,} from '../model/share';import type { ShareBridge } from '../native/share';@@ -31,6 +35,7 @@ export function ShareSheet({signedIn,shareable,onClose,+ onOpenExternal,}: {bridge: ShareBridge;spaceId: string;@@ -38,13 +43,19 @@ export function ShareSheet({signedIn: boolean;shareable: boolean;onClose: () => void;+ /** Opens a link (See Teams) in the browser. */+ onOpenExternal?: (url: string) => void;}) {const [shares, setShares] = useState<ShareEntryInput[]>([]);+ // In a team that can share; null until read, or when it cannot be said.+ const [hasTeam, setHasTeam] = useState<boolean | null>(null);// Sharing adoption: the sheet was opened.useEffect(() => telemetryBridge().recordSignals(featureSignals('share_open')), []);const [state, setState] = useState(shareInitial);const input: ShareInput = { spaceId, spaceName, shares, signedIn, shareable };const v = shareView(input, state);+ const gate = signedIn && shareable ? shareGate(hasTeam) : null;+ const closed = Boolean(v.disabledReason) || gate !== null;useEffect(() => {if (!signedIn) return;@@ -54,6 +65,11 @@ export function ShareSheet({);}, [bridge, spaceId, signedIn]);+ useEffect(() => {+ if (!signedIn) return;+ void bridge.hasTeam().then(setHasTeam, () => {});+ }, [bridge, signedIn]);+const run = useCallback(async (action: ShareSheetAction) => {const next = reduceShare(input, state, action);@@ -72,7 +88,12 @@ export function ShareSheet({telemetryBridge().recordSignals(shareSignals(input, next, { type: 'done' }));setState((s) => reduceShare({ ...input, shares: r.shares }, s, { type: 'done' }));} catch (e) {- const failed: ShareSheetAction = { type: 'failed', error: message(e) };+ // A refusal for who is not in the team (or no team) reads in plain words.+ const raw = message(e);+ const failed: ShareSheetAction = {+ type: 'failed',+ error: shareErrorWords(raw, request.kind === 'share' ? request.who : '') ?? raw,+ };telemetryBridge().recordSignals(shareSignals(input, next, failed));setState((s) => reduceShare(input, s, failed));}@@ -86,7 +107,7 @@ export function ShareSheet({className="dw-input"aria-label={label}value={value}- disabled={v.busy || Boolean(v.disabledReason)}+ disabled={v.busy || closed}onChange={(e) => onChange(e.target.value)}>{v.roles.map((r) => (@@ -107,7 +128,18 @@ export function ShareSheet({}}><h2 className="dv-sheet-title">{v.title}</h2>- {v.disabledReason && <p className="dv-sheet-text">{v.disabledReason}</p>}+ {(v.disabledReason || gate) && (+ <p className="dv-sheet-text">{v.disabledReason ?? gate?.reason}</p>+ )}+ {!v.disabledReason && gate && (+ <button+ type="button"+ className="dw-btn"+ onClick={() => onOpenExternal?.(gate.action.url)}+ >+ {gate.action.label}+ </button>+ )}<div className="sh-add"><inputclassName="dw-input"@@ -117,11 +149,11 @@ export function ShareSheet({autoFocusspellCheck={false}autoComplete="off"- disabled={v.busy || Boolean(v.disabledReason)}+ disabled={v.busy || closed}onChange={(event) => void run({ type: 'set-who', who: event.target.value })}/>{roleSelect(v.role, (role) => void run({ type: 'set-role', role }), 'Role')}- <button type="submit" className="dw-btn dw-btn-primary" disabled={!v.canShare}>+ <button type="submit" className="dw-btn dw-btn-primary" disabled={!v.canShare || closed}>{v.shareLabel}</button></div>@@ -165,3 +197,48 @@ export function ShareSheet({</SmallSheet>);}++/**+ * Sharing is for teams (CUA-1883): the owner sees once, in one line, who can+ * no longer open a shared computer, with "Invite to your team". The words are+ * the app core's (`share.removalNote`); closing it tells the account it was+ * seen, so it does not come back.+ */+export function ShareRemovalBanner({+ bridge,+ signedIn,+ onOpenExternal,+}: {+ bridge: ShareBridge;+ signedIn: boolean;+ onOpenExternal: (url: string) => void;+}) {+ const [note, setNote] = useState<ShareRemovalNote | null>(null);+ useEffect(() => {+ if (!signedIn) return;+ let live = true;+ void bridge.removals().then(+ (removals) => live && setNote(shareRemovalNote(removals)),+ () => {}+ );+ return () => {+ live = false;+ };+ }, [bridge, signedIn]);+ if (!note) return null;+ const dismiss = () => {+ setNote(null);+ void bridge.ackRemovals().catch(() => {});+ };+ return (+ <div className="dw-banner" data-tone="info" role="status" data-share-removal="">+ <span>{note.text}</span>+ <button type="button" className="dw-btn" onClick={() => onOpenExternal(note.action.url)}>+ {note.action.label}+ </button>+ <button type="button" className="dw-btn" onClick={dismiss}>+ {note.dismiss}+ </button>+ </div>+ );+}diff --git a/apps/cua-spaces/src/components/desktop/MainWindow.tsx b/apps/cua-spaces/src/components/desktop/MainWindow.tsxindex cab3694902..4d630db7d7 100644--- a/apps/cua-spaces/src/components/desktop/MainWindow.tsx+++ b/apps/cua-spaces/src/components/desktop/MainWindow.tsx@@ -40,7 +40,7 @@ import { createDevicesBridge, type DevicesBridge } from '../../native/devices';import { createShareBridge, type ShareBridge } from '../../native/share';import { connectedClouds, createCloudBridge, isCloudWord, type CloudBridge, type CloudStatusWire } from '../../native/cloud';import { ConnectCloudSheet } from '../ConnectCloudSheet';-import { ShareSheet } from '../ShareSheet';+import { ShareRemovalBanner, ShareSheet } from '../ShareSheet';import { hasFeature } from '../../model/spaces';import { canRunContainer, canRunMacos, type LocalStatus } from '../../native/local';import { createWindowDragBridge, type WindowDragBridge } from '../../native/windowDrag';@@ -780,9 +780,16 @@ export function MainWindow({signedIn={Boolean(sync.identity)}shareable={sharing.id.startsWith('relay:') || hasFeature(sharing, 'relay_attach')}onClose={() => setSharing(null)}+ onOpenExternal={(url) => void fleet.openExternal(url).catch(() => {})}/>)}+ <ShareRemovalBanner+ bridge={shareBridge}+ signedIn={Boolean(sync.identity)}+ onOpenExternal={(url) => void fleet.openExternal(url).catch(() => {})}+ />+{sync.rosterError && (<div className="dw-banner" data-tone="error" role="alert">{sync.rosterError}diff --git a/apps/cua-spaces/src/model/share.ts b/apps/cua-spaces/src/model/share.tsindex ba82a2116a..276aa910f0 100644--- a/apps/cua-spaces/src/model/share.ts+++ b/apps/cua-spaces/src/model/share.ts@@ -90,3 +90,41 @@ export function reduceShare(export function shareView(input: ShareInput, state: ShareSheetState): ShareSheetView {return core('share.view', { input, state });}++/** Why the sheet cannot share and where to go (`share.gate`). */+export interface ShareGate {+ reason: string;+ action: { label: string; url: string };+}++/**+ * The gate for an account: closed with an explanation and a link to Teams+ * when it is known to be in no team that can share. `null` leaves the sheet+ * open: in a team, or not known (the server decides). This only explains;+ * the control plane and the relay refuse an outside share either way.+ */+export function shareGate(hasTeam: boolean | null): ShareGate | null {+ return core('share.gate', { hasTeam });+}++/** A refused share in plain words (`share_outside_team`, `sharing_needs_team`); null for any other error. */+export function shareErrorWords(error: string, who: string): string | null {+ return core('share.errorWords', { error, who });+}++/** Someone removed from a shared computer (`sharing.removals`). */+export interface ShareRemoval {+ who: string;+ machineName: string;+}++/** The owner's one-line note about them (`share.removalNote`). */+export interface ShareRemovalNote {+ text: string;+ action: { label: string; url: string };+ dismiss: string;+}++export function shareRemovalNote(removals: ShareRemoval[]): ShareRemovalNote | null {+ return core('share.removalNote', { removals });+}diff --git a/apps/cua-spaces/src/native/share.ts b/apps/cua-spaces/src/native/share.tsindex a87df347fe..aaa50dfa9b 100644--- a/apps/cua-spaces/src/native/share.ts+++ b/apps/cua-spaces/src/native/share.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import type { ShareEntryInput } from '../model/share';+import type { ShareEntryInput, ShareRemoval } from '../model/share';import { hasTauri } from './bridge';/** The `space_shares` / `share_space` / `unshare_space` result. */@@ -23,8 +23,18 @@ export interface ShareBridge {shares(spaceId: string): Promise<SpaceSharesResult>;share(spaceId: string, who: string, role: string): Promise<SpaceSharesResult>;unshare(spaceId: string, who: string): Promise<SpaceSharesResult>;+ /** In a team that can share (null: not known, so the server decides). */+ hasTeam(): Promise<boolean | null>;+ /** People removed from the account's shared computers, until acknowledged. */+ removals(): Promise<ShareRemoval[]>;+ /** The owner has seen the removal note. */+ ackRemovals(): Promise<void>;}+/** The account is in a team on the Teams plan (`teams_list`'s `plan`). */+const inSharingTeam = (list: { teams: { plan: string }[] }) =>+ list.teams.some((t) => t.plan === 'teams');+export function createTauriShareBridge(): ShareBridge {const core = import('@tauri-apps/api/core');const invoke = async <T>(command: string, args?: Record<string, unknown>) =>@@ -33,20 +43,44 @@ export function createTauriShareBridge(): ShareBridge {shares: (spaceId) => invoke('space_shares', { spaceId }),share: (spaceId, who, role) => invoke('share_space', { spaceId, who, role }),unshare: (spaceId, who) => invoke('unshare_space', { spaceId, who }),+ hasTeam: async () => {+ try {+ return inSharingTeam(await invoke<{ teams: { plan: string }[] }>('teams_list'));+ } catch {+ return null;+ }+ },+ removals: () => invoke<ShareRemoval[]>('share_removals'),+ ackRemovals: () => invoke<void>('ack_share_removals'),};}export function createShareBridge(): ShareBridge {if (hasTauri()) return createTauriShareBridge();const unavailable = () => Promise.reject(new Error('Sharing needs the Cua Spaces app'));- return { shares: unavailable, share: unavailable, unshare: unavailable };+ return {+ shares: unavailable,+ share: unavailable,+ unshare: unavailable,+ hasTeam: async () => null,+ removals: async () => [],+ ackRemovals: async () => {},+ };}/** In-memory relay for tests: `presenceFails` refuses as a cancelled Touch ID would. */export function createFakeShareBridge(- options: { shares?: ShareEntryInput[]; presenceFails?: string } = {}+ options: {+ shares?: ShareEntryInput[];+ presenceFails?: string;+ /** The server refuses a share with this (e.g. `share_outside_team`). */+ refuses?: string;+ hasTeam?: boolean | null;+ removals?: ShareRemoval[];+ } = {}): ShareBridge & { calls: string[] } {let shares = [...(options.shares ?? [])];+ let removals = [...(options.removals ?? [])];const calls: string[] = [];const result = (space: string): SpaceSharesResult => ({space,@@ -65,6 +99,7 @@ export function createFakeShareBridge(share: async (space, who, role) => {calls.push(`share:${space}:${who}:${role}`);if (options.presenceFails) throw new Error(options.presenceFails);+ if (options.refuses) throw new Error(options.refuses);shares = [...shares.filter((s) => s.who !== who), { who, role, connected: false }];return result(space);},@@ -73,5 +108,14 @@ export function createFakeShareBridge(shares = shares.filter((s) => s.who !== who);return result(space);},+ hasTeam: async () => options.hasTeam ?? null,+ removals: async () => {+ calls.push('removals');+ return removals;+ },+ ackRemovals: async () => {+ calls.push('ackRemovals');+ removals = [];+ },};}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 626da6b42d..a36957b692 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@@ -22,7 +22,7 @@ description: "Your Spaces and machines, unattended access on this machine, devic| [`cua spaces stop`](#cua-spaces-stop) | Turn a Space off: a local container or QEMU VM is suspended (its memory is kept), a Lume VM or a Space one of your computers provides is stopped (its disk is kept), and so is a Space in your own cloud (`--on aws`, `gcp`; compute billing stops). || [`cua spaces start`](#cua-spaces-start) | Turn a Space back on: resume a suspended one or boot a stopped one. || [`cua spaces rm`](#cua-spaces-rm) | Forget a registered Space and its stored token. |-| [`cua spaces share`](#cua-spaces-share) | Let another cua.ai account watch (viewer) or use (editor) a Space, through the relay. |+| [`cua spaces share`](#cua-spaces-share) | Let someone in your team watch (viewer) or use (editor) a Space, through the relay. || [`cua spaces unshare`](#cua-spaces-unshare) | Stop sharing a Space with one account at once, or with everyone. || [`cua spaces shares`](#cua-spaces-shares) | Who a Space is shared with, and who of them is connected now. || [`cua spaces relay-register`](#cua-spaces-relay-register) | Publish a Space on the relay for your other devices (a phone off this network): its own driver dials out, as `cua host setup` does for this computer. |@@ -34,7 +34,7 @@ description: "Your Spaces and machines, unattended access on this machine, devic| [`cua host status`](#cua-host-status) | Show whether this computer is set up, the service, and who is connected. || [`cua host stop`](#cua-host-stop) | Stop sharing: disconnect everyone and refuse new connections. || [`cua host start`](#cua-host-start) | Start sharing again after `stop`. |-| [`cua host share`](#cua-host-share) | Share a relay computer (this one, or `--machine`) with other cua.ai accounts (id or verified email). |+| [`cua host share`](#cua-host-share) | Share a relay computer (this one, or `--machine`) with people in your team (id or verified email). || [`cua host unshare`](#cua-host-unshare) | Stop sharing a relay computer with accounts; their open connections are cut. || [`cua host remove`](#cua-host-remove) | Unregister from the relay, uninstall the service and delete the host configuration (asks first). || [`cua devices`](#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. |@@ -293,7 +293,7 @@ cua spaces rm studio### `cua spaces share`-Let another cua.ai account watch (viewer) or use (editor) a Space, through the relay. They open it as `relay:<computer>`.+Let someone in your team watch (viewer) or use (editor) a Space, through the relay. They open it as `relay:<computer>`. Sharing is for teams: you need a team, and they must be in it (or share with the whole team as `team:<id>`).```text outputcua spaces share [OPTIONS] <SPACE> <WHO>@@ -302,7 +302,7 @@ cua spaces share [OPTIONS] <SPACE> <WHO>| Argument | Type | Default | Description || --- | --- | --- | --- || `<SPACE>` | string | required | Space id, address or display name. |-| `<WHO>` | string | required | Their email (verified by cua.ai) or account id. |+| `<WHO>` | string | required | Their email (verified by cua.ai) or account id, in your team; or `team:<id>` for the whole team. || Flag | Short | Type | Default | Description || --- | --- | --- | --- | --- |@@ -316,6 +316,9 @@ cua spaces share local:studio [email protected]cua spaces share local:studio [email protected] --role editorcua spaces share relay:0123abcd4567ef89 acct-42 --role viewer+# The whole team, to watch+cua spaces share local:studio team:acme --role viewer+# From a script or agent: confirm with Touch ID or your password herecua spaces share local:studio [email protected] --yes```@@ -543,7 +546,7 @@ cua host start### `cua host share`-Share a relay computer (this one, or `--machine`) with other cua.ai accounts (id or verified email). Run from an enrolled device; every change is in the owner's audit log (`cua devices audit`).+Share a relay computer (this one, or `--machine`) with people in your team (id or verified email). Run from an enrolled device; every change is in the owner's audit log (`cua devices audit`).```text outputcua host share [OPTIONS] <WHO>...diff --git a/docs/content/docs/cua-cli/reference/mcp-tools.mdx b/docs/content/docs/cua-cli/reference/mcp-tools.mdxindex fb0d2a9522..8684815fbc 100644--- a/docs/content/docs/cua-cli/reference/mcp-tools.mdx+++ b/docs/content/docs/cua-cli/reference/mcp-tools.mdx@@ -172,7 +172,7 @@ Full entries: [Sharing](/spaces/reference/spaces#sharing).| Tool | Description || --- | --- |-| <span id="share_space"></span>[`share_space`](/spaces/reference/spaces#share_space) | Let another cua.ai account watch or edit a Space. |+| <span id="share_space"></span>[`share_space`](/spaces/reference/spaces#share_space) | Let someone in your team watch or edit a Space. || <span id="unshare_space"></span>[`unshare_space`](/spaces/reference/spaces#unshare_space) | Stop sharing a Space with an account, or with everyone. || <span id="space_shares"></span>[`space_shares`](/spaces/reference/spaces#space_shares) | List who a Space is shared with. || <span id="relay_register_space"></span>[`relay_register_space`](/spaces/reference/spaces#relay_register_space) | Publish a Space on the relay for the account's other devices. |diff --git a/docs/content/docs/spaces/guides/add-a-computer.mdx b/docs/content/docs/spaces/guides/add-a-computer.mdxindex 2f76c09c45..0bd99f9c40 100644--- a/docs/content/docs/spaces/guides/add-a-computer.mdx+++ b/docs/content/docs/spaces/guides/add-a-computer.mdx@@ -144,11 +144,12 @@ 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 thatdevice.-## Share it with other accounts+## Share it with your team`--allow` at setup, or later from an enrolled device, shares the computer with-another account (id or verified email). Sharing asks for confirmation.-Unsharing cuts that account's open connections.+someone in your team (id or verified email). Sharing is for teams: you need a+team, and they must be in it. See [Share a Space](/spaces/guides/share-a-space).+Sharing asks for confirmation. Unsharing cuts that account's open connections.```bash test="cli-shape" id="cua-host-share"cua host share [email protected]diff --git a/docs/content/docs/spaces/guides/share-a-space.mdx b/docs/content/docs/spaces/guides/share-a-space.mdxindex b83ebea751..57a44214d5 100644--- a/docs/content/docs/spaces/guides/share-a-space.mdx+++ b/docs/content/docs/spaces/guides/share-a-space.mdx@@ -1,16 +1,24 @@---title: Share a Space-description: 'Let another cua.ai account watch or use one of your Spaces through the relay, and reach a Space from your other devices.'+description: 'Let someone in your team watch or use one of your Spaces through the relay, and reach a Space from your other devices.'---import { Callout } from 'fumadocs-ui/components/callout';-Share a Space with another cua.ai account by email or account ID. A **viewer**-joins with their own named cursor and watches. An **editor** can also use the+Sharing is for teams. You can share a Space with the people in your own team,+one at a time or the whole team. A **viewer** ("Can view") joins with their+own named cursor and watches. An **editor** ("Can edit") can also use theSpace. They open it from their own app or terminal as `relay:<machine>`.-To share from the app, press **Share** in the Space's toolbar, enter an email-address or account ID, and choose **Viewer** or **Editor**. The same list shows+<Callout title="Sharing needs a team">+ On Free and Pro without a team, the **Share** button explains this and links+ to [Teams](/spaces/guides/teams), which starts at 1 seat. Start a team, invite+ the people you want to share with, then share.+</Callout>++To share from the app, press **Share** in the Space's toolbar, enter the email+address or account ID of someone in your team, and choose **Can view** or+**Can edit**. The same list showswho has access and who is connected. Cua Spaces asks you to confirm first:Touch ID or your login password on a Mac, Windows Hello or your account passwordon Windows, and your password through polkit on Linux.@@ -24,7 +32,7 @@ on Windows, and your password through polkit on Linux.See [Linux packages](/spaces/guides/install#linux-packages).</Callout>-You can share with one person at a time, or with a whole team at once. See+You can share with one teammate at a time, or with the whole team at once. See[People and teams](#people-and-teams).From a terminal:@@ -32,6 +40,7 @@ From a terminal:```bash test="cli-shape" id="cua-spaces-share"cua spaces share local:studio [email protected] # viewercua spaces share local:studio [email protected] --role editor # change the role+cua spaces share local:studio team:acme --role viewer # the whole team, to watchcua spaces shares local:studio # who, and who is connectedcua spaces unshare local:studio [email protected] # at oncecua spaces unshare local:studio --all # nobody; leaves the relay@@ -39,14 +48,22 @@ cua spaces unshare local:studio --all # nobody; leaves t## People and teams-- **One person.** Type their email or account ID. They can be anyone with a- cua.ai account. They do not have to be on your team, or on any team. You- choose **Viewer** or **Editor** for each person.-- **A whole team.** Every member of the team, and their agents, can use the- Space, as an editor. Only an owner or admin of a team on the- [Teams plan](/spaces/guides/teams) can do this, and only for a Space they- own. See+- **One person.** Type their email or account ID. They must be a member of+ your team: if they are not, you see "Alex isn't in your team. Invite them+ to your team first." You choose **Can view** or **Can edit** for each person.+- **A whole team.** Every member of the team, and their agents, can open the+ Space, as **Can view** (watch only) or **Can edit**. Only an owner or admin+ of a team on the [Teams plan](/spaces/guides/teams) can do this, and only for+ a Space they own. See[Share a Space with the team](/spaces/guides/teams#share-a-space-with-the-team).+- **No team.** Free and Pro accounts without a team cannot share. The+ command fails with "Sharing is for teams. Start a team to share this Space."++<Callout title="If you shared with people outside your team before">+ Those shares stopped when sharing became team-only. The Space owner sees one+ line in the app listing who was removed, with an **Invite to your team**+ button. Once they join your team, share again.+</Callout>## What each role can do@@ -60,8 +77,8 @@ cua spaces unshare local:studio --all # nobody; leaves tThe Space's own cua-spacesd enforces the role, not the caller. A refused callfails with `PermissionDenied` (`view-only share: <who> cannot call <method>`).-A team always gets the Editor role. There is no view-only share for a whole-team. To let someone only watch, share with them as a person, as a viewer.+A whole-team share has the same two roles, **Can view** and **Can edit**. To+change it, share with the team again with the other role.## How it works@@ -75,6 +92,11 @@ Sharing uses the same relay and allowlist as an- The relay keeps two lists per computer: `allow` (editors) and `viewers`.- Invitees need a verified email or account ID and an [enrolled device](/spaces/guides/add-a-computer#reach-it-from-your-other-devices).- Removing someone, or changing their role, cuts their open streams at once.+- Team membership comes from your team in your Cua account, not from the+ relay. The Cua account service checks it when you share and again each time+ someone opens the Space, and the relay enforces the answer. If someone+ leaves your team, they lose access to what you shared with them. If a team+ is deleted, its shares stop.- A team share works differently. The Space goes on the team's list ofcomputers, and each time someone opens it, the relay checks with the Cuaaccount service that they are still in the team and that their device is@@ -139,8 +161,8 @@ tools are `relay_register_space` and `relay_unregister_space`.| Added by address (`direct:`) | yes, if its driver supports `relay_attach` | Older drivers report `capability_missing`. || A Space shared with you | no | Only the owner can share (`permission_denied`). |-- You can share with a person or with a whole team. A team always gets the- Editor role.+- You can share with a person in your team or with the whole team, as+ **Can view** or **Can edit**.- Presence cursors travel on the relay stream, not QUIC datagrams, so remotecursors update a little less often than on your own network.- A Space that is released (for example a paused persistent agent in yourdiff --git a/docs/content/docs/spaces/guides/teams.mdx b/docs/content/docs/spaces/guides/teams.mdxindex df8a1ad8cc..d0fd49182c 100644--- a/docs/content/docs/spaces/guides/teams.mdx+++ b/docs/content/docs/spaces/guides/teams.mdx@@ -18,10 +18,11 @@ that lets your devices reach your computers. Current prices are on| Pro | $18 a month or $180 a year, one person | 5 | 200 a month || Teams | $30 per seat a month or $300 per seat a year, 1 to 100 seats | 5 per seat | 200 per seat a month, pooled across the team |-Every plan includes Spaces on every computer you connect, Teleport and sharing a-Space with named people. Pro adds more live sessions and remote hours. Teams-adds team-owned computers, roles and device approval. SSO and audit export are-not included yet.+Every plan includes Spaces on every computer you connect and Teleport. Pro adds+more live sessions and remote hours. Teams adds sharing a Space with your team,+team-owned computers, roles and device approval. Sharing is for teams: Free and+Pro accounts without a team cannot share a Space. SSO and audit export are not+included yet.## What counts toward the limits@@ -210,8 +211,9 @@ with the Cua account service and caches the answer for up to a minute.### Share a Space with the teamTo make a Space you already have a team computer, share it with the team. Every-member of the team, and their agents, then sees it and can open it as an editor-(full control), from a device an admin has approved.+member of the team, and their agents, then sees it and can open it from a device+an admin has approved, either as **Can edit** (full control) or **Can view**+(watch only).- **In the app:** press **Share** on the Space. If you own or manage a team onthe Teams plan, the Share window shows a **Share with** button for each of@@ -220,12 +222,13 @@ member of the team, and their agents, then sees it and can open it as an editor`cua team add-machine <team> <space>`. `cua team ls` shows the team ID.- Only an owner or admin of the team can do this, and only for a Space theyown. A team can hold as many shared computers as its seats allow.-- A team always gets the Editor role. There is no view-only share for a whole- team. To let someone only watch, share with them as a person, as a viewer.+- Choose **Can view** or **Can edit** for the whole team. Share again with the+ other role to change it.- To stop, remove the team in the Share window, or run`cua spaces unshare <space> team:<team id>`.-You can also share a Space with one person who is not on your team. See+You can also share a Space with one person in your team. Sharing is for teams:+you cannot share with anyone outside your team. See[Share a Space](/spaces/guides/share-a-space).## Seats and billingdiff --git a/docs/content/docs/spaces/reference/index.mdx b/docs/content/docs/spaces/reference/index.mdxindex b4a1c16f92..6fb82bc026 100644--- a/docs/content/docs/spaces/reference/index.mdx+++ b/docs/content/docs/spaces/reference/index.mdx@@ -166,7 +166,7 @@ Let other cua.ai accounts watch or edit a Space, through the relay.| Tool | Description | Effect || --- | --- | --- |-| [`share_space`](/spaces/reference/spaces#share_space) | Let another cua.ai account watch or edit a Space. | mutating, idempotent |+| [`share_space`](/spaces/reference/spaces#share_space) | Let someone in your team watch or edit a Space. | mutating, idempotent || [`unshare_space`](/spaces/reference/spaces#unshare_space) | Stop sharing a Space with an account, or with everyone. | mutating, idempotent || [`space_shares`](/spaces/reference/spaces#space_shares) | List who a Space is shared with. | read-only, idempotent || [`relay_register_space`](/spaces/reference/spaces#relay_register_space) | Publish a Space on the relay for the account's other devices. | mutating, idempotent |diff --git a/docs/content/docs/spaces/reference/spaces.mdx b/docs/content/docs/spaces/reference/spaces.mdxindex fe811a4a07..e401cb5d51 100644--- a/docs/content/docs/spaces/reference/spaces.mdx+++ b/docs/content/docs/spaces/reference/spaces.mdx@@ -832,7 +832,7 @@ Let other cua.ai accounts watch or edit a Space, through the relay.| Tool | Description || --- | --- |-| [`share_space`](#share_space) | Let another cua.ai account watch or edit a Space. |+| [`share_space`](#share_space) | Let someone in your team watch or edit a Space. || [`unshare_space`](#unshare_space) | Stop sharing a Space with an account, or with everyone. || [`space_shares`](#space_shares) | List who a Space is shared with. || [`relay_register_space`](#relay_register_space) | Publish a Space on the relay for the account's other devices. |@@ -840,9 +840,9 @@ Let other cua.ai accounts watch or edit a Space, through the relay.### share_space-Let another cua.ai account watch or edit a Space.+Let someone in your team watch or edit a Space.-Shares the Space through the cua.ai relay with one account, by verified email or account id, or with a whole team as `team:<id>` (always as an editor; Teams plan); the same allowlist and device enrollment `cua host share` uses. A viewer joins presence with their own named cursor and watches a view-only stream: the Space's driver refuses their input, shell, files and MCP. An editor gets full use, and their input is a human session. Sharing again changes the role. A host (`relay:<id>`) is shared directly; any other Space (local, cloud, or added by address) is attached to the relay on its first share: its own driver dials out, so it needs no inbound port. Invitees open `invitee_space`.+Shares the Space through the cua.ai relay with one person in your own team, by verified email or account id, or with the whole team as `team:<id>` (as a viewer or an editor). Sharing is for teams: an account in no team gets `sharing_needs_team` ("Sharing is for teams. Start a team to share this Space."), and someone outside your team gets `share_outside_team`. The same allowlist and device enrollment `cua host share` uses. A viewer joins presence with their own named cursor and watches a view-only stream: the Space's driver refuses their input, shell, files and MCP. An editor gets full use, and their input is a human session. Sharing again changes the role. A host (`relay:<id>`) is shared directly; any other Space (local, cloud, or added by address) is attached to the relay on its first share: its own driver dials out, so it needs no inbound port. Invitees open `invitee_space`.| | || --- | --- |@@ -860,7 +860,7 @@ Shares the Space through the cua.ai relay with one account, by verified email or| --- | --- | --- | --- || `role` | `string` | `viewer` | `viewer` (presence with their own cursor and a view-only stream) or `editor` (full use; their input is a human session). Default `viewer`. || `space` | `string` | required | Space id or name. |-| `who` | `string` | required | Who: an email address (verified by cua.ai) or an account id, or `team:<id>` for a whole team. A team always gets `editor` and needs the Teams plan; the sharer is a team owner or admin who owns the Space. |+| `who` | `string` | required | Who: the email address (verified by cua.ai) or account id of someone in your own team, or `team:<id>` for the whole team (as `viewer` or `editor`). Sharing is for teams: it needs a team on the Teams plan, and a whole-team share needs a team owner or admin who owns the Space. |#### Resultdiff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex 9b2724381c..3aa1bdd822 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -157,8 +157,8 @@ pub enum HostCmd {#[command(after_help = "Examples:cua host start")]Start,- /// Share a relay computer (this one, or `--machine`) with other cua.ai- /// accounts (id or verified email). Run from an enrolled device; every+ /// Share a relay computer (this one, or `--machine`) with people in your+ /// team (id or verified email). Run from an enrolled device; every/// change is in the owner's audit log (`cua devices audit`).#[command(after_help = "Examples:cua host share [email protected]@@ -377,18 +377,23 @@ Examples:/// Space id, address or display name (as `cua spaces ls` shows).space: String,},- /// Let another cua.ai account watch (viewer) or use (editor) a Space,- /// through the relay. They open it as `relay:<computer>`.+ /// Let someone in your team watch (viewer) or use (editor) a Space,+ /// through the relay. They open it as `relay:<computer>`. Sharing is for+ /// teams: you need a team, and they must be in it (or share with the+ /// whole team as `team:<id>`).#[command(after_help = "Examples:cua spaces share local:studio [email protected]cua spaces share local:studio [email protected] --role editorcua spaces share relay:0123abcd4567ef89 acct-42 --role viewer+ # The whole team, to watch+ cua spaces share local:studio team:acme --role viewer# From a script or agent: confirm with Touch ID or your password herecua spaces share local:studio [email protected] --yes")]Share {/// Space id, address or display name.space: String,- /// Their email (verified by cua.ai) or account id.+ /// Their email (verified by cua.ai) or account id, in your team; or+ /// `team:<id>` for the whole team.who: String,/// `viewer`: presence and a view-only stream. `editor`: full use.#[arg(long, default_value = "viewer", value_parser = ["viewer", "editor"])]diff --git a/libs/cua/crates/cua-host/src/spaces_api.rs b/libs/cua/crates/cua-host/src/spaces_api.rsindex 94358f3f22..906e369f38 100644--- a/libs/cua/crates/cua-host/src/spaces_api.rs+++ b/libs/cua/crates/cua-host/src/spaces_api.rs@@ -97,10 +97,56 @@ pub struct ApiOrgMachine {pub label: String,#[serde(default)]pub added_by: String,+ /// What the team may do with it: `editor` ("Can edit") or `viewer`+ /// ("Can view"). Empty from a server that predates view-only team+ /// shares: read it as `editor`.+ #[serde(default)]+ pub role: String,#[serde(default)]pub added_at: String,}+/// A team the account may share with as a whole (`GET /v1/me/sharing`).+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct ApiSharingTeam {+ #[serde(default)]+ pub id: String,+ #[serde(default)]+ pub alias: String,+ #[serde(default)]+ pub name: String,+ /// The caller is an owner or admin, so can share a whole team.+ #[serde(default)]+ pub can_add: bool,+}++/// `GET /v1/me/sharing`: whether this account can share Spaces. Sharing is+/// for teams (CUA-1883): only a member of a team on a plan with sharing can.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct ApiSharing {+ #[serde(default)]+ pub can_share: bool,+ /// `no_team` when `can_share` is false.+ #[serde(default)]+ pub reason: String,+ #[serde(default)]+ pub teams: Vec<ApiSharingTeam>,+}++/// Someone who lost access to a computer because sharing became team-only+/// (`GET /v1/me/share-removals`).+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct ApiShareRemoval {+ #[serde(default)]+ pub machine_id: String,+ #[serde(default)]+ pub machine_name: String,+ #[serde(default)]+ pub who: String,+ #[serde(default)]+ pub removed_at: String,+}+/// A member device's approval in an org (`GET /v1/orgs/{org}/devices`)./// `device_id` is the relay device id (`dev_…`).#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]@@ -657,6 +703,91 @@ impl SpacesApiClient {}}+ /// [`Self::add_org_machine`] with what the team may do: `viewer`+ /// ("Can view") or `editor` ("Can edit"). A computer already on the team+ /// gets the role changed instead.+ pub async fn add_org_machine_as(+ &self,+ token: &str,+ org: &str,+ machine_id: &str,+ platform: &str,+ label: &str,+ role: &str,+ ) -> Result<()> {+ let label: String = label.chars().take(120).collect();+ match self+ .org_post::<serde_json::Value>(+ &format!("/v1/orgs/{}/machines", seg(org)),+ token,+ serde_json::json!({ "machine_id": machine_id, "platform": platform, "label": label, "role": role }),+ )+ .await+ {+ Ok(_) => Ok(()),+ Err(Error::Conflict(m)) if m.contains("already_added") => {+ self.set_org_machine_role(token, org, machine_id, role).await+ }+ Err(e) => Err(e),+ }+ }++ /// `PATCH /v1/orgs/{org}/machines/{id}` (owner or admin): "Can view"+ /// (`viewer`) or "Can edit" (`editor`) for the whole team.+ pub async fn set_org_machine_role(+ &self,+ token: &str,+ org: &str,+ machine_id: &str,+ role: &str,+ ) -> Result<()> {+ self.send_org::<serde_json::Value>(+ self.http+ .patch(self.url(&format!(+ "/v1/orgs/{}/machines/{}",+ seg(org),+ seg(machine_id)+ )))+ .json(&serde_json::json!({ "role": role })),+ token,+ )+ .await+ .map(|_| ())+ }++ /// `GET /v1/me/sharing`: can this account share, and with which teams as+ /// a whole. A server that predates team-only sharing answers "Teams are+ /// not available" ([`is_teams_unavailable`]): callers let the server+ /// decide.+ pub async fn sharing(&self, token: &str) -> Result<ApiSharing> {+ self.org_get("/v1/me/sharing", token).await+ }++ /// `GET /v1/me/share-removals`: people removed from the account's+ /// shared computers since it last asked, until+ /// [`Self::ack_share_removals`].+ pub async fn share_removals(&self, token: &str) -> Result<Vec<ApiShareRemoval>> {+ #[derive(Deserialize)]+ struct R {+ #[serde(default)]+ removals: Vec<ApiShareRemoval>,+ }+ Ok(self+ .org_get::<R>("/v1/me/share-removals", token)+ .await?+ .removals)+ }++ /// `POST /v1/me/share-removals/ack`: the owner has seen them.+ pub async fn ack_share_removals(&self, token: &str) -> Result<()> {+ self.send_org::<serde_json::Value>(+ self.http.post(self.url("/v1/me/share-removals/ack")),+ token,+ )+ .await+ .map(|_| ())+ }+/// `DELETE /v1/orgs/{org}/machines/{id}` (owner or admin).pub async fn remove_org_machine(&self, token: &str, org: &str, machine_id: &str) -> Result<()> {self.org_delete(@@ -995,6 +1126,64 @@ mod tests {assert!(matches!(e, Error::NotFound(_)), "{e}");}+ #[tokio::test]+ async fn sharing_is_for_teams_and_a_team_share_has_a_role() {+ let api = crate::testing::FakeSpacesApi::start().await;+ api.add_account("ada", "sub-ada", "[email protected]");+ api.add_account("dan", "sub-dan", "[email protected]");+ let org = api.add_org(+ "acme",+ "Acme",+ "sub-ada",+ &["team_machines", "space_sharing"],+ );+ let c = SpacesApiClient::new(&api.url).unwrap();++ // In a team that can share: yes, and the team is offered.+ let s = c.sharing("ada").await.unwrap();+ assert!(s.can_share && s.reason.is_empty());+ assert_eq!(s.teams.len(), 1);+ assert!(s.teams[0].can_add && s.teams[0].alias == "acme");+ // In no team: no, and why.+ let s = c.sharing("dan").await.unwrap();+ assert!(!s.can_share && s.reason == "no_team" && s.teams.is_empty());++ // A whole-team share is "Can view" or "Can edit", and can change.+ c.add_org_machine_as("ada", &org, "m1", "linux", "box", "viewer")+ .await+ .unwrap();+ assert_eq!(api.machine_role(&org, "m1").as_deref(), Some("viewer"));+ c.add_org_machine_as("ada", &org, "m1", "linux", "box", "editor")+ .await+ .unwrap();+ assert_eq!(api.machine_role(&org, "m1").as_deref(), Some("editor"));+ let listed = c.org_machines("ada", &org).await.unwrap();+ assert_eq!(listed[0].role, "editor");+ let e = c+ .set_org_machine_role("ada", &org, "m1", "owner")+ .await+ .unwrap_err();+ assert!(e.to_string().contains("bad_role"), "{e}");++ // The owner's one-line note: read, then acknowledged once.+ api.add_share_removal("sub-ada", "Design", "[email protected]");+ let r = c.share_removals("ada").await.unwrap();+ assert_eq!(r.len(), 1);+ assert_eq!(+ (r[0].who.as_str(), r[0].machine_name.as_str()),+ ("[email protected]", "Design")+ );+ assert!(c.share_removals("dan").await.unwrap().is_empty());+ c.ack_share_removals("ada").await.unwrap();+ assert!(c.share_removals("ada").await.unwrap().is_empty());++ // A server without these routes: Teams are not available (the caller+ // lets the server decide).+ api.without_teams();+ let e = c.sharing("ada").await.unwrap_err();+ assert!(is_teams_unavailable(&e), "{e}");+ }+#[tokio::test]async fn a_just_paid_plan_is_retried_until_it_arrives() {let api = crate::testing::FakeSpacesApi::start().await;diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rsindex ee09884af5..a57ab6a449 100644--- a/libs/cua/crates/cua-host/src/testing.rs+++ b/libs/cua/crates/cua-host/src/testing.rs@@ -80,6 +80,9 @@ struct State_ {reads_down: bool,/// A relay that predates meta patches: the key is ignored.ignore_meta_patches: bool,+ /// A relay (or its control plane) that refuses to change who a computer+ /// is shared with, with this code (`share_outside_team`).+ refuse_shares: Option<String>,/// Machine registrations received (including refused ones).register_calls: usize,/// machine id → `(path prefix, base URL)` its `/m/<id>/…` gRPC-Web@@ -561,6 +564,11 @@ async fn patch(if matches!(caller(&st, &headers), Some(Caller::Machine(_))) {return err(StatusCode::FORBIDDEN, "owner only");}+ if let Some(code) = st.refuse_shares.clone()+ && (body["allow"].is_array() || body["viewers"].is_array())+ {+ return err(StatusCode::FORBIDDEN, &code);+ }let rec = st.machines.get_mut(&id).unwrap();if let Some(n) = body["name"].as_str() {rec.machine.name = n.into();@@ -1226,6 +1234,13 @@ impl FakeRelay {self.state.lock().unwrap().reads_down = down;}+ /// While set, a PATCH that changes who a computer is shared with is+ /// refused with `code` (`share_outside_team`), as the relay does for+ /// someone outside the owner's team.+ pub fn refuse_shares(&self, code: Option<&str>) {+ self.state.lock().unwrap().refuse_shares = code.map(str::to_string);+ }+/// While `on`, a PATCH with `meta` is accepted but its keys are/// dropped, as a relay that predates them does.pub fn set_ignore_meta_patches(&self, on: bool) {@@ -1361,6 +1376,8 @@ struct ApiState {entitlement_reads: usize,/// Every org route answers 410, as a server without Teams.gone: bool,+ /// (owner sub, removal) not yet acknowledged.+ removals: Vec<(String, crate::spaces_api::ApiShareRemoval)>,}type A = Arc<Mutex<ApiState>>;@@ -1463,8 +1480,11 @@ impl FakeSpacesApi {).route("/v1/orgs/{org}/machines/{id}",- axum::routing::delete(api_remove_machine),+ axum::routing::delete(api_remove_machine).patch(api_set_machine_role),)+ .route("/v1/me/sharing", get(api_sharing))+ .route("/v1/me/share-removals", get(api_share_removals))+ .route("/v1/me/share-removals/ack", post(api_ack_share_removals)).route("/v1/orgs/{org}/devices", get(api_devices)).route("/v1/orgs/{org}/devices/request", post(api_request_device)).route(@@ -1536,6 +1556,32 @@ impl FakeSpacesApi {self.state.lock().unwrap().entitlement_reads}+ /// Records that `who` lost access to a computer of `owner` (a sub).+ pub fn add_share_removal(&self, owner: &str, machine_name: &str, who: &str) {+ self.state.lock().unwrap().removals.push((+ owner.into(),+ crate::spaces_api::ApiShareRemoval {+ machine_id: "m1".into(),+ machine_name: machine_name.into(),+ who: who.into(),+ removed_at: api_now(),+ },+ ));+ }++ /// The role of `machine` on `org` (`editor` or `viewer`).+ pub fn machine_role(&self, org: &str, machine: &str) -> Option<String> {+ self.state+ .lock()+ .unwrap()+ .orgs+ .get(org)?+ .machines+ .iter()+ .find(|m| m.machine_id == machine)+ .map(|m| m.role.clone())+ }+/// The machine ids bound to `org`.pub fn machines(&self, org: &str) -> Vec<String> {self.state@@ -1814,6 +1860,7 @@ async fn api_add_machine(platform: b["platform"].as_str().unwrap_or("").into(),label: b["label"].as_str().unwrap_or("").into(),added_by: sub,+ role: b["role"].as_str().unwrap_or("editor").into(),added_at: api_now(),});(@@ -1823,6 +1870,76 @@ async fn api_add_machine(.into_response()}+async fn api_set_machine_role(+ State(s): State<A>,+ h: HeaderMap,+ Path((org, machine)): Path<(String, String)>,+ Json(b): Json<serde_json::Value>,+) -> Response {+ let mut st = s.lock().unwrap();+ let (sub, _) = tri!(api_caller(&st, &h));+ let (id, _) = tri!(api_org(&st, &org, &sub, "admin"));+ let role = b["role"].as_str().unwrap_or("");+ if role != "viewer" && role != "editor" {+ return api_fail(+ StatusCode::UNPROCESSABLE_ENTITY,+ "bad_role",+ "role is viewer or editor",+ );+ }+ let o = st.orgs.get_mut(&id).unwrap();+ let Some(m) = o.machines.iter_mut().find(|m| m.machine_id == machine) else {+ return api_fail(StatusCode::NOT_FOUND, "machine_not_found", "");+ };+ m.role = role.into();+ Json(serde_json::json!({ "machine_id": machine, "role": role })).into_response()+}++/// `GET /v1/me/sharing`: can share when in an org with `space_sharing`.+async fn api_sharing(State(s): State<A>, h: HeaderMap) -> Response {+ let st = s.lock().unwrap();+ let (sub, _) = tri!(api_caller(&st, &h));+ if st.gone {+ return api_fail(StatusCode::GONE, "gone", "retired");+ }+ let teams: Vec<_> = st+ .orgs+ .values()+ .filter(|o| o.members.contains_key(&sub) && o.features.iter().any(|f| f == "space_sharing"))+ .map(|o| {+ let role = o.members[&sub].as_str();+ serde_json::json!({+ "id": o.id, "alias": o.alias, "name": o.name,+ "can_add": role == "owner" || role == "admin",+ })+ })+ .collect();+ let mut out = serde_json::json!({ "can_share": !teams.is_empty(), "teams": teams });+ if teams.is_empty() {+ out["reason"] = "no_team".into();+ }+ Json(out).into_response()+}++async fn api_share_removals(State(s): State<A>, h: HeaderMap) -> Response {+ let st = s.lock().unwrap();+ let (sub, _) = tri!(api_caller(&st, &h));+ let rows: Vec<_> = st+ .removals+ .iter()+ .filter(|(owner, _)| *owner == sub)+ .map(|(_, r)| r.clone())+ .collect();+ Json(serde_json::json!({ "removals": rows })).into_response()+}++async fn api_ack_share_removals(State(s): State<A>, h: HeaderMap) -> Response {+ let mut st = s.lock().unwrap();+ let (sub, _) = tri!(api_caller(&st, &h));+ st.removals.retain(|(owner, _)| *owner != sub);+ StatusCode::NO_CONTENT.into_response()+}+async fn api_remove_machine(State(s): State<A>,h: HeaderMap,diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rsindex f9942cbe5b..e6f4e2e544 100644--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs@@ -252,6 +252,9 @@ pub const METHODS: &[&str] = &["share.initial","share.reduce","share.view",+ "share.gate",+ "share.errorWords",+ "share.removalNote","agents.pageInitial","agents.pageReduce","agents.pageView",@@ -1047,6 +1050,14 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {&a.get::<share::ShareInput>("input")?,&a.get::<share::ShareSheetState>("state")?,)),+ "share.gate" => out(share::share_gate(a.get::<Option<bool>>("hasTeam")?)),+ "share.errorWords" => out(share::share_error_words(+ &a.get::<String>("error")?,+ &a.get::<String>("who")?,+ )),+ "share.removalNote" => out(share::share_removal_note(+ &a.get::<Vec<share::ShareRemovalInput>>("removals")?,+ )),"host.clientLabel" => out(host::client_label(&a.get::<String>("id")?,a.get::<Option<String>>("email")?.as_deref(),diff --git a/libs/cua/crates/cua-spaces-app-core/src/share.rs b/libs/cua/crates/cua-spaces-app-core/src/share.rsindex 58e926ea85..e949628c31 100644--- a/libs/cua/crates/cua-spaces-app-core/src/share.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/share.rs@@ -146,6 +146,16 @@ pub struct ShareRowView {pub connected: bool,}+/// A button with somewhere to go.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ShareActionView {+ /// The button's words.+ pub label: String,+ /// Where it opens.+ pub url: String,+}+/// The sheet as drawn.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -247,15 +257,128 @@ fn role_of(role: &str) -> &'static str {if role == "editor" { "editor" } else { "viewer" }}-/// A team always gets full use (teams have no view-only members).-fn role_for(who: &str, role: &str) -> &'static str {- if who.starts_with("team:") {- "editor"+/// A role, for a person or a whole team: "Can view" or "Can edit".+fn role_for(_who: &str, role: &str) -> &'static str {+ role_of(role)+}++/// Why a Free or Pro account without a team cannot share (CUA-1883).+pub const NO_TEAM: &str = "Sharing is for teams. Start a team to share this Space.";++/// Where Teams starts, at one seat.+pub const TEAMS_URL: &str = "https://app.cua.ai/buy/teams?from=app_share";++/// Where an owner invites people to their team.+pub const INVITE_URL: &str = "https://app.cua.ai/team";++/// Why the sheet cannot share, and what to do about it: sharing is for+/// teams (CUA-1883).+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ShareGate {+ /// "Sharing is for teams. Start a team to share this Space."+ pub reason: String,+ /// "See Teams": where Teams starts, at one seat.+ pub action: ShareActionView,+}++/// The gate for an account, from whether it is in a team that can share:+/// `Some(false)` closes the sheet; `Some(true)`, or `None` (the host could+/// not say, so the server decides), leaves it open.+pub fn share_gate(has_team: Option<bool>) -> Option<ShareGate> {+ (has_team == Some(false)).then(|| ShareGate {+ reason: NO_TEAM.into(),+ action: ShareActionView {+ label: "See Teams".into(),+ url: TEAMS_URL.into(),+ },+ })+}++/// What a refused share says, in plain words, from the server's code or+/// message (`share_outside_team`, `sharing_needs_team`). `None` for any+/// other error: the caller shows its own.+pub fn share_error_words(error: &str, who: &str) -> Option<String> {+ let e = error.to_ascii_lowercase();+ if e.contains("sharing_needs_team") {+ Some(NO_TEAM.into())+ } else if e.contains("share_outside_team") {+ let who = who.trim();+ let name = if who.is_empty() { "That person" } else { who };+ Some(format!(+ "{name} isn't in your team. Invite them to your team first."+ ))} else {- role_of(role)+ None}}+/// Someone who lost access to a computer when sharing became team-only.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ShareRemovalInput {+ /// The person (an email or account id).+ pub who: String,+ /// The computer's name.+ #[serde(default)]+ pub machine_name: String,+}++/// The one-line note for an owner whose shares were removed.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ShareRemovalNote {+ /// One line: who can no longer open what, and why.+ pub text: String,+ /// "Invite to your team".+ pub action: ShareActionView,+ /// Dismiss.+ pub dismiss: String,+}++/// The note for `removals`, or nothing when there are none. It names up to+/// three people, then counts the rest, and names the computer only when+/// there is one.+pub fn share_removal_note(removals: &[ShareRemovalInput]) -> Option<ShareRemovalNote> {+ let mut people: Vec<&str> = Vec::new();+ for r in removals {+ let w = r.who.trim();+ if !w.is_empty() && !people.iter().any(|p| p.eq_ignore_ascii_case(w)) {+ people.push(w);+ }+ }+ if people.is_empty() {+ return None;+ }+ let mut computers: Vec<&str> = removals+ .iter()+ .map(|r| r.machine_name.trim())+ .filter(|n| !n.is_empty())+ .collect();+ computers.sort_unstable();+ computers.dedup();+ let shown: Vec<String> = people.iter().take(3).map(|p| p.to_string()).collect();+ let rest = people.len() - shown.len();+ let who = match (shown.as_slice(), rest) {+ ([a], 0) => a.clone(),+ ([a, b], 0) => format!("{a} and {b}"),+ ([a, b, c], 0) => format!("{a}, {b} and {c}"),+ (_, n) => format!("{}, and {n} more", shown.join(", ")),+ };+ let what = match computers.as_slice() {+ [one] => format!("\u{201c}{one}\u{201d}"),+ _ => "your shared Spaces".to_string(),+ };+ Some(ShareRemovalNote {+ text: format!("{who} can no longer open {what}, because they're not in your team."),+ action: ShareActionView {+ label: "Invite to your team".into(),+ url: INVITE_URL.into(),+ },+ dismiss: "Dismiss".into(),+ })+}+/// The roles, in menu order.pub fn roles() -> Vec<RoleOption> {vec![@@ -456,7 +579,7 @@ mod tests {#[test]fn teams_are_shared_with_unless_turned_off() {- // On (the default): a team id, always for full use.+ // On (the default): a team id, for either role.assert_eq!(validate_who_with("team:Design Team", true).unwrap_err(),"Enter a team as team:<id>, as `cua team ls` shows it."@@ -476,7 +599,9 @@ mod tests {.unwrap_err().contains("old Teams"));- assert_eq!(role_for("team:design", "viewer"), "editor");+ // A whole team can be shared with as "Can view" or "Can edit".+ assert_eq!(role_for("team:design", "viewer"), "viewer");+ assert_eq!(role_for("team:design", "editor"), "editor");// Off (CUA_EXPERIMENTAL_TEAMS=0): refused, whatever the id.for who in ["team:team-0a1b", "team:design", "org:acme"] {assert_eq!(@@ -521,4 +646,94 @@ mod tests {.contains("too old"));}++ #[test]+ fn no_team_means_the_sheet_explains_and_links_to_teams() {+ // Unknown, or in a team: the sheet stays open.+ assert!(share_gate(None).is_none());+ assert!(share_gate(Some(true)).is_none());+ let g = share_gate(Some(false)).expect("closed without a team");+ assert_eq!(+ g.reason,+ "Sharing is for teams. Start a team to share this Space."+ );+ assert_eq!(g.action.label, "See Teams");+ assert_eq!(g.action.url, "https://app.cua.ai/buy/teams?from=app_share");+ }++ #[test]+ fn team_shares_keep_the_role_chosen() {+ let i = input();+ let mut s = share_reduce(+ &i,+ &share_initial(),+ &ShareSheetAction::SetWho {+ who: "team:design".into(),+ },+ );+ s = share_reduce(+ &i,+ &s,+ &ShareSheetAction::SetRole {+ role: "viewer".into(),+ },+ );+ s = share_reduce(&i, &s, &ShareSheetAction::Submit);+ assert_eq!(+ s.request,+ Some(ShareRequest::Share {+ space: "local:studio".into(),+ who: "team:design".into(),+ role: "viewer".into()+ })+ );+ }++ #[test]+ fn refused_shares_read_in_plain_words() {+ assert_eq!(+ share_error_words("HTTP 403: share_outside_team", "[email protected]").as_deref(),+ Some("[email protected] isn't in your team. Invite them to your team first.")+ );+ assert_eq!(+ share_error_words("sharing_needs_team", "").as_deref(),+ Some(NO_TEAM)+ );+ assert_eq!(+ share_error_words("share_outside_team", " ").as_deref(),+ Some("That person isn't in your team. Invite them to your team first.")+ );+ assert!(share_error_words("HTTP 500", "[email protected]").is_none());+ }++ #[test]+ fn removal_note_is_one_line_with_an_invite_button() {+ let r = |who: &str, m: &str| ShareRemovalInput {+ who: who.into(),+ machine_name: m.into(),+ };+ assert!(share_removal_note(&[]).is_none());+ let n =+ share_removal_note(&[r("[email protected]", "Design"), r("[email protected]", "Design")]).unwrap();+ assert_eq!(+ n.text,+ "[email protected] and [email protected] can no longer open \u{201c}Design\u{201d}, because they're not in your team."+ );+ assert_eq!(n.action.label, "Invite to your team");+ assert_eq!(n.action.url, "https://app.cua.ai/team");+ // Several computers, many people: still one line.+ let n = share_removal_note(&[+ r("[email protected]", "One"),+ r("[email protected]", "Two"),+ r("[email protected]", "One"),+ r("[email protected]", "One"),+ r("[email protected]", "One"),+ ])+ .unwrap();+ assert_eq!(+ n.text,+ "[email protected], [email protected], [email protected], and 1 more can no longer open your shared Spaces, because they're not in your team."+ );+ assert!(!n.text.contains('\n'));+ }}diff --git a/libs/cua/crates/cua-spaces-contract/src/inputs.rs b/libs/cua/crates/cua-spaces-contract/src/inputs.rsindex d1775025f6..18ae14e4e4 100644--- a/libs/cua/crates/cua-spaces-contract/src/inputs.rs+++ b/libs/cua/crates/cua-spaces-contract/src/inputs.rs@@ -1037,14 +1037,15 @@ pub struct DriveCacheSet {#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]pub struct NoArgs {}-/// `share_space`: let an account watch or edit the Space.+/// `share_space`: let someone in your team watch or edit the Space.#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]pub struct ShareSpace {/// Space id or name.pub space: SpaceArg,- /// Who: an email address (verified by cua.ai) or an account id, or- /// `team:<id>` for a whole team. A team always gets `editor` and needs- /// the Teams plan; the sharer is a team owner or admin who owns the Space.+ /// Who: the email address (verified by cua.ai) or account id of someone+ /// in your own team, or `team:<id>` for the whole team (as `viewer` or+ /// `editor`). Sharing is for teams: it needs a team on the Teams plan,+ /// and a whole-team share needs a team owner or admin who owns the Space.pub who: String,/// `viewer` (presence with their own cursor and a view-only stream) or/// `editor` (full use; their input is a human session). Defaultdiff --git a/libs/cua/crates/cua-spaces-contract/src/lib.rs b/libs/cua/crates/cua-spaces-contract/src/lib.rsindex 0f69e389ce..16db91e5ea 100644--- a/libs/cua/crates/cua-spaces-contract/src/lib.rs+++ b/libs/cua/crates/cua-spaces-contract/src/lib.rs@@ -608,7 +608,7 @@ const DRIVE_INSTRUCTIONS: &str = "Cua Volume is one versioned drive per account,const SHARES_RESULT: &str = "JSON: `space`, `machine` (the relay computer it is shared as; empty when not shared), `invitee_space` (what the people it is shared with open: `relay:<computer>`), `url`, `online` and `shares` (each `who`, `role`: viewer or editor, and `connected`).";-const SHARE_INSTRUCTIONS: &str = "Shares the Space through the cua.ai relay with one account, by verified email or account id, or with a whole team as `team:<id>` (always as an editor; Teams plan); the same allowlist and device enrollment `cua host share` uses. A viewer joins presence with their own named cursor and watches a view-only stream: the Space's driver refuses their input, shell, files and MCP. An editor gets full use, and their input is a human session. Sharing again changes the role. A host (`relay:<id>`) is shared directly; any other Space (local, cloud, or added by address) is attached to the relay on its first share: its own driver dials out, so it needs no inbound port. Invitees open `invitee_space`.";+const SHARE_INSTRUCTIONS: &str = "Shares the Space through the cua.ai relay with one person in your own team, by verified email or account id, or with the whole team as `team:<id>` (as a viewer or an editor). Sharing is for teams: an account in no team gets `sharing_needs_team` (\"Sharing is for teams. Start a team to share this Space.\"), and someone outside your team gets `share_outside_team`. The same allowlist and device enrollment `cua host share` uses. A viewer joins presence with their own named cursor and watches a view-only stream: the Space's driver refuses their input, shell, files and MCP. An editor gets full use, and their input is a human session. Sharing again changes the role. A host (`relay:<id>`) is shared directly; any other Space (local, cloud, or added by address) is attached to the relay on its first share: its own driver dials out, so it needs no inbound port. Invitees open `invitee_space`.";/// The Spaces tools, in manifest order.pub fn tools() -> Vec<Tool> {@@ -1551,7 +1551,7 @@ pub fn tools() -> Vec<Tool> {sdk_symbol: "space.sharing.share(with:role:)",rust_symbol: "Spaces::share_space",notes: &["Viewers and editors are enforced by the Space's own cua-spacesd, not by the caller; a Space whose driver predates relay_attach reports capability_missing."],- ..Spec::new("share_space", "Let another cua.ai account watch or edit a Space.")+ ..Spec::new("share_space", "Let someone in your team watch or edit a Space.")}.with::<i::ShareSpace>(),Spec {diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rsindex afc6264480..2838915bac 100644--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs@@ -749,6 +749,61 @@ pub fn app_share_view(input: AppShareInput, state: AppShareSheetState) -> AppShacore::share::share_view(&input, &state)}+/// Why the Share sheet is closed, from whether the account is in a team+/// that can share (`None`: the host could not say, so the sheet stays open+/// and the server decides). Sharing is for teams (CUA-1883).+#[uniffi::export]+pub fn app_share_gate(has_team: Option<bool>) -> Option<AppShareGate> {+ core::share::share_gate(has_team)+}++/// A refused share in plain words (`share_outside_team`,+/// `sharing_needs_team`); `None` for any other error.+#[uniffi::export]+pub fn app_share_error_words(error: String, who: String) -> Option<String> {+ core::share::share_error_words(&error, &who)+}++/// The owner's one-line note about people removed from shared computers.+#[uniffi::export]+pub fn app_share_removal_note(removals: Vec<AppShareRemovalInput>) -> Option<AppShareRemovalNote> {+ core::share::share_removal_note(&removals)+}++/// People removed from the account's shared computers because sharing is+/// for teams now, until [`app_ack_share_removals`]. Empty on a server that+/// predates it.+#[uniffi::export]+pub async fn app_share_removals(account_token: String) -> Result<Vec<AppShareRemovalInput>> {+ cua_sdk::support::run(async move {+ let api = cua_host::spaces_api::SpacesApiClient::current()?;+ match api.share_removals(&account_token).await {+ Err(e) if cua_host::spaces_api::is_teams_unavailable(&e) => Ok(vec![]),+ other => Ok(other?+ .into_iter()+ .map(|r| core::share::ShareRemovalInput {+ who: r.who,+ machine_name: r.machine_name,+ })+ .collect()),+ }+ })+ .await+}++/// The owner has seen the note: it is not shown again.+#[uniffi::export]+pub async fn app_ack_share_removals(account_token: String) -> Result<()> {+ cua_sdk::support::run(async move {+ let api = cua_host::spaces_api::SpacesApiClient::current()?;+ match api.ack_share_removals(&account_token).await {+ Err(e) if cua_host::spaces_api::is_teams_unavailable(&e) => Ok(()),+ other => Ok(other?),+ }+ })+ .await+}+/// Share sheet input from JSON (fixtures, parity flows).#[uniffi::export]pub fn app_share_input_from_json(json: String) -> Result<AppShareInput> {diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rsindex 96615dd285..4caff2f139 100644--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs@@ -8582,6 +8582,16 @@ pub struct AppShareRowView {pub connected: bool,}+/// A button with somewhere to go.+pub type AppShareActionView = core::share::ShareActionView;+#[uniffi::remote(Record)]+pub struct AppShareActionView {+ /// The button's words.+ pub label: String,+ /// Where it opens.+ pub url: String,+}+/// The sheet as drawn.pub type AppShareSheetView = core::share::ShareSheetView;#[uniffi::remote(Record)]@@ -8620,6 +8630,39 @@ pub struct AppShareSheetView {pub request: Option<AppShareRequest>,}+/// Why the sheet cannot share, and what to do about it: sharing is for+/// teams (CUA-1883).+pub type AppShareGate = core::share::ShareGate;+#[uniffi::remote(Record)]+pub struct AppShareGate {+ /// "Sharing is for teams. Start a team to share this Space."+ pub reason: String,+ /// "See Teams": where Teams starts, at one seat.+ pub action: AppShareActionView,+}++/// Someone who lost access to a computer when sharing became team-only.+pub type AppShareRemovalInput = core::share::ShareRemovalInput;+#[uniffi::remote(Record)]+pub struct AppShareRemovalInput {+ /// The person (an email or account id).+ pub who: String,+ /// The computer's name.+ pub machine_name: String,+}++/// The one-line note for an owner whose shares were removed.+pub type AppShareRemovalNote = core::share::ShareRemovalNote;+#[uniffi::remote(Record)]+pub struct AppShareRemovalNote {+ /// One line: who can no longer open what, and why.+ pub text: String,+ /// "Invite to your team".+ pub action: AppShareActionView,+ /// Dismiss.+ pub dismiss: String,+}+/// A persistent agent, as `persistent_agent_list` reports it.pub type AppPersistentAgentInput = core::persistent::PersistentAgentInput;#[uniffi::remote(Record)]diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rsindex efd61487fd..f6b1159e9f 100644--- a/libs/cua/crates/cua-spaces/src/share.rs+++ b/libs/cua/crates/cua-spaces/src/share.rs@@ -1,4 +1,11 @@-//! Sharing a Space with other cua.ai accounts, to watch or to edit.+//! Sharing a Space with people in your team, to watch or to edit.+//!+//! Sharing is for teams (CUA-1883): only members of your own team, one at a+//! time or the whole team, and only from an account in a team on a plan with+//! sharing. The Spaces API decides (team membership comes from Keycloak+//! organisations); the relay enforces, when a share is made and each time one+//! is used. This crate asks first only to give a clear message, and turns the+//! refusals into plain words ([`NO_TEAM`], [`outside_team`]).//!//! Every shared Space is a machine of the owner's account on the relay//! (`relay:<machine-id>` to the people it is shared with):@@ -28,6 +35,17 @@ use serde::{Deserialize, Serialize};use crate::{Error, Result, SpaceId, Spaces};+/// Why an account without a team cannot share, as the apps say it.+pub const NO_TEAM: &str = "Sharing is for teams. Start a team to share this Space.";++/// Where Teams starts, at one seat.+pub const TEAMS_URL: &str = "https://app.cua.ai/buy/teams?from=app_share";++/// Why `who` cannot be shared with.+pub fn outside_team(who: &str) -> String {+ format!("{who} isn't in your team. Invite them to your team first.")+}+/// The user's confirmation before a Space is shared: sharing hands a/// desktop to another account, so an agent calling `share_space` must not/// be able to do it on its own. `cua daemon` answers with user presence@@ -269,7 +287,62 @@ fn entries(m: &crate::relay::RelayMachine) -> Vec<ShareEntry> {.collect()}+/// A refusal from the relay or the Spaces API about who a Space is shared+/// with, in plain words; any other error as it is.+fn share_refused(e: cua_host::Error, who: &str) -> Error {+ let text = e.to_string();+ if text.contains("sharing_needs_team") {+ Error::Relay(cua_host::Error::PermissionDenied(NO_TEAM.into()))+ } else if text.contains("share_outside_team") {+ Error::Relay(cua_host::Error::PermissionDenied(outside_team(who)))+ } else {+ Error::Relay(e)+ }+}+impl Spaces {+ /// Refuses early, before asking the user to confirm, when this account+ /// is in no team that can share. Best effort: a server that predates+ /// team-only sharing, or one that cannot be reached, lets the share+ /// through to the relay, which decides.+ async fn require_team_to_share(&self) -> Result<()> {+ let relay = self.relay()?;+ let (Ok(api), Ok(token)) = (relay.spaces_api(), relay.tokens.access_token().await) else {+ return Ok(());+ };+ match api.sharing(&token).await {+ Ok(s) if !s.can_share => Err(Error::Relay(cua_host::Error::PermissionDenied(+ NO_TEAM.into(),+ ))),+ _ => Ok(()),+ }+ }++ /// People removed from this account's shared Spaces because they are not+ /// in its team, since the owner last acknowledged. For the one-line note+ /// in the apps; empty when there is nothing, or the server has nothing+ /// like it yet.+ pub async fn share_removals(&self) -> Result<Vec<cua_host::spaces_api::ApiShareRemoval>> {+ let relay = self.relay()?;+ let api = relay.spaces_api()?;+ let token = relay.tokens.access_token().await?;+ match api.share_removals(&token).await {+ Err(e) if cua_host::spaces_api::is_teams_unavailable(&e) => Ok(vec![]),+ other => Ok(other?),+ }+ }++ /// The owner has seen [`Self::share_removals`].+ pub async fn ack_share_removals(&self) -> Result<()> {+ let relay = self.relay()?;+ let api = relay.spaces_api()?;+ let token = relay.tokens.access_token().await?;+ match api.ack_share_removals(&token).await {+ Err(e) if cua_host::spaces_api::is_teams_unavailable(&e) => Ok(()),+ other => Ok(other?),+ }+ }+fn shares_path(&self) -> PathBuf {self.home_dir().join("shared-spaces.json")}@@ -440,9 +513,20 @@ impl Spaces {if let Ok(ms) = api.org_machines(&token, &org.id).await&& ms.iter().any(|m| m.machine_id == machine){+ let role = ms+ .iter()+ .find(|m| m.machine_id == machine)+ .map(|m| m.role.as_str())+ .map_or(ShareRole::Editor, |r| {+ if r == "viewer" {+ ShareRole::Viewer+ } else {+ ShareRole::Editor+ }+ });shares.push(ShareEntry {who: format!("team:{}", org.id),- role: ShareRole::Editor,+ role,connected: false,});}@@ -468,10 +552,13 @@ impl Spaces {role: ShareRole,) -> Result<SpaceShares> {if let Some(team) = team_of(who) {- return self.share_with_team(space, &team?).await;+ return self+ .share_with_team_as(space, &team?, role, &mut |_| {})+ .await;}let who = normalize_who(who)?;let canonical = self.resolve(space)?.to_string();+ self.require_team_to_share().await?;let consent = self.inner.share_consent@@ -513,7 +600,8 @@ impl Spaces {..Default::default()},)- .await?;+ .await+ .map_err(|e| share_refused(e, &who))?;self.audit_share("share", &canonical, &format!("{who} {}", role.as_str()));self.shares_of(&canonical, &machine).await}@@ -606,6 +694,19 @@ impl Spaces {self.share_with_team_waiting(space, team, &mut |_| {}).await}+ /// [`Self::share_with_team`] with what the whole team may do: "Can view"+ /// (`Viewer`: watch only) or "Can edit" (`Editor`). Sharing again with+ /// the other role changes it.+ pub async fn share_with_team_as(+ &self,+ space: &str,+ team: &str,+ role: ShareRole,+ waiting: &mut (dyn FnMut(std::time::Duration) + Send),+ ) -> Result<SpaceShares> {+ self.share_with_team_role(space, team, role, waiting).await+ }+/// [`Self::share_with_team`], calling `waiting` while a just-paid plan/// is on its way (show "Finishing setup…").pub async fn share_with_team_waiting(@@ -613,6 +714,17 @@ impl Spaces {space: &str,team: &str,waiting: &mut (dyn FnMut(std::time::Duration) + Send),+ ) -> Result<SpaceShares> {+ self.share_with_team_role(space, team, ShareRole::Editor, waiting)+ .await+ }++ async fn share_with_team_role(+ &self,+ space: &str,+ team: &str,+ role: ShareRole,+ waiting: &mut (dyn FnMut(std::time::Duration) + Send),) -> Result<SpaceShares> {let id = self.resolve(space)?;let canonical = id.to_string();@@ -635,10 +747,15 @@ impl Spaces {.filter(|o| !o.is_empty()).unwrap_or_default();let label = listed.map(|i| i.name).unwrap_or_default();- self.confirm_share(format!(- "Let every member of team {} use {canonical} (see and control it)",- org.label()- ))+ self.confirm_share(match role {+ ShareRole::Viewer => {+ format!("Let every member of team {} watch {canonical}", org.label())+ }+ ShareRole::Editor => format!(+ "Let every member of team {} use {canonical} (see and control it)",+ org.label()+ ),+ }).await?;let machine = self.ensure_shared_machine(&canonical).await?;let token = relay.tokens.access_token().await?;@@ -646,17 +763,21 @@ impl Spaces {&token,cua_host::spaces_api::SETUP_RETRY_WINDOW,waiting,- || api.add_org_machine(&token, &org.id, &machine, &os, &label),+ || api.add_org_machine_as(&token, &org.id, &machine, &os, &label, role.as_str()),).await.map_err(team_err)?;- self.audit_share("share", &canonical, &format!("team:{} editor", org.id));+ self.audit_share(+ "share",+ &canonical,+ &format!("team:{} {}", org.id, role.as_str()),+ );let mut shares = self.shares_of(&canonical, &machine).await?;let who = format!("team:{}", org.id);if !shares.shares.iter().any(|s| s.who == who) {shares.shares.push(ShareEntry {who,- role: ShareRole::Editor,+ role,connected: false,});}diff --git a/libs/cua/crates/cua-spaces/tests/share.rs b/libs/cua/crates/cua-spaces/tests/share.rsindex 2819318209..fc1db04618 100644--- a/libs/cua/crates/cua-spaces/tests/share.rs+++ b/libs/cua/crates/cua-spaces/tests/share.rs@@ -698,7 +698,7 @@ async fn sharing_with_a_team_adds_a_team_machine_including_a_mac() {relay.add_account("ada-token", "ada", Some("[email protected]"));let api = cua_host::testing::FakeSpacesApi::start().await;api.add_account("ada-token", "ada", "[email protected]");- let team = api.add_org("aigis", "AIGIS", "ada", &["team_machines"]);+ let team = api.add_org("aigis", "AIGIS", "ada", &["team_machines", "space_sharing"]);let home = tempfile::tempdir().unwrap();let consent = yes();let spaces = Spaces::builder()@@ -751,16 +751,20 @@ async fn sharing_with_a_team_adds_a_team_machine_including_a_mac() {.any(|r| r.contains("every member of team AIGIS")),"the user confirmed");- // A team gets full use, whatever role was asked for; it is named by- // its organization id.+ // A whole team gets the role that was asked for (here "Can view"); it+ // is named by its organization id.assert_eq!(shares.shares,vec![cua_spaces::share::ShareEntry {who: format!("team:{team}"),- role: ShareRole::Editor,+ role: ShareRole::Viewer,connected: false,}]);+ assert_eq!(+ api.machine_role(&team, &attached.machine_id).as_deref(),+ Some("viewer")+ );let m = relay.machine(&attached.machine_id).unwrap();assert_eq!(m.meta.get("cua.space.os").map(String::as_str),@@ -825,3 +829,153 @@ async fn sharing_with_a_team_adds_a_team_machine_including_a_mac() {.unwrap_err();assert!(e.to_string().contains("Teams are not available"), "{e}");}++#[tokio::test]+async fn sharing_is_refused_for_an_account_without_a_team_and_asks_nothing_first() {+ let relay = FakeRelay::start().await;+ relay.add_account("dan-token", "dan", Some("[email protected]"));+ relay.add_account("ada-token", "ada", Some("[email protected]"));+ let api = cua_host::testing::FakeSpacesApi::start().await;+ api.add_account("dan-token", "dan", "[email protected]");+ api.add_account("ada-token", "ada", "[email protected]");+ api.add_org("aigis", "AIGIS", "ada", &["team_machines", "space_sharing"]);+ let env = MockServer::start(MockAuth::default()).await;+ env.state.advertise(&["relay_attach"]);++ for (token, ok) in [("dan-token", false), ("ada-token", true)] {+ let home = tempfile::tempdir().unwrap();+ let consent = yes();+ let spaces = Spaces::builder()+ .home(home.path())+ .relay(+ RelayAccount::new(&relay.url, Arc::new(StaticToken(token.into())))+ .with_spaces_api(&api.url),+ )+ .share_consent(consent.clone())+ .build();+ let info = spaces+ .add(&env.url(), None, Some("studio".into()))+ .await+ .unwrap();+ let attached = tokio::spawn({+ let relay = relay.clone();+ let state = env.state.clone();+ async move {+ for _ in 0..200 {+ if let Some(a) = state.relay_attached.lock().unwrap().clone() {+ relay.set_online(&a.machine_id, true, "0.1.0");+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ }+ });+ let r = spaces+ .share_space(&info.id, "[email protected]", ShareRole::Viewer)+ .await;+ if ok {+ r.unwrap();+ } else {+ let e = r.unwrap_err();+ assert!(+ e.to_string()+ .contains("Sharing is for teams. Start a team to share this Space."),+ "{e}"+ );+ assert!(+ consent.asked.lock().unwrap().is_empty(),+ "a refused share must not ask for Touch ID"+ );+ assert!(env.state.relay_attached.lock().unwrap().is_none());+ }+ attached.abort();+ }+}++#[tokio::test]+async fn owners_read_and_acknowledge_who_was_removed() {+ let relay = FakeRelay::start().await;+ relay.add_account("ada-token", "ada", Some("[email protected]"));+ let api = cua_host::testing::FakeSpacesApi::start().await;+ api.add_account("ada-token", "ada", "[email protected]");+ api.add_share_removal("ada", "Design", "[email protected]");+ let home = tempfile::tempdir().unwrap();+ let spaces = Spaces::builder()+ .home(home.path())+ .relay(+ RelayAccount::new(&relay.url, Arc::new(StaticToken("ada-token".into())))+ .with_spaces_api(&api.url),+ )+ .build();+ let r = spaces.share_removals().await.unwrap();+ assert_eq!(r.len(), 1);+ assert_eq!(r[0].who, "[email protected]");+ spaces.ack_share_removals().await.unwrap();+ assert!(spaces.share_removals().await.unwrap().is_empty());+}++#[test]+fn refusals_read_in_plain_words() {+ assert_eq!(+ cua_spaces::share::outside_team("[email protected]"),+ "[email protected] isn't in your team. Invite them to your team first."+ );+ assert!(cua_spaces::share::NO_TEAM.starts_with("Sharing is for teams."));+}++/// The sheet's check is an explanation, not the gate: with no Spaces API to+/// ask first (or one that lacks the check), a direct SDK call still reaches+/// the relay, and its refusal reads in plain words.+#[tokio::test]+async fn the_relays_refusal_of_an_outsider_reads_in_plain_words() {+ let relay = FakeRelay::start().await;+ relay.add_account("ada-token", "ada", Some("[email protected]"));+ let env = MockServer::start(MockAuth::default()).await;+ env.state.advertise(&["relay_attach"]);+ let home = tempfile::tempdir().unwrap();+ // No `with_spaces_api`: nothing to check with before the relay.+ let spaces = Spaces::builder()+ .home(home.path())+ .relay(RelayAccount::new(+ &relay.url,+ Arc::new(StaticToken("ada-token".into())),+ ))+ .share_consent(yes())+ .build();+ let info = spaces+ .add(&env.url(), None, Some("studio".into()))+ .await+ .unwrap();+ let attached = tokio::spawn({+ let relay = relay.clone();+ let state = env.state.clone();+ async move {+ for _ in 0..200 {+ if let Some(a) = state.relay_attached.lock().unwrap().clone() {+ relay.set_online(&a.machine_id, true, "0.1.0");+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ }+ });+ // A teammate first, so the computer is registered with the relay.+ spaces+ .share_space(&info.id, "[email protected]", ShareRole::Viewer)+ .await+ .unwrap();+ attached.abort();+ relay.refuse_shares(Some("share_outside_team"));+ let e = spaces+ .share_space(&info.id, "[email protected]", ShareRole::Viewer)+ .await+ .unwrap_err();+ assert!(+ e.to_string()+ .contains("[email protected] isn't in your team. Invite them to your team first."),+ "{e}"+ );+ // And nothing was shared with her.+ let shares = spaces.space_shares(&info.id).await.unwrap();+ assert!(shares.shares.iter().all(|s| s.who != "[email protected]"));+}diff --git a/libs/cua/scripts/generate-app-core-ffi.py b/libs/cua/scripts/generate-app-core-ffi.pyindex 6fc78ce25c..49127741ad 100644--- a/libs/cua/scripts/generate-app-core-ffi.py+++ b/libs/cua/scripts/generate-app-core-ffi.py@@ -60,7 +60,7 @@ TYPES = [("agents.rs", "agents", ["AgentStatus", "SpaceAgentRun", "AgentSetupStatus", "AgentSettingsRow", "AgentSetupOutcomeInput", "AgentSetupSummary"]),("devices.rs", "devices", ["DeviceInput", "MachineInput", "AuditInput", "DevicesInput", "BannerTone", "DeviceAction", "DeviceBanner", "DeviceConfirm", "UnconfirmedMachine", "DeviceRow", "ApprovalPrompt", "ActivityRow", "EnrollmentKind", "MachineAccessNotice", "ThisDevice", "DevicesLabels", "DevicesView", "EnrollMethod", "EnrollPhase", "EnrollState", "EnrollAction", "EnrollOption", "EnrollView", "ApproveSheetState", "ApproveSheetAction", "ApproveRequest", "ApproveSheetView"]),("cloud_connect.rs", "cloud_connect", ["CloudProviderInput", "CloudConnectInput", "CloudCheckInput", "CloudConnectPhase", "CloudConnectState", "CloudConnectAction", "CloudTargetArgs", "CloudConnectRequest", "CloudProviderRow", "CloudField", "CloudCheckRow", "CloudConnectView"]),- ("share.rs", "share", ["ShareEntryInput", "ShareInput", "ShareRequest", "ShareSheetState", "ShareSheetAction", "RoleOption", "ShareRowView", "ShareSheetView"]),+ ("share.rs", "share", ["ShareEntryInput", "ShareInput", "ShareRequest", "ShareSheetState", "ShareSheetAction", "RoleOption", "ShareRowView", "ShareActionView", "ShareSheetView", "ShareGate", "ShareRemovalInput", "ShareRemovalNote"]),("persistent.rs", "persistent", ["PersistentAgentInput", "DriveEntryInput", "FileVersionInput", "OpenFileInput", "RoutineInput", "ComputerGrantInput", "AccessAuditInput", "AgentsInput", "AgentTab", "RoutineScheduleKind", "RoutineForm", "AgentsRequest", "AgentsState", "AgentsAction", "AgentRowView", "LineView", "TabView", "FileView", "AgentDetailView", "AgentsView"]),("drive_page.rs", "drive_page", ["DriveRequestInput", "DriveGrantInput", "DriveDeviceInput", "DriveConflictInput", "DriveSyncInput", "DriveInput", "DriveRequest", "DriveState", "DriveAction", "ConflictView", "DriveView"]),("notifications.rs", "notifications", ["NotificationInput", "SystemNote", "NotificationsPlan", "NotificationsView"]),diff --git a/libs/cua/spaces-contract/manifest.json b/libs/cua/spaces-contract/manifest.jsonindex 16e315d416..e0dbd7177a 100644--- a/libs/cua/spaces-contract/manifest.json+++ b/libs/cua/spaces-contract/manifest.json@@ -4623,8 +4623,8 @@{"name": "share_space","category": "sharing",- "description": "Let another cua.ai account watch or edit a Space.",- "instructions": "Shares the Space through the cua.ai relay with one account, by verified email or account id, or with a whole team as `team:<id>` (always as an editor; Teams plan); the same allowlist and device enrollment `cua host share` uses. A viewer joins presence with their own named cursor and watches a view-only stream: the Space's driver refuses their input, shell, files and MCP. An editor gets full use, and their input is a human session. Sharing again changes the role. A host (`relay:<id>`) is shared directly; any other Space (local, cloud, or added by address) is attached to the relay on its first share: its own driver dials out, so it needs no inbound port. Invitees open `invitee_space`.",+ "description": "Let someone in your team watch or edit a Space.",+ "instructions": "Shares the Space through the cua.ai relay with one person in your own team, by verified email or account id, or with the whole team as `team:<id>` (as a viewer or an editor). Sharing is for teams: an account in no team gets `sharing_needs_team` (\"Sharing is for teams. Start a team to share this Space.\"), and someone outside your team gets `share_outside_team`. The same allowlist and device enrollment `cua host share` uses. A viewer joins presence with their own named cursor and watches a view-only stream: the Space's driver refuses their input, shell, files and MCP. An editor gets full use, and their input is a human session. Sharing again changes the role. A host (`relay:<id>`) is shared directly; any other Space (local, cloud, or added by address) is attached to the relay on its first share: its own driver dials out, so it needs no inbound port. Invitees open `invitee_space`.","platforms": ["macos","windows",@@ -4672,7 +4672,7 @@"type": "string"},"who": {- "description": "Who: an email address (verified by cua.ai) or an account id, or\n`team:<id>` for a whole team. A team always gets `editor` and needs\nthe Teams plan; the sharer is a team owner or admin who owns the Space.",+ "description": "Who: the email address (verified by cua.ai) or account id of someone\nin your own team, or `team:<id>` for the whole team (as `viewer` or\n`editor`). Sharing is for teams: it needs a team on the Teams plan,\nand a whole-team share needs a team owner or admin who owns the Space.","type": "string"}},diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swiftindex 36c9a6a709..929b5a1715 100644--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift@@ -30334,6 +30334,72 @@ public func FfiConverterTypeAppSettingsSection_lower(_ value: AppSettingsSection}+public struct AppShareActionView: Equatable, Hashable {+ /**+ * The button's words.+ */+ public var label: String+ /**+ * Where it opens.+ */+ public var url: String++ // Default memberwise initializers are never public by default, so we+ // declare one manually.+ public init(+ /**+ * The button's words.+ */label: String,+ /**+ * Where it opens.+ */url: String) {+ self.label = label+ self.url = url+ }+++++}++#if compiler(>=6)+extension AppShareActionView: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeAppShareActionView: FfiConverterRustBuffer {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppShareActionView {+ return+ try AppShareActionView(+ label: FfiConverterString.read(from: &buf),+ url: FfiConverterString.read(from: &buf)+ )+ }++ public static func write(_ value: AppShareActionView, into buf: inout [UInt8]) {+ FfiConverterString.write(value.label, into: &buf)+ FfiConverterString.write(value.url, into: &buf)+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppShareActionView_lift(_ buf: RustBuffer) throws -> AppShareActionView {+ return try FfiConverterTypeAppShareActionView.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppShareActionView_lower(_ value: AppShareActionView) -> RustBuffer {+ return FfiConverterTypeAppShareActionView.lower(value)+}++public struct AppShareEntryInput: Equatable, Hashable {/*** Email or account id.@@ -30410,6 +30476,72 @@ public func FfiConverterTypeAppShareEntryInput_lower(_ value: AppShareEntryInput}+public struct AppShareGate: Equatable, Hashable {+ /**+ * "Sharing is for teams. Start a team to share this Space."+ */+ public var reason: String+ /**+ * "See Teams": where Teams starts, at one seat.+ */+ public var action: AppShareActionView++ // Default memberwise initializers are never public by default, so we+ // declare one manually.+ public init(+ /**+ * "Sharing is for teams. Start a team to share this Space."+ */reason: String,+ /**+ * "See Teams": where Teams starts, at one seat.+ */action: AppShareActionView) {+ self.reason = reason+ self.action = action+ }+++++}++#if compiler(>=6)+extension AppShareGate: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeAppShareGate: FfiConverterRustBuffer {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppShareGate {+ return+ try AppShareGate(+ reason: FfiConverterString.read(from: &buf),+ action: FfiConverterTypeAppShareActionView.read(from: &buf)+ )+ }++ public static func write(_ value: AppShareGate, into buf: inout [UInt8]) {+ FfiConverterString.write(value.reason, into: &buf)+ FfiConverterTypeAppShareActionView.write(value.action, into: &buf)+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppShareGate_lift(_ buf: RustBuffer) throws -> AppShareGate {+ return try FfiConverterTypeAppShareGate.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppShareGate_lower(_ value: AppShareGate) -> RustBuffer {+ return FfiConverterTypeAppShareGate.lower(value)+}++public struct AppShareInput: Equatable, Hashable {/*** The Space's id.@@ -30506,6 +30638,148 @@ public func FfiConverterTypeAppShareInput_lower(_ value: AppShareInput) -> RustB}+public struct AppShareRemovalInput: Equatable, Hashable {+ /**+ * The person (an email or account id).+ */+ public var who: String+ /**+ * The computer's name.+ */+ public var machineName: String++ // Default memberwise initializers are never public by default, so we+ // declare one manually.+ public init(+ /**+ * The person (an email or account id).+ */who: String,+ /**+ * The computer's name.+ */machineName: String) {+ self.who = who+ self.machineName = machineName+ }+++++}++#if compiler(>=6)+extension AppShareRemovalInput: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeAppShareRemovalInput: FfiConverterRustBuffer {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppShareRemovalInput {+ return+ try AppShareRemovalInput(+ who: FfiConverterString.read(from: &buf),+ machineName: FfiConverterString.read(from: &buf)+ )+ }++ public static func write(_ value: AppShareRemovalInput, into buf: inout [UInt8]) {+ FfiConverterString.write(value.who, into: &buf)+ FfiConverterString.write(value.machineName, into: &buf)+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppShareRemovalInput_lift(_ buf: RustBuffer) throws -> AppShareRemovalInput {+ return try FfiConverterTypeAppShareRemovalInput.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppShareRemovalInput_lower(_ value: AppShareRemovalInput) -> RustBuffer {+ return FfiConverterTypeAppShareRemovalInput.lower(value)+}+++public struct AppShareRemovalNote: Equatable, Hashable {+ /**+ * One line: who can no longer open what, and why.+ */+ public var text: String+ /**+ * "Invite to your team".+ */+ public var action: AppShareActionView+ /**+ * Dismiss.+ */+ public var dismiss: String++ // Default memberwise initializers are never public by default, so we+ // declare one manually.+ public init(+ /**+ * One line: who can no longer open what, and why.+ */text: String,+ /**+ * "Invite to your team".+ */action: AppShareActionView,+ /**+ * Dismiss.+ */dismiss: String) {+ self.text = text+ self.action = action+ self.dismiss = dismiss+ }+++++}++#if compiler(>=6)+extension AppShareRemovalNote: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeAppShareRemovalNote: FfiConverterRustBuffer {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppShareRemovalNote {+ return+ try AppShareRemovalNote(+ text: FfiConverterString.read(from: &buf),+ action: FfiConverterTypeAppShareActionView.read(from: &buf),+ dismiss: FfiConverterString.read(from: &buf)+ )+ }++ public static func write(_ value: AppShareRemovalNote, into buf: inout [UInt8]) {+ FfiConverterString.write(value.text, into: &buf)+ FfiConverterTypeAppShareActionView.write(value.action, into: &buf)+ FfiConverterString.write(value.dismiss, into: &buf)+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppShareRemovalNote_lift(_ buf: RustBuffer) throws -> AppShareRemovalNote {+ return try FfiConverterTypeAppShareRemovalNote.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppShareRemovalNote_lower(_ value: AppShareRemovalNote) -> RustBuffer {+ return FfiConverterTypeAppShareRemovalNote.lower(value)+}++public struct AppShareRowView: Equatable, Hashable {/*** Email or account id.@@ -61116,6 +61390,54 @@ fileprivate struct FfiConverterOptionTypeAppRuntimeSwitch: FfiConverterRustBuffe}}+#if swift(>=5.8)+@_documentation(visibility: private)+#endif+fileprivate struct FfiConverterOptionTypeAppShareGate: FfiConverterRustBuffer {+ typealias SwiftType = AppShareGate?++ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {+ guard let value = value else {+ writeInt(&buf, Int8(0))+ return+ }+ writeInt(&buf, Int8(1))+ FfiConverterTypeAppShareGate.write(value, into: &buf)+ }++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {+ switch try readInt(&buf) as Int8 {+ case 0: return nil+ case 1: return try FfiConverterTypeAppShareGate.read(from: &buf)+ default: throw UniffiInternalError.unexpectedOptionalTag+ }+ }+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+fileprivate struct FfiConverterOptionTypeAppShareRemovalNote: FfiConverterRustBuffer {+ typealias SwiftType = AppShareRemovalNote?++ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {+ guard let value = value else {+ writeInt(&buf, Int8(0))+ return+ }+ writeInt(&buf, Int8(1))+ FfiConverterTypeAppShareRemovalNote.write(value, into: &buf)+ }++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {+ switch try readInt(&buf) as Int8 {+ case 0: return nil+ case 1: return try FfiConverterTypeAppShareRemovalNote.read(from: &buf)+ default: throw UniffiInternalError.unexpectedOptionalTag+ }+ }+}+#if swift(>=5.8)@_documentation(visibility: private)#endif@@ -64965,6 +65287,31 @@ fileprivate struct FfiConverterSequenceTypeAppShareEntryInput: FfiConverterRustB}}+#if swift(>=5.8)+@_documentation(visibility: private)+#endif+fileprivate struct FfiConverterSequenceTypeAppShareRemovalInput: FfiConverterRustBuffer {+ typealias SwiftType = [AppShareRemovalInput]++ public static func write(_ value: [AppShareRemovalInput], into buf: inout [UInt8]) {+ let len = Int32(value.count)+ writeInt(&buf, len)+ for item in value {+ FfiConverterTypeAppShareRemovalInput.write(item, into: &buf)+ }+ }++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [AppShareRemovalInput] {+ let len: Int32 = try readInt(&buf)+ var seq = [AppShareRemovalInput]()+ seq.reserveCapacity(Int(len))+ for _ in 0 ..< len {+ seq.append(try FfiConverterTypeAppShareRemovalInput.read(from: &buf))+ }+ return seq+ }+}+#if swift(>=5.8)@_documentation(visibility: private)#endif@@ -66622,6 +66969,23 @@ public func appAccountAppUrl() -> String {)})}+/**+ * The owner has seen the note: it is not shown again.+ */+public func appAckShareRemovals(accountToken: String)async throws {+ return+ try await uniffiRustCallAsync(+ rustFutureFunc: {+ uniffi_cua_spaces_ffi_fn_func_app_ack_share_removals(FfiConverterString.lower(accountToken)+ )+ },+ pollFunc: ffi_cua_spaces_ffi_rust_future_poll_void,+ completeFunc: ffi_cua_spaces_ffi_rust_future_complete_void,+ freeFunc: ffi_cua_spaces_ffi_rust_future_free_void,+ liftFunc: { $0 },+ errorHandler: FfiConverterTypeCuaError_lift+ )+}/*** The add or replace sheet.*/@@ -68675,6 +69039,30 @@ public func appShareActionFromJson(json: String)throws -> AppShareSheetAction)})}+/**+ * A refused share in plain words (`share_outside_team`,+ * `sharing_needs_team`); `None` for any other error.+ */+public func appShareErrorWords(error: String, who: String) -> String? {+ return try! FfiConverterOptionString.lift(try! rustCall() {+ uniffi_cua_spaces_ffi_fn_func_app_share_error_words(+ FfiConverterString.lower(error),+ FfiConverterString.lower(who),$0+ )+})+}+/**+ * Why the Share sheet is closed, from whether the account is in a team+ * that can share (`None`: the host could not say, so the sheet stays open+ * and the server decides). Sharing is for teams (CUA-1883).+ */+public func appShareGate(hasTeam: Bool?) -> AppShareGate? {+ return try! FfiConverterOptionTypeAppShareGate.lift(try! rustCall() {+ uniffi_cua_spaces_ffi_fn_func_app_share_gate(+ FfiConverterOptionBool.lower(hasTeam),$0+ )+})+}/*** A new Share sheet.*/@@ -68706,6 +69094,35 @@ public func appShareReduce(input: AppShareInput, state: AppShareSheetState, acti)})}+/**+ * The owner's one-line note about people removed from shared computers.+ */+public func appShareRemovalNote(removals: [AppShareRemovalInput]) -> AppShareRemovalNote? {+ return try! FfiConverterOptionTypeAppShareRemovalNote.lift(try! rustCall() {+ uniffi_cua_spaces_ffi_fn_func_app_share_removal_note(+ FfiConverterSequenceTypeAppShareRemovalInput.lower(removals),$0+ )+})+}+/**+ * People removed from the account's shared computers because sharing is+ * for teams now, until [`app_ack_share_removals`]. Empty on a server that+ * predates it.+ */+public func appShareRemovals(accountToken: String)async throws -> [AppShareRemovalInput] {+ return+ try await uniffiRustCallAsync(+ rustFutureFunc: {+ uniffi_cua_spaces_ffi_fn_func_app_share_removals(FfiConverterString.lower(accountToken)+ )+ },+ pollFunc: ffi_cua_spaces_ffi_rust_future_poll_rust_buffer,+ completeFunc: ffi_cua_spaces_ffi_rust_future_complete_rust_buffer,+ freeFunc: ffi_cua_spaces_ffi_rust_future_free_rust_buffer,+ liftFunc: FfiConverterSequenceTypeAppShareRemovalInput.lift,+ errorHandler: FfiConverterTypeCuaError_lift+ )+}/*** The Share sheet's state from JSON (fixtures, parity).*/@@ -69878,6 +70295,9 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_spaces_ffi_checksum_func_app_account_app_url() != 9943) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cua_spaces_ffi_checksum_func_app_ack_share_removals() != 16071) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form() != 42778) {return InitializationResult.apiChecksumMismatch}@@ -70451,6 +70871,12 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_spaces_ffi_checksum_func_app_share_action_from_json() != 61097) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cua_spaces_ffi_checksum_func_app_share_error_words() != 56839) {+ return InitializationResult.apiChecksumMismatch+ }+ if (uniffi_cua_spaces_ffi_checksum_func_app_share_gate() != 9867) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cua_spaces_ffi_checksum_func_app_share_initial() != 65098) {return InitializationResult.apiChecksumMismatch}@@ -70460,6 +70886,12 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_spaces_ffi_checksum_func_app_share_reduce() != 46853) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cua_spaces_ffi_checksum_func_app_share_removal_note() != 63359) {+ return InitializationResult.apiChecksumMismatch+ }+ if (uniffi_cua_spaces_ffi_checksum_func_app_share_removals() != 49780) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cua_spaces_ffi_checksum_func_app_share_state_from_json() != 38498) {return InitializationResult.apiChecksumMismatch}diff --git a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.hindex 7ce72d8222..a7d87a5ade 100644--- a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h+++ b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h@@ -694,6 +694,11 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_app_about_view(RustBuffer input, RustCa#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_ACCOUNT_APP_URLRustBuffer uniffi_cua_spaces_ffi_fn_func_app_account_app_url(RustCallStatus *_Nonnull out_status+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_ACK_SHARE_REMOVALS+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_ACK_SHARE_REMOVALS+uint64_t uniffi_cua_spaces_ffi_fn_func_app_ack_share_removals(RustBuffer account_token);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_AGENT_KEY_FORM@@ -1667,6 +1672,16 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_app_settings_with_storage(RustBuffer paRustBuffer uniffi_cua_spaces_ffi_fn_func_app_share_action_from_json(RustBuffer json, RustCallStatus *_Nonnull out_status);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_ERROR_WORDS+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_ERROR_WORDS+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_share_error_words(RustBuffer error, RustBuffer who, RustCallStatus *_Nonnull out_status+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_GATE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_GATE+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_share_gate(RustBuffer has_team, RustCallStatus *_Nonnull out_status+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_INITIAL#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_INITIALRustBuffer uniffi_cua_spaces_ffi_fn_func_app_share_initial(RustCallStatus *_Nonnull out_status@@ -1683,6 +1698,16 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_app_share_input_from_json(RustBuffer jsRustBuffer uniffi_cua_spaces_ffi_fn_func_app_share_reduce(RustBuffer input, RustBuffer state, RustBuffer action, RustCallStatus *_Nonnull out_status);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_REMOVAL_NOTE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_REMOVAL_NOTE+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_share_removal_note(RustBuffer removals, RustCallStatus *_Nonnull out_status+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_REMOVALS+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_REMOVALS+uint64_t uniffi_cua_spaces_ffi_fn_func_app_share_removals(RustBuffer account_token+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_STATE_FROM_JSON#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SHARE_STATE_FROM_JSONRustBuffer uniffi_cua_spaces_ffi_fn_func_app_share_state_from_json(RustBuffer json, RustCallStatus *_Nonnull out_status@@ -2490,6 +2515,12 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_about_view(void#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_ACCOUNT_APP_URLuint16_t uniffi_cua_spaces_ffi_checksum_func_app_account_app_url(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_ACK_SHARE_REMOVALS+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_ACK_SHARE_REMOVALS+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_ack_share_removals(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_AGENT_KEY_FORM@@ -3636,6 +3667,18 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_settings_with_storage(void#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_ACTION_FROM_JSONuint16_t uniffi_cua_spaces_ffi_checksum_func_app_share_action_from_json(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_ERROR_WORDS+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_ERROR_WORDS+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_share_error_words(void++);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_GATE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_GATE+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_share_gate(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_INITIAL@@ -3654,6 +3697,18 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_share_input_from_json(void#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_REDUCEuint16_t uniffi_cua_spaces_ffi_checksum_func_app_share_reduce(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_REMOVAL_NOTE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_REMOVAL_NOTE+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_share_removal_note(void++);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_REMOVALS+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_REMOVALS+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_share_removals(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SHARE_STATE_FROM_JSONdiff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex c90d4c66cb..5f8e7ef38b 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -9450,7 +9450,7 @@"usage": "cua host start [OPTIONS]"},{- "abstract": "Share a relay computer (this one, or `--machine`) with other cua.ai accounts (id or verified email). Run from an enrolled device; every change is in the owner's audit log (`cua devices audit`)",+ "abstract": "Share a relay computer (this one, or `--machine`) with people in your team (id or verified email). Run from an enrolled device; every change is in the owner's audit log (`cua devices audit`)","after_help": "Examples:\n cua host share [email protected]\n cua host share [email protected] --machine 0123abcd4567ef89 --yes","aliases": [],"arguments": [@@ -10104,8 +10104,8 @@"usage": "cua spaces rm [OPTIONS] <SPACE>"},{- "abstract": "Let another cua.ai account watch (viewer) or use (editor) a Space, through the relay. They open it as `relay:<computer>`",- "after_help": "Examples:\n cua spaces share local:studio [email protected]\n cua spaces share local:studio [email protected] --role editor\n cua spaces share relay:0123abcd4567ef89 acct-42 --role viewer\n # From a script or agent: confirm with Touch ID or your password here\n cua spaces share local:studio [email protected] --yes",+ "abstract": "Let someone in your team watch (viewer) or use (editor) a Space, through the relay. They open it as `relay:<computer>`. Sharing is for teams: you need a team, and they must be in it (or share with the whole team as `team:<id>`)",+ "after_help": "Examples:\n cua spaces share local:studio [email protected]\n cua spaces share local:studio [email protected] --role editor\n cua spaces share relay:0123abcd4567ef89 acct-42 --role viewer\n # The whole team, to watch\n cua spaces share local:studio team:acme --role viewer\n # From a script or agent: confirm with Touch ID or your password here\n cua spaces share local:studio [email protected] --yes","aliases": [],"arguments": [{@@ -10120,7 +10120,7 @@},{"default_value": null,- "help": "Their email (verified by cua.ai) or account id",+ "help": "Their email (verified by cua.ai) or account id, in your team; or `team:<id>` for the whole team","hidden": false,"is_optional": false,"name": "WHO",