From 4226dc6010b8c141d04c1322c10cda97586e1a87 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 19 Nov 2026 13:05:01 +0800 Subject: [PATCH 1/2] feat(remote-connect): let devices opt out of inbound control --- docs/interactive-capabilities/README.md | 16 +-- .../capabilities.json | 68 +++++++++- .../capabilities/feature.remote-connect.md | 4 + .../technical/product-control-open-audit.json | 22 ++- .../technical/tauri-command-map.json | 24 +++- src/apps/cli/README.md | 6 + src/apps/cli/src/account.rs | 62 ++++++++- src/apps/cli/src/main.rs | 28 ++++ src/apps/cli/src/remote_control.rs | 18 ++- .../desktop/src/api/remote_connect_api.rs | 124 +++++++++++++++-- .../remote_connect_api/relay_routes_tests.rs | 128 ++++++++++++++++++ src/apps/desktop/src/lib.rs | 1 + .../service/remote_connect/account_runtime.rs | 4 +- .../remote_connect/bot/command_router.rs | 6 + .../src/service/remote_connect/control.rs | 4 + .../core/src/service/remote_connect/mod.rs | 35 +++-- .../generated/product-control-catalog.json | 66 ++++++++- .../generated/remote-surface-registry.json | 14 +- .../src/remote_surface/table.rs | 1 + .../src/remote_connect/device.rs | 71 ++++++++++ .../src/remote_connect/relay_client.rs | 3 + .../interactive-capabilities/catalog.json | 14 ++ .../RemoteConnectDialog.contract.test.ts | 5 + .../RemoteConnectDialog.tsx | 38 ++++++ .../generated/interactive-capabilities.json | 66 ++++++++- .../api/generated/productControl.ts | 2 +- .../api/generated/remoteSurface.ts | 3 +- .../api/service-api/RemoteConnectAPI.ts | 5 + .../peer-device/PeerConnectionManager.test.ts | 10 ++ .../peer-device/PeerConnectionManager.ts | 15 +- .../PeerDeviceSurfaceController.ts | 8 +- .../peer-device/peerDeviceSurfaceRuntime.ts | 3 +- src/web-ui/src/locales/en-US/common.json | 4 + src/web-ui/src/locales/zh-CN/common.json | 4 + src/web-ui/src/locales/zh-TW/common.json | 4 + 35 files changed, 819 insertions(+), 67 deletions(-) diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index a32578af80..58bac5a850 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -1,9 +1,9 @@ # OpenBitFun 功能与设置目录 / OpenBitFun Features & Settings -OpenBitFun Playbook 当前包含 **24 个功能**和 **23 个设置页**,共 **47 个**用户可理解的条目、**368 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 +OpenBitFun Playbook 当前包含 **24 个功能**和 **23 个设置页**,共 **47 个**用户可理解的条目、**369 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 -OpenBitFun Playbook currently contains **24 features**, **23 settings pages**, and **368** source-backed sub-capabilities across **47** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. +OpenBitFun Playbook currently contains **24 features**, **23 settings pages**, and **369** source-backed sub-capabilities across **47** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. ## 唯一事实源 / Single source of truth @@ -27,20 +27,20 @@ OpenBitFun Playbook currently contains **24 features**, **23 settings pages**, a - Generated per-item interaction audit: `docs/interactive-capabilities/technical/product-control-open-audit.json` - Generated low-level audit map: `docs/interactive-capabilities/technical/tauri-command-map.json` -说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **701** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 +说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **702** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 -Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **701** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes. +Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **702** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes. ## 控制边界 / Control boundary -- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **64**、委托 **74**、需交互 **230**、不支持 **0**。 +- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **64**、委托 **74**、需交互 **231**、不支持 **0**。 - 稳定行为声明为带 JSON 输入契约的 `operations` 或 `options`,并绑定原生产品控制 Provider;智能体不接触原始 Tauri Command。 -- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 368 项子能力都不会写入 system prompt。 +- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 369 项子能力都不会写入 system prompt。 - 目录发现与契约读取不依赖 React 或可见窗口。普通配置型 option 统一由 Product Assembly 的共享 ConfigService 执行器读、写并回读,因此 Desktop、CLI 与 Headless 表面走同一份实现;只有宿主原生 operation/provider option 和界面导航按表面注册适配器,缺失时必须明确返回不可用,禁止静默回退本机。只读智能体只能发现和读取目录。 -- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **64 direct**, **74 delegated**, **230 interactive**, and **0 unsupported**. +- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **64 direct**, **74 delegated**, **231 interactive**, and **0 unsupported**. - Stable behavior becomes a typed `operation` or `option` with a JSON input contract and a native product-control provider. Agents never receive raw Tauri commands. -- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 368 documented items enters the system prompt. +- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 369 documented items enters the system prompt. - Discovery and contract lookup do not depend on React or a visible window. Ordinary config-backed options are read, written, and read back by one Product Assembly ConfigService executor shared by Desktop, CLI, and headless surfaces. Only host-native operations/provider options and presentation routes install surface adapters; missing adapters return explicit unavailability without local fallback. Read-only agents may only discover and inspect entries. ## 防腐化门禁 / Anti-drift gates diff --git a/docs/interactive-capabilities/capabilities.json b/docs/interactive-capabilities/capabilities.json index d33f458ef9..e9eb9c7c12 100644 --- a/docs/interactive-capabilities/capabilities.json +++ b/docs/interactive-capabilities/capabilities.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c", + "digest": "bec28fbd98726d074ccb1073068d0b9c147dddba552cbd46736305e58852b681", "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { @@ -187,11 +187,11 @@ "features": 24, "settings": 23, "userFacing": 47, - "documentedItems": 368, + "documentedItems": 369, "controlCoverage": { "direct": 64, "delegated": 74, - "interactive": 230, + "interactive": 231, "unsupported": 0 } }, @@ -9558,6 +9558,7 @@ "id": "feature.remote-connect:query", "capabilityId": "feature.remote-connect", "itemIds": [ + "device-control-permission", "connection-methods", "start-stop-status", "network", @@ -10012,6 +10013,52 @@ "eventName": "openbitfun:open-remote-connect" } }, + { + "id": "feature.remote-connect:open:device-control-permission", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "device-control-permission" + ], + "kind": "open", + "risk": "ui", + "executionHost": "presentationSurface", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "product_control_presentation_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "openReason": "unstructuredInteraction", + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, { "id": "feature.remote-connect:open:connection-methods", "capabilityId": "feature.remote-connect", @@ -28809,6 +28856,19 @@ "Ask the agent directly to start/stop channels, launch WeChat QR login, or inspect listener health" ], "items": [ + { + "id": "device-control-permission", + "titleZh": "本机可被控制", + "titleEn": "Allow control of this device", + "descriptionZh": "在设备与连接的概览中切换。关闭后,本机显示为离线,仍可控制其他在线设备。", + "descriptionEn": "Switch this in the Devices & Connections overview. When off, this device appears offline and can still control other online devices.", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "请在当前设备的「设备与连接」概览中切换「本机可被控制」,选择其他设备能否连接这台设备。", + "reasonEn": "Choose “Allow control of this device” in the local Devices & Connections overview to set whether other devices can connect to this one." + } + }, { "id": "connection-methods", "titleZh": "使用免部署官方 Relay 或桌面端局域网 Relay(可同时开启)", @@ -29167,6 +29227,8 @@ "Pair a WeChat, Feishu, or Telegram bot to chat and approve permissions from your messenger", "Same-account Peer Device Mode: expand and operate another computer’s workspaces right in your sidebar", "Ask the agent directly to start/stop channels, launch WeChat QR login, or inspect listener health", + "本机可被控制", + "Allow control of this device", "使用免部署官方 Relay 或桌面端局域网 Relay(可同时开启)", "Use the zero-setup official Relay or Desktop LAN Relay concurrently", "一键启动、停用远控渠道并查看实时连接与设备信息", diff --git a/docs/interactive-capabilities/capabilities/feature.remote-connect.md b/docs/interactive-capabilities/capabilities/feature.remote-connect.md index 65b0cd3f81..3f2feb9976 100644 --- a/docs/interactive-capabilities/capabilities/feature.remote-connect.md +++ b/docs/interactive-capabilities/capabilities/feature.remote-connect.md @@ -26,6 +26,10 @@ Follow sessions, approve permissions, and keep working from Mobile Web or a WeCh ## 完整功能清单 / Everything included +- **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 本机可被控制 + - Allow control of this device + - 说明:在设备与连接的概览中切换。关闭后,本机显示为离线,仍可控制其他在线设备。 + - Why & how: Switch this in the Devices & Connections overview. When off, this device appears offline and can still control other online devices. - **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 使用免部署官方 Relay 或桌面端局域网 Relay(可同时开启) - Use the zero-setup official Relay or Desktop LAN Relay concurrently - 说明:外网出门走官方加密中继即开即用,内网高速互连可同时打开桌面端局域网 Relay;首次身份认证均需联网登录。 diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index a4cd7db940..269a4236e5 100644 --- a/docs/interactive-capabilities/technical/product-control-open-audit.json +++ b/docs/interactive-capabilities/technical/product-control-open-audit.json @@ -1,12 +1,12 @@ { "schemaVersion": 1, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c", - "count": 230, + "catalogDigest": "bec28fbd98726d074ccb1073068d0b9c147dddba552cbd46736305e58852b681", + "count": 231, "reasonCounts": { "externalAuth": 4, "secretEntry": 6, - "unstructuredInteraction": 193, + "unstructuredInteraction": 194, "visualSelection": 27 }, "entries": [ @@ -2122,6 +2122,22 @@ "command:ssh_disconnect_all" ] }, + { + "capabilityId": "feature.remote-connect", + "itemId": "device-control-permission", + "titleZh": "本机可被控制", + "titleEn": "Allow control of this device", + "reasonCode": "unstructuredInteraction", + "reasonZh": "请在当前设备的「设备与连接」概览中切换「本机可被控制」,选择其他设备能否连接这台设备。", + "reasonEn": "Choose “Allow control of this device” in the local Devices & Connections overview to set whether other devices can connect to this one.", + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + }, + "evidence": [ + "command:remote_connect_set_allowed" + ] + }, { "capabilityId": "feature.remote-connect", "itemId": "connection-methods", diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index adfa1c0169..7f4026a0a5 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -1,11 +1,11 @@ { "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c", - "commandCount": 701, + "catalogDigest": "bec28fbd98726d074ccb1073068d0b9c147dddba552cbd46736305e58852b681", + "commandCount": 702, "coverage": { - "commandCount": 701, - "documentedCommandCount": 634, + "commandCount": 702, + "documentedCommandCount": 635, "implementationCommandCount": 67, "implementationDigest": "3c03db6cdd74260fd8b7203d30ea4ab7224b4cfdea4a532c11e41a587cd92b19" }, @@ -7481,6 +7481,22 @@ "signature": "fn remote_connect_get_methods() -> Result, String>", "remoteWorkspacePolicy": "WorkspaceAgnostic" }, + { + "id": "remote_connect_set_allowed", + "moduleId": "remote_connect", + "capabilityId": "feature.remote-connect", + "capabilityIds": [ + "feature.remote-connect" + ], + "documentedItemIds": [ + "feature.remote-connect:device-control-permission" + ], + "visibility": "documented", + "rustPath": "api::remote_connect_api::remote_connect_set_allowed", + "sourceFile": "src/apps/desktop/src/api/remote_connect_api.rs", + "signature": "fn remote_connect_set_allowed(request: SetRemoteControlRequest) -> Result<(), String>", + "remoteWorkspacePolicy": "WorkspaceAgnostic" + }, { "id": "remote_connect_set_bot_verbose_mode", "moduleId": "remote_connect", diff --git a/src/apps/cli/README.md b/src/apps/cli/README.md index a5d0a95270..b612bcdc6f 100644 --- a/src/apps/cli/README.md +++ b/src/apps/cli/README.md @@ -388,6 +388,12 @@ openbitfun daemon install openbitfun daemon status ``` +Run `openbitfun daemon remote-control` to show this device’s setting (default +`on`). Use `openbitfun daemon remote-control off` to appear offline and stop +accepting remote control, or `openbitfun daemon remote-control on` to allow it +again. The setting is shared with Desktop and persists across restarts. An +offline device can still control online devices on the same account. + Linux uses a systemd user service and macOS uses a LaunchAgent. Windows does not currently install an auto-start service; use `openbitfun daemon run` under a supervisor instead. Run `openbitfun daemon --help` for lifecycle commands and diff --git a/src/apps/cli/src/account.rs b/src/apps/cli/src/account.rs index aaccedbc35..57e488805b 100644 --- a/src/apps/cli/src/account.rs +++ b/src/apps/cli/src/account.rs @@ -18,7 +18,7 @@ use openbitfun_core::service::remote_connect::account_runtime::{ BackgroundRoutingOwnerRetirementError, }; use openbitfun_core::service::remote_connect::{ - self, encryption, + self, device, encryption, relay_client::{ConnectionState, DeviceRoutingPriority, RelayClient, RelayEvent}, DeviceIdentity, RemoteServer, }; @@ -73,7 +73,12 @@ pub(crate) fn account_snapshot_projection( pub(crate) fn account_login_status_message( result: &openbitfun_core::service::remote_connect::account_runtime::AccountLoginResult, ) -> String { - if result.routing_standby { + if device::remote_control_allowed().ok() == Some(false) { + format!( + "Logged in as user {} on {}. Remote control is off.", + result.user_id, result.relay_url + ) + } else if result.routing_standby { format!( "Logged in as user {} on {}. Another OpenBitFun host on this machine serves device routing; this one takes over when it exits.", result.user_id, result.relay_url @@ -132,6 +137,7 @@ pub(crate) struct CliAccountRoutingHost { RwLock>>, self_ref: Weak, runtime: OnceLock>, + permission_monitor: OnceLock, relay_client: RwLock>>, /// Read leases cover one routing event through its response. Routing owner /// changes take the write lease, so old events cannot escape through a new @@ -140,12 +146,21 @@ pub(crate) struct CliAccountRoutingHost { routing_cancel: tokio::sync::watch::Sender, } +impl Drop for CliAccountRoutingHost { + fn drop(&mut self) { + if let Some(task) = self.permission_monitor.get() { + task.abort(); + } + } +} + impl CliAccountRoutingHost { fn new() -> Arc { Arc::new_cyclic(|self_ref| Self { self_ref: self_ref.clone(), host_stream_hub: RwLock::new(None), runtime: OnceLock::new(), + permission_monitor: OnceLock::new(), relay_client: RwLock::new(None), lifecycle: Arc::new(RwLock::new(())), routing_cancel: tokio::sync::watch::channel(0).0, @@ -172,12 +187,51 @@ impl CliAccountRoutingHost { .ok_or_else(|| anyhow!("account runtime is unavailable")) } + pub(crate) fn monitor_remote_control(&self) { + self.permission_monitor.get_or_init(|| { + let host = self.self_ref.clone(); + let mut allowed = device::remote_control_allowed().unwrap_or(false); + tokio::spawn(async move { + loop { + allowed = device::wait_for_remote_control_change(allowed).await; + let Some(host) = host.upgrade() else { return }; + let Ok(runtime) = host.runtime() else { return }; + if !allowed { + host.stop_routing().await; + } + if let Some(daemon) = crate::remote_control::daemon_host() { + if let Err(error) = daemon.apply_remote_control_permission(allowed).await { + tracing::warn!( + "Failed to apply daemon remote control setting: {error}" + ); + } + } else if allowed + && runtime.device_routing_requested(runtime.account_context_generation()) + { + if let Ok(info) = runtime.account_info().await { + if let Err(error) = + runtime.restore_device_routing(&info.device_name).await + { + tracing::warn!("Failed to resume device routing: {error}"); + } + } + } + } + }) + .abort_handle() + }); + } + async fn start_routing(&self, request: AccountRoutingStartRequest) -> Result<()> { + self.monitor_remote_control(); let runtime = self.runtime()?; if !runtime.device_routing_requested(request.account_generation) { return Err(anyhow!("account context changed")); } self.stop_routing().await; + if !device::remote_control_allowed()? { + return Ok(()); + } // A Desktop host on this machine serves the shared device first; this // client stands by and takes over once that host exits. @@ -199,6 +253,7 @@ impl CliAccountRoutingHost { client.disconnect().await; return Err(anyhow!("account context changed")); } + device::require_remote_control()?; *self.relay_client.write().await = Some(client.clone()); } if !runtime.device_routing_requested(request.account_generation) { @@ -360,6 +415,9 @@ impl CliAccountRoutingHost { cancellation: Some(cancelled.clone()), }; let device_rpc = matches!(&event, RelayEvent::DeviceMessageReceived { .. }); + if device_rpc && device::require_remote_control().is_err() { + return; + } let mut event_cancellation = cancelled.clone(); let handling = ACTIVE_PEER_FANOUT_OWNER.scope( fanout_owner, diff --git a/src/apps/cli/src/main.rs b/src/apps/cli/src/main.rs index d1bc4bdfab..bce44fdf92 100644 --- a/src/apps/cli/src/main.rs +++ b/src/apps/cli/src/main.rs @@ -759,6 +759,17 @@ enum DaemonAction { Uninstall, /// Show daemon and auto-start service status Status, + /// Show or change whether this device accepts remote control (shared with Desktop) + RemoteControl { + #[arg(value_enum)] + setting: Option, + }, +} + +#[derive(Clone, Copy, ValueEnum)] +enum RemoteControlSetting { + On, + Off, } #[derive(Subcommand)] @@ -1597,6 +1608,23 @@ async fn run_cli() -> Result<()> { DaemonAction::Install => daemon::install_service()?, DaemonAction::Uninstall => daemon::uninstall_service()?, DaemonAction::Status => daemon::print_status()?, + DaemonAction::RemoteControl { setting } => { + use openbitfun_core::service::remote_connect::device; + if let Some(setting) = setting { + device::set_remote_control_allowed(matches!( + setting, + RemoteControlSetting::On + ))?; + } + println!( + "{}", + if device::remote_control_allowed()? { + "on" + } else { + "off" + } + ); + } }, Some(Commands::Dispatch { action }) => { diff --git a/src/apps/cli/src/remote_control.rs b/src/apps/cli/src/remote_control.rs index 7238700e46..c3fd6dff94 100644 --- a/src/apps/cli/src/remote_control.rs +++ b/src/apps/cli/src/remote_control.rs @@ -12,6 +12,7 @@ use openbitfun_core::agentic::tools::openbitfun_control_host::set_openbitfun_con use openbitfun_core::service::remote_connect::{ bot, control::{RemoteBotControl, RemoteConnectServiceHolder}, + device, embedded_relay_host::EmbeddedRelayHost, relay_client::ConnectionState, AccountClient, DeviceIdentity, QrGenerator, RemoteConnectConfig, RemoteConnectService, @@ -76,6 +77,7 @@ pub(crate) async fn activate_daemon( )) } }); + runtime.account_routing().monitor_remote_control(); let info = runtime.account_runtime().account_info().await?; if let Err(error) = host.bots.restore(&info.user_id).await { tracing::warn!("Daemon bot restore is unavailable: {error}"); @@ -122,13 +124,24 @@ impl CliRemoteControlHost { .ok_or_else(|| anyhow!("CLI runtime is shutting down")) } + pub(crate) async fn apply_remote_control_permission(&self, allowed: bool) -> Result<()> { + if allowed { + let account = self.runtime()?.account_runtime().account_info().await?; + self.bots.restore(&account.user_id).await?; + self.reconcile_relay().await?; + } else if let Some(service) = self.service.read().await.as_ref() { + service.stop_bots().await; + } + Ok(()) + } + pub(crate) async fn reconcile_relay(&self) -> Result<()> { let _operation = self.relay_operation.lock().await; self.connect_relay_if_enabled().await } async fn connect_relay_if_enabled(&self) -> Result<()> { - if !self.relay_enabled.load(Ordering::Acquire) { + if !self.relay_enabled.load(Ordering::Acquire) || !device::remote_control_allowed()? { return Ok(()); } let runtime = self.runtime()?; @@ -170,7 +183,7 @@ impl CliRemoteControlHost { result["daemonRunning"] = json!(true); result["host"] = json!({"kind":"cli", "deviceId":info.device_id, "deviceName":info.device_name}); result["mobileWeb"] = json!({ - "method":"mobile_web", "enabled":self.relay_enabled.load(Ordering::Acquire), + "method":"mobile_web", "enabled":self.relay_enabled.load(Ordering::Acquire) && device::remote_control_allowed()?, "routingState": format!("{:?}", runtime.account_routing().connection_state().await).to_ascii_lowercase(), "relayUrl":info.relay_url, "lastError":self.relay_error.read().await.clone(), }); @@ -178,6 +191,7 @@ impl CliRemoteControlHost { Ok(result) } RemoteControlRequest::Start { method: RemoteControlMethod::MobileWeb, .. } => { + device::require_remote_control()?; let _operation = self.relay_operation.lock().await; self.relay_enabled.store(true, Ordering::Release); self.connect_relay_if_enabled().await?; diff --git a/src/apps/desktop/src/api/remote_connect_api.rs b/src/apps/desktop/src/api/remote_connect_api.rs index 35d8f86f66..1a4c94354c 100644 --- a/src/apps/desktop/src/api/remote_connect_api.rs +++ b/src/apps/desktop/src/api/remote_connect_api.rs @@ -10,7 +10,7 @@ use openbitfun_core::service::remote_connect::session_store::{ }; use openbitfun_core::service::remote_connect::{ bot::{self, weixin, BotConfig}, - lan, session_store, AccountClient, AccountSession, ConnectionMethod, ConnectionResult, + device, lan, session_store, AccountClient, AccountSession, ConnectionMethod, ConnectionResult, DeviceIdentity, RemoteConnectConfig, RemoteConnectService, }; use openbitfun_events::AI_MODEL_CATALOG_UPDATED_EVENT; @@ -263,8 +263,8 @@ fn tag_peer_event_source(payload: serde_json::Value, source_device_id: &str) -> } } -fn emit_device_presence(devices: &[OnlineDeviceInfo]) { - let payload = serde_json::json!({ "devices": devices }); +fn emit_device_presence(devices: &[OnlineDeviceInfo], controller_only: bool) { + let payload = serde_json::json!({ "devices": devices, "controllerOnly": controller_only }); emit_account_event("account://device-presence", payload); } @@ -274,7 +274,7 @@ fn emit_device_presence(devices: &[OnlineDeviceInfo]) { async fn disconnect_route_controllers(route: RelayRoute, reason: &'static str) { clear_route_delivery_targets(route, reason); if route == RelayRoute::Official { - emit_device_presence(&[]); + emit_device_presence(&[], false); } } @@ -1445,8 +1445,33 @@ async fn maintain_device_session() -> anyhow::Result { Ok(true) } +fn monitor_remote_control_permission() { + let mut allowed = device::remote_control_allowed().unwrap_or(false); + tokio::spawn(async move { + loop { + allowed = device::wait_for_remote_control_change(allowed).await; + if allowed { + restore_saved_bots().await; + } else { + if let Err(error) = remote_connect_stop(None).await { + log::warn!("Failed to stop remote control: {error}"); + } + if let Some(service) = get_service_holder().read().await.as_ref() { + service.stop_bots().await; + } + } + if read_account_context().await.is_ok() { + if let Err(error) = account_connect_devices_with_retry().await { + log::warn!("Failed to update account connection after remote control setting changed: {error}"); + } + } + } + }); +} + pub fn init_on_startup() { register_page_tool_hosts(); + monitor_remote_control_permission(); tokio::spawn(async { let startup_generation = account_context_generation(); let error = session_store::renew_session_if_due(false).await.err(); @@ -1732,6 +1757,12 @@ pub struct RemoteConnectStatusResponse { pub clients: Vec, pub bot_connected: Option, pub bot_verbose_mode: bool, + #[serde(default = "default_remote_control_allowed")] + pub remote_control_allowed: bool, +} + +fn default_remote_control_allowed() -> bool { + true } #[derive(Debug, Serialize)] @@ -2076,6 +2107,7 @@ pub async fn remote_connect_start( ensure_service().await?; let method = parse_connection_method(&request.method, request.lan_ip)?; let _start_stop = RELAY_START_STOP_LOCK.lock().await; + device::require_remote_control().map_err(|e| e.to_string())?; if matches!( method, ConnectionMethod::BotFeishu | ConnectionMethod::BotTelegram | ConnectionMethod::BotWeixin @@ -2236,9 +2268,20 @@ pub async fn remote_connect_status() -> Result Result<(), String> { + device::set_remote_control_allowed(request.allowed).map_err(|e| e.to_string()) +} + #[tauri::command] pub async fn remote_connect_get_form_state() -> Result { Ok(bot::load_bot_persistence().form_state) @@ -2667,6 +2710,10 @@ async fn connect_route_devices_for_generation( account_generation: u64, ) -> Result, String> { let operation_guard = route.lock_operation(account_generation).await?; + let serves_device = device::remote_control_allowed().map_err(|e| e.to_string())?; + if !serves_device && route == RelayRoute::Lan { + return Err("Remote control is disabled on this device".into()); + } if route == RelayRoute::Official && !ROUTING_INTENT.requested(account_generation) { return Err("device routing stopped".to_string()); } @@ -2684,11 +2731,14 @@ async fn connect_route_devices_for_generation( if let Some(devices) = device_presence_for_account_on_route(route, account_generation, &session.token) { - let is_connected = service.is_device_connected().await; + let connected_role = service.account_socket_serves_device().await; if !route.matches(account_generation, &session.token).await { return Err("account context changed".to_string()); } - if is_connected { + if connected_role == Some(serves_device) { + if !serves_device { + return Ok(devices); + } let local_id = DeviceIdentity::from_current_machine() .ok() .map(|d| d.device_id); @@ -2719,7 +2769,7 @@ async fn connect_route_devices_for_generation( &session, &device_name, // Desktop serves the device ahead of a CLI/daemon on this machine. - openbitfun_core::service::remote_connect::relay_client::DeviceRoutingPriority::Primary, + serves_device.then_some(openbitfun_core::service::remote_connect::relay_client::DeviceRoutingPriority::Primary), Arc::new(DesktopHostStreamNotifier(route)), ) .await @@ -2731,7 +2781,7 @@ async fn connect_route_devices_for_generation( // The reconnect kept the previous roster; without a connection it // no longer describes reachable devices. if route == RelayRoute::Official { - emit_device_presence(&[]); + emit_device_presence(&[], false); } // Token invalidation re-enters the account transition path, so the // current account-operation lease must be released first. @@ -2837,7 +2887,7 @@ async fn connect_route_devices_for_generation( break 'routing_events; } if route == RelayRoute::Official { - emit_device_presence(&devices); + emit_device_presence(&devices, !serves_device); } } RelayEvent::DeviceMessageReceived { @@ -2881,10 +2931,22 @@ async fn connect_route_devices_for_generation( // webview only sees the records they read back. continue; } - emit_account_event( - &event, - tag_peer_event_source(payload, &source_device_id), - ); + if should_fanout_peer_ui_event(&event) + || event == "account://settings-applied" + || (serves_device + && device::remote_control_allowed().unwrap_or(false)) + { + emit_account_event( + &event, + tag_peer_event_source(payload, &source_device_id), + ); + } + } + Ok(_) + if !serves_device + || device::require_remote_control().is_err() => + { + continue } Ok(RemoteCommand::ExecuteOnDevice { session_id, @@ -3126,7 +3188,7 @@ async fn connect_route_devices_for_generation( break 'routing_events; } if route == RelayRoute::Official { - emit_device_presence(&[]); + emit_device_presence(&[], false); } } RelayEvent::Reconnected => { @@ -3194,6 +3256,40 @@ pub async fn account_execute_on_device( let (session, relay_url) = read_account_context_for_generation(account_generation).await?; use openbitfun_core::service::remote_connect::remote_server::RemoteCommand; + if !device::remote_control_allowed().map_err(|e| e.to_string())? { + // User-scoped sockets can call peer commands, but only a machine host + // can send the legacy one-way ExecuteOnDevice event. + use openbitfun_core::service::remote_connect::remote_server::RemoteResponse; + let request = RemoteCommand::HostInvoke { + command: "start_dialog_turn".into(), + args: serde_json::json!({ "request": { + "sessionId": session_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()), + "turnId": uuid::Uuid::new_v4().to_string(), + "userInput": content, + "agentType": agent_type.unwrap_or_else(|| "Standard".into()), + "workspacePath": workspace_path, + }}), + }; + let command_json = serde_json::to_string(&request).map_err(|e| e.to_string())?; + let response = AccountClient::new() + .device_rpc(&relay_url, &session, &target_device_id, &command_json) + .await + .map_err(|e| e.to_string())?; + if !account_context_matches(account_generation, &session.token).await { + return Err("account context changed".into()); + } + return match serde_json::from_str(&response) + .map_err(|e| format!("Invalid peer reply: {e}"))? + { + RemoteResponse::HostInvokeResult { ok: true, .. } => Ok(()), + RemoteResponse::HostInvokeResult { + error: Some(message), + .. + } + | RemoteResponse::Error { message } => Err(message), + _ => Err("The peer did not acknowledge the remote turn".into()), + }; + } let envelope = serde_json::to_string(&RemoteCommand::ExecuteOnDevice { session_id, content, diff --git a/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs b/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs index 5a67ad257e..ab8002c5eb 100644 --- a/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs +++ b/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs @@ -428,6 +428,8 @@ async fn dual_relay_rpc_persistence_and_teardown_are_independent() { "pong" ); + verify_remote_control_permission(&official, &official_session, &official_controller, &id).await; + // Full sign-out is the shared identity boundary and retires both routes. let replacement_lan = lan.credential(&id, [2; 32]).await; RelayRoute::Lan @@ -468,6 +470,132 @@ async fn dual_relay_rpc_persistence_and_teardown_are_independent() { official.stop().await; } +/// Use independent encrypted sockets on the fixture Relay. An offline host +/// remains an authenticated controller, including after a directory refresh. +async fn verify_remote_control_permission( + relay: &FixtureHost, + session: &AccountSession, + peer: &AccountSession, + id: &str, +) { + use openbitfun_core::service::remote_connect::relay_client::{RelayClient, RelayEvent}; + monitor_remote_control_permission(); + remote_connect_set_allowed(SetRemoteControlRequest { allowed: false }) + .await + .unwrap(); + let client = AccountClient::new(); + let url = relay.url(); + tokio::time::timeout(std::time::Duration::from_secs(8), async { + loop { + if client + .list_devices(&url, peer) + .await + .unwrap() + .iter() + .any(|row| row.device_id == id && !row.online) + && RelayRoute::Official + .service() + .read() + .await + .as_ref() + .unwrap() + .account_socket_serves_device() + .await + == Some(false) + { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .expect("host should become controller-only"); + account_connect_devices().await.unwrap(); + assert!(client + .device_rpc(&url, peer, id, r#"{"cmd":"ping"}"#) + .await + .is_err()); + let (target, mut events) = RelayClient::new(); + target.connect(&url).await.unwrap(); + target + .connect_authenticated(&peer.token, "peer") + .await + .unwrap(); + let answer = async { + while let Some(event) = events.recv().await { + if let RelayEvent::DeviceMessageReceived { + source_device_id, + correlation_id, + encrypted_data, + nonce, + encoding_offer, + } = event + { + if correlation_id.is_empty() { + continue; + } + assert_eq!(source_device_id, id); + let request = peer + .decrypt_peer_message(&url, id, &encrypted_data, &nonce, encoding_offer) + .await + .unwrap(); + assert_eq!(request, r#"{"cmd":"ping"}"#); + let (data, nonce) = peer + .encrypt_reply(&url, id, r#"{"resp":"pong"}"#, false) + .await + .unwrap(); + target + .send_device_message(id, &correlation_id, &data, &nonce) + .await + .unwrap(); + return; + } + } + panic!("peer disconnected before the outbound request"); + }; + let outbound = account_device_rpc("controller".into(), r#"{"cmd":"ping"}"#.into(), Some(5000)); + let (result, ()) = tokio::time::timeout(std::time::Duration::from_secs(8), async { + tokio::join!(outbound, answer) + }) + .await + .unwrap(); + assert_eq!(result.unwrap(), r#"{"resp":"pong"}"#); + assert!(client + .list_devices(&url, peer) + .await + .unwrap() + .iter() + .any(|device| device.device_id == id && !device.online)); + assert_eq!( + session_store::load_session_detailed() + .unwrap() + .unwrap() + .token, + session.token + ); + remote_connect_set_allowed(SetRemoteControlRequest { allowed: true }) + .await + .unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(8), async { + while !client + .list_devices(&url, peer) + .await + .unwrap() + .iter() + .any(|row| row.device_id == id && row.online) + { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .unwrap(); + assert_eq!( + rpc(relay, peer, id, serde_json::json!({"cmd":"ping"})).await["resp"], + "pong" + ); + target.disconnect().await; +} + #[tokio::test] async fn html_preview_streams_assets_over_encrypted_peer_rpc() { peer_preview_fixture(false).await; diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index 0b62d85536..d9e0747a58 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -1862,6 +1862,7 @@ pub async fn run() { api::remote_connect_api::remote_connect_stop_bot, api::remote_connect_api::remote_connect_status, api::remote_connect_api::remote_connect_get_form_state, + api::remote_connect_api::remote_connect_set_allowed, api::remote_connect_api::remote_connect_set_form_state, api::remote_connect_api::remote_connect_configure_bot, api::remote_connect_api::remote_connect_weixin_qr_start, diff --git a/src/crates/assembly/core/src/service/remote_connect/account_runtime.rs b/src/crates/assembly/core/src/service/remote_connect/account_runtime.rs index f4f7306491..1e5f268111 100644 --- a/src/crates/assembly/core/src/service/remote_connect/account_runtime.rs +++ b/src/crates/assembly/core/src/service/remote_connect/account_runtime.rs @@ -531,7 +531,9 @@ impl AccountRuntime { user_id, relay_url, routing_owner_replaced: retired_background_owner, - routing_connected: routing.is_ok() && !routing_standby, + routing_connected: routing.is_ok() + && !routing_standby + && self.host.device_routing_is_active().await, routing_standby, routing_error: routing.err().map(|error| error.to_string()), }) diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs index 1f736ca4f5..90cee99306 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs @@ -634,6 +634,9 @@ pub async fn bootstrap_im_chat_after_pairing(state: &mut BotChatState) -> String /// Mark chat paired, run assistant/session bootstrap, return main menu. pub async fn complete_im_bot_pairing(state: &mut BotChatState) -> HandleResult { + if let Err(error) = super::super::device::require_remote_control() { + return result_from_menu(state, MenuView::plain(error.to_string())); + } state.paired = true; let language = current_bot_language().await; let s = strings_for(language); @@ -817,6 +820,9 @@ pub async fn handle_command( cmd: BotCommand, images: Vec, ) -> HandleResult { + if let Err(error) = super::super::device::require_remote_control() { + return result_from_menu(state, MenuView::plain(error.to_string())); + } if state.active_remote_device.is_none() && !state.account_remote_context && state.current_workspace.as_ref().is_some_and(|workspace| { diff --git a/src/crates/assembly/core/src/service/remote_connect/control.rs b/src/crates/assembly/core/src/service/remote_connect/control.rs index 97786b299a..0c7e90126e 100644 --- a/src/crates/assembly/core/src/service/remote_connect/control.rs +++ b/src/crates/assembly/core/src/service/remote_connect/control.rs @@ -57,6 +57,9 @@ impl RemoteBotControl { .as_ref() .ok_or_else(|| anyhow!("Remote Connect host is unavailable"))?; service.set_bot_account(Some(user_id.into())).await; + if !super::device::remote_control_allowed()? { + return Ok(()); + } for saved in &data.connections { if !restore_eligible(&data, saved, user_id) { continue; @@ -353,6 +356,7 @@ impl RemoteBotControl { } pub async fn weixin_login_start(&self) -> Result { + super::device::require_remote_control()?; let account = self.account_scope().await?; let generation = self.login_generation.fetch_add(1, Ordering::AcqRel) + 1; let data = bot::try_load_bot_persistence()?; diff --git a/src/crates/assembly/core/src/service/remote_connect/mod.rs b/src/crates/assembly/core/src/service/remote_connect/mod.rs index 6224467067..45799b67eb 100644 --- a/src/crates/assembly/core/src/service/remote_connect/mod.rs +++ b/src/crates/assembly/core/src/service/remote_connect/mod.rs @@ -307,6 +307,7 @@ impl RemoteConnectService { /// asking for its invitation again never drops a connection. pub async fn prepare_relay(&self, method: &ConnectionMethod) -> Result { let _lifecycle = self.relay_lifecycle.lock().await; + device::require_remote_control()?; if self.active_method.read().await.as_ref() == Some(method) { if let Some(url) = self.prepared_relay_url.read().await.clone() { return Ok(url); @@ -360,6 +361,7 @@ impl RemoteConnectService { return self.start_bot_connection(&method).await; } let _lifecycle = self.device_relay_lifecycle.lock().await; + device::require_remote_control()?; let device_id = self .authenticated_device_id .read() @@ -407,6 +409,7 @@ impl RemoteConnectService { async fn start_bot_connection(&self, method: &ConnectionMethod) -> Result { let _lifecycle = self.bot_lifecycle.lock().await; + device::require_remote_control()?; let account_user_id = self .bot_account_user_id .read() @@ -681,6 +684,7 @@ impl RemoteConnectService { /// Skips the pairing step and directly starts the message loop. pub async fn restore_bot(&self, saved: &bot::SavedBotConnection) -> Result<()> { let _lifecycle = self.bot_lifecycle.lock().await; + device::require_remote_control()?; let account_user_id = self .bot_account_user_id .read() @@ -1063,14 +1067,18 @@ impl RemoteConnectService { /// active (i.e. `start_device_connection` has been called and not yet /// disconnected). pub async fn is_device_connected(&self) -> bool { - let client = self.device_relay_client.read().await.clone(); - let Some(client) = client else { - return false; - }; + self.account_socket_serves_device().await == Some(true) + } + + /// A controller-only connection receives account presence and peer events + /// without advertising a routable machine on the Relay. + pub async fn account_socket_serves_device(&self) -> Option { + let client = self.device_relay_client.read().await.clone()?; matches!( client.connection_state().await, relay_client::ConnectionState::Connected | relay_client::ConnectionState::Reconnecting ) + .then(|| client.serves_device()) } pub async fn device_relay_url(&self) -> Option { @@ -1086,14 +1094,14 @@ impl RemoteConnectService { /// /// `notifier` delivers host stream hints to subscribed controllers; the host /// adapter owns pairwise encryption and the routing lease, so it supplies it. - /// `priority` decides which host serves this device when several OpenBitFun - /// hosts on the machine share its identity. + /// A host priority registers a machine socket and arbitrates local hosts. + /// With no priority, the endpoint only receives controller events. pub async fn start_device_connection( &self, relay_url: &str, session: &AccountSession, device_name: &str, - priority: relay_client::DeviceRoutingPriority, + host_priority: Option, notifier: Arc, ) -> Result<( tokio::sync::mpsc::Receiver, @@ -1104,7 +1112,10 @@ impl RemoteConnectService { // Disconnect previous device connection if any. self.stop_device_connection_inner().await; - let (client, mut event_rx) = RelayClient::new_device_host(priority); + let (client, mut event_rx) = match host_priority { + Some(priority) => RelayClient::new_device_host(priority), + None => RelayClient::new_controller(), + }; let client = client.with_account_session(session); client.connect(relay_url).await?; client @@ -1130,9 +1141,11 @@ impl RemoteConnectService { if let Err(e) = DeviceIdentity::adopt_account_device_id(&device_id) { log::warn!("Failed to adopt AuthOk device_id: {e}"); } - let hub = start_host_stream_hub(notifier.clone()); - if let Some(previous) = self.host_stream_hub.write().await.replace(hub) { - previous.close(); + if host_priority.is_some() { + let hub = start_host_stream_hub(notifier.clone()); + if let Some(previous) = self.host_stream_hub.write().await.replace(hub) { + previous.close(); + } } authenticated_device_id = Some(device_id); } diff --git a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json index 2cfcc7f07c..2cc33f7f08 100644 --- a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json +++ b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c", + "digest": "bec28fbd98726d074ccb1073068d0b9c147dddba552cbd46736305e58852b681", "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { @@ -187,11 +187,11 @@ "features": 24, "settings": 23, "userFacing": 47, - "documentedItems": 368, + "documentedItems": 369, "controlCoverage": { "direct": 64, "delegated": 74, - "interactive": 230, + "interactive": 231, "unsupported": 0 } }, @@ -9558,6 +9558,7 @@ "id": "feature.remote-connect:query", "capabilityId": "feature.remote-connect", "itemIds": [ + "device-control-permission", "connection-methods", "start-stop-status", "network", @@ -10012,6 +10013,52 @@ "eventName": "openbitfun:open-remote-connect" } }, + { + "id": "feature.remote-connect:open:device-control-permission", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "device-control-permission" + ], + "kind": "open", + "risk": "ui", + "executionHost": "presentationSurface", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "product_control_presentation_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "openReason": "unstructuredInteraction", + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, { "id": "feature.remote-connect:open:connection-methods", "capabilityId": "feature.remote-connect", @@ -27689,6 +27736,17 @@ "Ask the agent directly to start/stop channels, launch WeChat QR login, or inspect listener health" ], "items": [ + { + "id": "device-control-permission", + "titleZh": "本机可被控制", + "titleEn": "Allow control of this device", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "请在当前设备的「设备与连接」概览中切换「本机可被控制」,选择其他设备能否连接这台设备。", + "reasonEn": "Choose “Allow control of this device” in the local Devices & Connections overview to set whether other devices can connect to this one." + } + }, { "id": "connection-methods", "titleZh": "使用免部署官方 Relay 或桌面端局域网 Relay(可同时开启)", @@ -28039,6 +28097,8 @@ "Pair a WeChat, Feishu, or Telegram bot to chat and approve permissions from your messenger", "Same-account Peer Device Mode: expand and operate another computer’s workspaces right in your sidebar", "Ask the agent directly to start/stop channels, launch WeChat QR login, or inspect listener health", + "本机可被控制", + "Allow control of this device", "使用免部署官方 Relay 或桌面端局域网 Relay(可同时开启)", "Use the zero-setup official Relay or Desktop LAN Relay concurrently", "一键启动、停用远控渠道并查看实时连接与设备信息", diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index b1e855fbb4..3dbfbd48e0 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:975d66aad34aa784", + "digest": "fnv1a64:c33c5af9950946e1", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -5865,6 +5865,18 @@ "reason": "the controller keeps this command; peer hosts refuse it before dispatch" } }, + { + "id": "remote_connect_set_allowed", + "surface": "tauri_command", + "remoteWorkspace": "WorkspaceAgnostic", + "peer": { + "kind": "controller_local" + }, + "cliPeer": { + "kind": "unsupported", + "reason": "the controller keeps this command; peer hosts refuse it before dispatch" + } + }, { "id": "remote_connect_set_bot_verbose_mode", "surface": "tauri_command", diff --git a/src/crates/contracts/product-domains/src/remote_surface/table.rs b/src/crates/contracts/product-domains/src/remote_surface/table.rs index 7db081dc4f..f086d37501 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -586,6 +586,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("remote_connect_get_lan_ip", Agnostic, ControllerLocal, REFUSED), op("remote_connect_get_lan_network_info", Agnostic, ControllerLocal, REFUSED), op("remote_connect_get_methods", Agnostic, ControllerLocal, REFUSED), + op("remote_connect_set_allowed", Agnostic, ControllerLocal, REFUSED), op("remote_connect_set_bot_verbose_mode", Agnostic, ControllerLocal, REFUSED), op("remote_connect_set_form_state", Agnostic, ControllerLocal, REFUSED), op("remote_connect_start", Agnostic, ControllerLocal, REFUSED), diff --git a/src/crates/services/services-integrations/src/remote_connect/device.rs b/src/crates/services/services-integrations/src/remote_connect/device.rs index dc901e393f..174cd38aa9 100644 --- a/src/crates/services/services-integrations/src/remote_connect/device.rs +++ b/src/crates/services/services-integrations/src/remote_connect/device.rs @@ -241,6 +241,58 @@ fn load_persisted() -> Result> { .map_err(|error| error.context(path.display().to_string())) } +/// Device-scoped, shared by Desktop and the CLI daemon. An old installation +/// has no opt-out marker. Reading a marker never rewrites the device identity. +fn remote_control_marker() -> Result { + Ok(identity_file_path()?.with_extension("remote-control-disabled")) +} + +pub fn remote_control_allowed() -> Result { + Ok(!remote_control_marker()? + .try_exists() + .context("read device remote control setting")?) +} + +pub fn require_remote_control() -> Result<()> { + anyhow::ensure!( + remote_control_allowed()?, + "Remote control is disabled on this device" + ); + Ok(()) +} + +pub fn set_remote_control_allowed(allowed: bool) -> Result<()> { + let path = remote_control_marker()?; + if allowed { + match std::fs::remove_file(path) { + Ok(()) => {} + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(err) => return Err(err).context("enable device remote control"), + } + } else { + crate::remote_persistence::write_private_bytes(&path, b"")?; + } + REMOTE_CONTROL_CHANGED.notify_waiters(); + Ok(()) +} + +static REMOTE_CONTROL_CHANGED: tokio::sync::Notify = tokio::sync::Notify::const_new(); + +/// Local writes wake listeners immediately. Other hosts share the same file. +pub async fn wait_for_remote_control_change(previous: bool) -> bool { + loop { + let notified = REMOTE_CONTROL_CHANGED.notified(); + let allowed = remote_control_allowed().unwrap_or(false); + if allowed != previous { + return allowed; + } + tokio::select! { + _ = notified => {}, + _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {}, + } + } +} + fn save_persisted(identity: &DeviceIdentity) -> Result<()> { let path = identity_file_path()?; crate::remote_persistence::write_device_identity(&path, identity) @@ -304,6 +356,25 @@ mod tests { format!("{nanos:x}") } + #[test] + fn legacy_device_allows_remote_control_and_keeps_its_identity_across_toggles() { + with_temp_identity_path(|| { + let path = identity_file_path().unwrap(); + let legacy = br#"{"device_id":"0123456789abcdef0123456789abcdef","device_name":"host","mac_address":"aa:bb:cc:dd:ee:ff"}"#; + std::fs::write(&path, legacy).unwrap(); + assert!(require_remote_control().is_ok()); + for _ in 0..2 { + set_remote_control_allowed(false).unwrap(); + assert!(require_remote_control().is_err()); + } + for _ in 0..2 { + set_remote_control_allowed(true).unwrap(); + assert!(require_remote_control().is_ok()); + } + assert_eq!(std::fs::read(path).unwrap(), legacy); + }); + } + #[test] fn metadata_filters_each_field_independently_by_bytes_and_controls() { assert_eq!(metadata_value(&"a".repeat(256)), Some("a".repeat(256))); diff --git a/src/crates/services/services-integrations/src/remote_connect/relay_client.rs b/src/crates/services/services-integrations/src/remote_connect/relay_client.rs index b5cc338db5..0eafc2e211 100644 --- a/src/crates/services/services-integrations/src/remote_connect/relay_client.rs +++ b/src/crates/services/services-integrations/src/remote_connect/relay_client.rs @@ -237,6 +237,9 @@ impl RelayClient { } } } + pub fn serves_device(&self) -> bool { + self.machine + } pub async fn connection_state(&self) -> ConnectionState { self.owner.lock().unwrap().state.clone() } diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index a584b23811..68757ca790 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -6113,6 +6113,20 @@ "Ask the agent directly to start/stop channels, launch WeChat QR login, or inspect listener health" ], "items": [ + { + "id": "device-control-permission", + "titleZh": "本机可被控制", + "titleEn": "Allow control of this device", + "descriptionZh": "在设备与连接的概览中切换。关闭后,本机显示为离线,仍可控制其他在线设备。", + "descriptionEn": "Switch this in the Devices & Connections overview. When off, this device appears offline and can still control other online devices.", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "请在当前设备的「设备与连接」概览中切换「本机可被控制」,选择其他设备能否连接这台设备。", + "reasonEn": "Choose “Allow control of this device” in the local Devices & Connections overview to set whether other devices can connect to this one." + }, + "evidence": ["command:remote_connect_set_allowed"] + }, { "id": "connection-methods", "titleZh": "使用免部署官方 Relay 或桌面端局域网 Relay(可同时开启)", diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.contract.test.ts b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.contract.test.ts index 8f878b3f61..9ba17e3083 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.contract.test.ts +++ b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.contract.test.ts @@ -74,6 +74,11 @@ describe('Remote Connect safety contracts', () => { ); expect(overview).toContain('remote-connect-my-devices-title'); + const localSwitch = overview.slice(0, overview.indexOf('{accountLoggedIn && void setRemoteControlAllowed(allowed)}'); expect(overview).toContain('remote-connect-access-title'); expect(overview.match(/renderOverviewAction\(\{/g)).toHaveLength(3); expect(overview).toContain("view: 'account'"); diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx index d1e0a41aa0..788c3e1c42 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx +++ b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx @@ -194,6 +194,7 @@ export const RemoteConnectDialog: React.FC = ({ const [selectedLanIp, setSelectedLanIp] = useState(''); const [showDisclaimer, setShowDisclaimer] = useState(false); const [hasAgreedDisclaimer, setHasAgreedDisclaimer] = useState(() => getRemoteConnectDisclaimerAgreed()); + const [savingControlPermission, setSavingControlPermission] = useState(false); const [botVerboseMode, setBotVerboseMode] = useState(false); const [qrCopied, setQrCopied] = useState(false); @@ -1338,6 +1339,19 @@ export const RemoteConnectDialog: React.FC = ({ ); + const setRemoteControlAllowed = async (allowed: boolean) => { + setSavingControlPermission(true); + try { + await remoteConnectAPI.setRemoteControlAllowed(allowed); + remoteConnectStatusSource.invalidateReads(); + await remoteConnectStatusSource.refresh(); + } catch (cause) { + notifyError(String(cause), { title: t('remoteConnect.controlSettingFailed') }); + } finally { + setSavingControlPermission(false); + } + }; + const renderOverview = () => ( = ({ +
+
+ + {t('remoteConnect.controlAllowed')} + + + {t('remoteConnect.controlAllowedDescription')} + +
+ {status?.remote_control_allowed === undefined ? ( + {t(statusState === 'loading' ? 'remoteConnect.statusChecking' : 'remoteConnect.statusUnavailable')} + ) : ( + void setRemoteControlAllowed(allowed)} + /> + )} +
+ {accountLoggedIn &&
= ({ > + ) : status?.remote_control_allowed === false ? ( + renderNotice(t('remoteConnect.controlDisabledNotice')) ) : activeView === 'network' ? ( = new Set([ "remote_connect_get_lan_ip", "remote_connect_get_lan_network_info", "remote_connect_get_methods", + "remote_connect_set_allowed", "remote_connect_set_bot_verbose_mode", "remote_connect_set_form_state", "remote_connect_start", diff --git a/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts index b5a132599e..53fbab40d3 100644 --- a/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts @@ -105,6 +105,7 @@ export interface ConnectionResult { } export interface RemoteConnectStatus { + remote_control_allowed?: boolean; /** Present only when the host supports independently managed Relay routes. */ connections?: Array<{ method: 'lan' | 'openbitfun_server'; @@ -260,6 +261,10 @@ class RemoteConnectAPIService { } } + async setRemoteControlAllowed(allowed: boolean): Promise { + await this.adapter.request('remote_connect_set_allowed', { request: { allowed } }); + } + async getFormState(): Promise { try { return await this.adapter.request('remote_connect_get_form_state'); diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts index 32e7a15a51..8c25eca291 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts @@ -496,6 +496,16 @@ describe('PeerConnectionManager host readiness and attachment status', () => { expect(manager.get('peer-1')?.getState().health).toBe('ready'); }); + it('restores a controller-only attachment after a legacy host publishes its roster', async () => { + const rpc = pingRpc(() => ({ host_type: 'cli', capabilities: {} })); + const manager = createManager(rpc.deviceRpc); + await manager.connect('peer-1', 'Studio'); + manager.reportPresence(['peer-1'], true); + await vi.advanceTimersByTimeAsync(0); + expect(rpc.commands.filter(call => call.command === 'peer_control_attach')).toHaveLength(2); + expect(manager.list()[0].health).toBe('ready'); + }); + it('ignores caller_attached from a host that does not advertise the capability', async () => { const rpc = pingRpc(() => ({ host_type: 'cli', capabilities: {}, caller_attached: false })); const manager = createManager(rpc.deviceRpc); diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index a274df474f..738fab679c 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -507,13 +507,17 @@ export class PeerConnectionManager { * omit an otherwise running host. Retain the attachment and verify it with * a handshake. Repeated roster updates must not postpone an existing retry. */ - reportPresence(onlineDeviceIds: Iterable): void { + reportPresence(onlineDeviceIds: Iterable, controllerOnly = false): void { const online = new Set(onlineDeviceIds); for (const entry of this.entries.values()) { const wasOnline = entry.presenceOnline; entry.presenceOnline = online.has(entry.deviceId); if (!entry.presenceOnline && wasOnline !== false) { this.requestRecovery(entry, 'presence'); + } else if (controllerOnly && entry.presenceOnline && entry.health === 'ready') { + // Hosts may prune an invisible controller when their roster changes. + // Verify the attachment while the peer remains reachable. + void this.runHealthCheck(entry, true); } else if (entry.presenceOnline && wasOnline === false && (entry.health === 'degraded' || entry.probeRequested)) { this.cancelTimer(entry); void this.runHealthCheck(entry); @@ -917,7 +921,7 @@ export class PeerConnectionManager { * `peer_control_attach` because the host may have pruned this controller * during the gap that made us degraded in the first place. */ - private runHealthCheck(entry: ConnectionEntry): Promise { + private runHealthCheck(entry: ConnectionEntry, verifyHiddenAttachment = false): Promise { if (this.entries.get(entry.deviceId) !== entry || entry.disposed) { return Promise.resolve(); } @@ -925,7 +929,7 @@ export class PeerConnectionManager { return entry.healthCheckInFlight; } this.cancelTimer(entry); - const check = this.checkHealth(entry).finally(() => { + const check = this.checkHealth(entry, verifyHiddenAttachment).finally(() => { if (entry.healthCheckInFlight !== check) return; entry.healthCheckInFlight = null; entry.probeRequested = false; @@ -938,13 +942,14 @@ export class PeerConnectionManager { return check; } - private async checkHealth(entry: ConnectionEntry): Promise { + private async checkHealth(entry: ConnectionEntry, verifyHiddenAttachment: boolean): Promise { try { const { capabilities, status } = await this.probeCapabilities(entry); // The host may have dropped this controller (presence loss, routing // restart) while every request still succeeded; re-attach instead of // reporting `ready` for a link that receives no events. - const lostAttachment = status.callerAttached === false; + const lostAttachment = status.callerAttached === false + || (verifyHiddenAttachment && status.callerAttached === null); if (lostAttachment) { log.info('Peer host no longer has this controller attached; re-attaching', { deviceId: entry.deviceId, diff --git a/src/web-ui/src/infrastructure/peer-device/PeerDeviceSurfaceController.ts b/src/web-ui/src/infrastructure/peer-device/PeerDeviceSurfaceController.ts index 6547199c9b..62ec821147 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerDeviceSurfaceController.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerDeviceSurfaceController.ts @@ -61,7 +61,7 @@ export interface PeerConnectionManagerPort { list(): readonly PeerConnectionState[]; subscribe(listener: (connections: readonly PeerConnectionState[]) => void): () => void; dispose(deviceId: string, options?: { notifyPeer?: boolean }): Promise; - reportPresence(onlineDeviceIds: Iterable): void; + reportPresence(onlineDeviceIds: Iterable, controllerOnly?: boolean): void; } export interface PeerDeviceSurfaceControllerDependencies { @@ -87,7 +87,7 @@ export interface PeerDeviceSurfaceControllerDependencies { discardSurfaceState: (surfaceId: DeviceSurfaceId) => void; clearDeviceActivity: (deviceId: string) => void; listenPresence: ( - listener: (onlineDeviceIds: readonly string[]) => void, + listener: (onlineDeviceIds: readonly string[], controllerOnly?: boolean) => void, ) => () => void; listenLoginState: (listener: (loggedIn: boolean) => void) => () => void; } @@ -150,8 +150,8 @@ export class PeerDeviceSurfaceController { connections => this.handleConnectionStates(connections), ); this.controlPlaneUnsubscribes = [ - this.dependencies.listenPresence(onlineDeviceIds => { - this.dependencies.connectionManager.reportPresence(onlineDeviceIds); + this.dependencies.listenPresence((onlineDeviceIds, controllerOnly) => { + this.dependencies.connectionManager.reportPresence(onlineDeviceIds, controllerOnly); }), this.dependencies.listenLoginState(loggedIn => { if (!loggedIn && this.dependencies.connectionManager.list().length > 0) { diff --git a/src/web-ui/src/infrastructure/peer-device/peerDeviceSurfaceRuntime.ts b/src/web-ui/src/infrastructure/peer-device/peerDeviceSurfaceRuntime.ts index 0b2d8234f4..c170b5c8d3 100644 --- a/src/web-ui/src/infrastructure/peer-device/peerDeviceSurfaceRuntime.ts +++ b/src/web-ui/src/infrastructure/peer-device/peerDeviceSurfaceRuntime.ts @@ -180,8 +180,9 @@ function createDependencies(): PeerDeviceSurfaceControllerDependencies { clearDeviceActivity, listenPresence: listener => api.listen<{ devices: Array<{ device_id: string }>; + controllerOnly?: boolean; }>('account://device-presence', payload => { - listener((payload?.devices ?? []).map(device => device.device_id)); + listener((payload?.devices ?? []).map(device => device.device_id), payload?.controllerOnly); }), listenLoginState: listener => api.listen<{ logged_in: boolean }>( 'account://login-state', diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index b57216d702..21bf1fe29a 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -1243,6 +1243,10 @@ "pairedClient": "Paired connection", "clientDetailsUnavailable": "Connection details are currently unavailable.", "centerTitle": "Devices & Connections", + "controlAllowed": "Allow control of this device", + "controlAllowedDescription": "When off, this device appears offline. You can still control other online devices from here.", + "controlDisabledNotice": "To connect to this device, turn on “Allow control of this device” in Overview.", + "controlSettingFailed": "Could not update remote control for this device", "overviewIntro": "Manage your signed-in devices and connections from phones, browsers, and chat apps.", "myDevicesTitle": "My devices", "controlOtherDevicesTitle": "Control other devices", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index 896932c8a6..0b88c8187e 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -1243,6 +1243,10 @@ "pairedClient": "配对连接", "clientDetailsUnavailable": "暂时无法获取连接明细。", "centerTitle": "设备与连接", + "controlAllowed": "本机可被控制", + "controlAllowedDescription": "关闭后,本机在其他设备上显示为离线。你仍可从本机控制其他在线设备。", + "controlDisabledNotice": "要连接本机,请先在概览中开启「本机可被控制」。", + "controlSettingFailed": "更新本机远控设置失败", "overviewIntro": "管理已登录的设备,以及手机、浏览器和聊天应用的连接。", "myDevicesTitle": "我的设备", "controlOtherDevicesTitle": "控制其他设备", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index d5b1723632..6a8dfa18cf 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -1243,6 +1243,10 @@ "pairedClient": "配對連線", "clientDetailsUnavailable": "暫時無法取得連線明細。", "centerTitle": "裝置與連線", + "controlAllowed": "本機可被控制", + "controlAllowedDescription": "關閉後,本機會在其他裝置上顯示為離線。你仍可從本機控制其他在線裝置。", + "controlDisabledNotice": "若要連線到本機,請先在概覽中開啟「本機可被控制」。", + "controlSettingFailed": "無法更新本機遠端控制設定", "overviewIntro": "管理已登入的裝置,以及手機、瀏覽器和聊天應用程式的連線。", "myDevicesTitle": "我的裝置", "controlOtherDevicesTitle": "控制其他裝置", From 54c9ff6ebc860542f059d1b8f04e99c31fa42423 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 19 Nov 2026 13:29:05 +0800 Subject: [PATCH 2/2] fix(remote-connect): preserve offline pairing and peer state across changes --- src/apps/cli/src/remote_control.rs | 4 +-- .../desktop/src/api/remote_connect_api.rs | 14 +++------- .../remote_connect_api/relay_routes_tests.rs | 18 +++++++++++++ .../src/service/remote_connect/bot/weixin.rs | 9 +++++-- .../src/service/remote_connect/control.rs | 10 +++++++ .../RemoteConnectDialog.status.test.tsx | 27 +++++++++++++++++++ .../RemoteConnectDialog.tsx | 10 +++++-- .../peer-device/PeerConnectionManager.test.ts | 7 +++-- .../peer-device/PeerConnectionManager.ts | 14 ++++++---- .../locales/en-US/scenes/capabilities.json | 1 + .../locales/zh-CN/scenes/capabilities.json | 1 + .../locales/zh-TW/scenes/capabilities.json | 1 + 12 files changed, 93 insertions(+), 23 deletions(-) diff --git a/src/apps/cli/src/remote_control.rs b/src/apps/cli/src/remote_control.rs index c3fd6dff94..ecbc2b8371 100644 --- a/src/apps/cli/src/remote_control.rs +++ b/src/apps/cli/src/remote_control.rs @@ -129,8 +129,8 @@ impl CliRemoteControlHost { let account = self.runtime()?.account_runtime().account_info().await?; self.bots.restore(&account.user_id).await?; self.reconcile_relay().await?; - } else if let Some(service) = self.service.read().await.as_ref() { - service.stop_bots().await; + } else { + self.bots.suspend().await; } Ok(()) } diff --git a/src/apps/desktop/src/api/remote_connect_api.rs b/src/apps/desktop/src/api/remote_connect_api.rs index 1a4c94354c..80a142efef 100644 --- a/src/apps/desktop/src/api/remote_connect_api.rs +++ b/src/apps/desktop/src/api/remote_connect_api.rs @@ -1456,9 +1456,7 @@ fn monitor_remote_control_permission() { if let Err(error) = remote_connect_stop(None).await { log::warn!("Failed to stop remote control: {error}"); } - if let Some(service) = get_service_holder().read().await.as_ref() { - service.stop_bots().await; - } + bot_control().suspend().await; } if read_account_context().await.is_ok() { if let Err(error) = account_connect_devices_with_retry().await { @@ -1757,12 +1755,8 @@ pub struct RemoteConnectStatusResponse { pub clients: Vec, pub bot_connected: Option, pub bot_verbose_mode: bool, - #[serde(default = "default_remote_control_allowed")] - pub remote_control_allowed: bool, -} - -fn default_remote_control_allowed() -> bool { - true + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote_control_allowed: Option, } #[derive(Debug, Serialize)] @@ -2268,7 +2262,7 @@ pub async fn remote_connect_status() -> Result) -> Result { - weixin_provider::weixin_qr_start(base_url_override, None, None).await + weixin_qr_start_with_existing(base_url_override, None, None).await } pub async fn weixin_qr_start_with_existing( @@ -270,6 +270,7 @@ pub async fn weixin_qr_start_with_existing( existing_ilink_token: Option, existing_bot_account_id: Option, ) -> Result { + super::super::device::require_remote_control()?; weixin_provider::weixin_qr_start( base_url_override, existing_ilink_token, @@ -283,7 +284,11 @@ pub async fn weixin_qr_poll( base_url_override: Option, verify_code: Option, ) -> Result { - weixin_provider::weixin_qr_poll(session_key, base_url_override, verify_code).await + super::super::device::require_remote_control()?; + let response = + weixin_provider::weixin_qr_poll(session_key, base_url_override, verify_code).await?; + super::super::device::require_remote_control()?; + Ok(response) } impl WeixinBot { diff --git a/src/crates/assembly/core/src/service/remote_connect/control.rs b/src/crates/assembly/core/src/service/remote_connect/control.rs index 0c7e90126e..81699cd8ad 100644 --- a/src/crates/assembly/core/src/service/remote_connect/control.rs +++ b/src/crates/assembly/core/src/service/remote_connect/control.rs @@ -85,6 +85,14 @@ impl RemoteBotControl { Ok(()) } + /// Suspend inbound channels without changing which paired bots should resume. + pub async fn suspend(&self) { + self.login_generation.fetch_add(1, Ordering::AcqRel); + if let Some(service) = self.service.read().await.as_ref() { + service.stop_bots().await; + } + } + pub async fn status(&self) -> Result { let data = bot::try_load_bot_persistence()?; let holder = self.service.read().await; @@ -229,6 +237,7 @@ impl RemoteBotControl { } async fn start_locked(&self, bot_type: &str) -> Result { + super::device::require_remote_control()?; let scope = self.account_scope().await?; let data = bot::try_load_bot_persistence()?; { @@ -415,6 +424,7 @@ impl RemoteBotControl { // Stop/logout remains available, and the completion is checked again. let response = bot::weixin::weixin_qr_poll(session_key, None, verify_code).await?; let _mutation = self.mutation.lock().await; + super::device::require_remote_control()?; anyhow::ensure!( self.account_scope().await? == scope && self.login_generation.load(Ordering::Acquire) == generation, diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.status.test.tsx b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.status.test.tsx index e95e57dbb2..88d9f44bdf 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.status.test.tsx +++ b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.status.test.tsx @@ -18,6 +18,8 @@ const boundary = vi.hoisted(() => ({ startConnection: vi.fn(), stopConnection: vi.fn(), stopBot: vi.fn(), + weixinQrPoll: vi.fn(), + configureBot: vi.fn(), getFormState: vi.fn(), listeners: new Map void>>(), jobs: {}, @@ -33,6 +35,9 @@ vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', async importOrigina startConnection: boundary.startConnection, stopConnection: boundary.stopConnection, stopBot: boundary.stopBot, + weixinQrStart: vi.fn().mockResolvedValue({ session_key: 'scan-session', qr_image_url: 'qr.png' }), + weixinQrPoll: boundary.weixinQrPoll, + configureBot: boundary.configureBot, getFormState: boundary.getFormState, setFormState: vi.fn().mockResolvedValue(undefined), getLanNetworkInfo: vi.fn().mockResolvedValue({ local_ip: '192.168.1.2', available_ips: [{ ip: '192.168.1.2', interface_name: 'en0' }] }), @@ -279,6 +284,28 @@ describe('Remote Connect shared status through the real dialog and sidebar', () .toBe('remoteConnect.stateConnected'); }); + it('discards a pending WeChat scan when the CLI disables control and preserves saved bot preferences', async () => { + boundary.backend = status({ bot_connected: null, remote_control_allowed: true }); + const poll = deferred<{ status: string; ilink_token: string; bot_account_id: string }>(); + boundary.weixinQrPoll.mockReturnValueOnce(poll.promise); + await render('bot'); + await click(element('#remote-connect-bot-tab-weixin')); + await clickText('remoteConnect.botWeixinQrButton'); + expect(boundary.weixinQrPoll).toHaveBeenCalledTimes(1); + + boundary.backend = status({ bot_connected: null, remote_control_allowed: false }); + await tick(); + boundary.backend = status({ bot_connected: null, remote_control_allowed: true }); + await tick(); + await act(async () => { + poll.resolve({ status: 'confirmed', ilink_token: 'fixture', bot_account_id: 'fixture' }); + }); + expect(boundary.configureBot).not.toHaveBeenCalled(); + expect(boundary.startConnection).not.toHaveBeenCalled(); + expect(boundary.stopBot).not.toHaveBeenCalled(); + expect(dialog().textContent).toContain('remoteConnect.botWeixinQrButton'); + }); + it('explains the single chat-app connection and labels the detail switch', async () => { await render('bot'); await tick(); diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx index 788c3e1c42..3fa4148caa 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx +++ b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx @@ -246,7 +246,7 @@ export const RemoteConnectDialog: React.FC = ({ const connectedNetworkTab = anyNetworkConnection.method; const connectedBotTab = botInfoToBotTab(status?.bot_connected); - const cancelPendingWork = useCallback(async () => { + const cancelPendingWork = useCallback(async (hostAlreadyStopping = false) => { operationGenerationRef.current += 1; const currentStatus = remoteConnectStatusSource.getSnapshot().status; const candidateOwner = pendingOwnerRef.current ?? connectionOwnerRef.current; @@ -254,7 +254,7 @@ export const RemoteConnectDialog: React.FC = ({ ?? (connectionResultRef.current ? remoteNetworkMethod(connectionResultRef.current.method) : null); // Closing an invitation preserves an established account route. // Disconnect is an explicit action for both Relay endpoints. - const owner = (candidateOwner === 'network' && !pendingStartRef.current && selectRemoteNetworkConnection(currentStatus, connectionResultRef.current, ownedMethod ?? undefined).connected) + const owner = hostAlreadyStopping || (candidateOwner === 'network' && !pendingStartRef.current && selectRemoteNetworkConnection(currentStatus, connectionResultRef.current, ownedMethod ?? undefined).connected) || (candidateOwner === 'bot' && currentStatus?.bot_connected) ? null : candidateOwner; const pendingStart = pendingStartRef.current; @@ -331,6 +331,12 @@ export const RemoteConnectDialog: React.FC = ({ }; }, [cancelPendingWork, isOpen]); + // Disabling on the CLI can interrupt an invitation while its dialog is open. + // The host owns teardown here. An explicit stop would also disable saved bots. + useEffect(() => { + if (status?.remote_control_allowed === false) void cancelPendingWork(true); + }, [cancelPendingWork, status?.remote_control_allowed]); + // ── Polling ────────────────────────────────────────────────────── const applyStatus = useCallback((nextStatus: RemoteConnectStatus, restoreSelection = false) => { diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts index 8c25eca291..203d2d8e3d 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts @@ -1116,7 +1116,10 @@ describe('PeerConnectionManager recovery races', () => { expect(connection.getState().health).toBe('ready'); }); - it('re-attaches when presence drops during an already running keepalive', async () => { + it.each([ + { name: 'the peer drops offline', online: [] as string[], controllerOnly: false }, + { name: 'a legacy peer refreshes a controller-only roster', online: ['peer-1'], controllerOnly: true }, + ])('re-attaches when $name during an already running keepalive', async ({ online, controllerOnly }) => { const rpc = createRpc(); const ping = deferred(); let pingCount = 0; @@ -1126,7 +1129,7 @@ describe('PeerConnectionManager recovery races', () => { })); const connection = await manager.connect('peer-1', 'Studio'); await vi.advanceTimersByTimeAsync(KEEPALIVE_MS); - manager.reportPresence([]); + manager.reportPresence(online, controllerOnly); ping.resolve(JSON.stringify({ resp: 'host_invoke_result', ok: true, value: { host_type: 'desktop', capabilities: {} } })); await vi.advanceTimersByTimeAsync(0); expect(connection.getState().health).toBe('ready'); diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 738fab679c..49677425b4 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -307,6 +307,7 @@ interface ConnectionEntry { presenceOnline: boolean | null; probeRequested: boolean; needsReattach: boolean; + verifyHiddenAttachment: boolean; healthCheckInFlight: Promise | null; reattachInFlight: Promise | null; hostStarting: boolean; @@ -517,7 +518,8 @@ export class PeerConnectionManager { } else if (controllerOnly && entry.presenceOnline && entry.health === 'ready') { // Hosts may prune an invisible controller when their roster changes. // Verify the attachment while the peer remains reachable. - void this.runHealthCheck(entry, true); + entry.verifyHiddenAttachment = true; + void this.runHealthCheck(entry); } else if (entry.presenceOnline && wasOnline === false && (entry.health === 'degraded' || entry.probeRequested)) { this.cancelTimer(entry); void this.runHealthCheck(entry); @@ -570,6 +572,7 @@ export class PeerConnectionManager { presenceOnline: null, probeRequested: false, needsReattach: false, + verifyHiddenAttachment: false, healthCheckInFlight: null, reattachInFlight: null, hostStarting: false, @@ -921,7 +924,7 @@ export class PeerConnectionManager { * `peer_control_attach` because the host may have pruned this controller * during the gap that made us degraded in the first place. */ - private runHealthCheck(entry: ConnectionEntry, verifyHiddenAttachment = false): Promise { + private runHealthCheck(entry: ConnectionEntry): Promise { if (this.entries.get(entry.deviceId) !== entry || entry.disposed) { return Promise.resolve(); } @@ -929,7 +932,7 @@ export class PeerConnectionManager { return entry.healthCheckInFlight; } this.cancelTimer(entry); - const check = this.checkHealth(entry, verifyHiddenAttachment).finally(() => { + const check = this.checkHealth(entry).finally(() => { if (entry.healthCheckInFlight !== check) return; entry.healthCheckInFlight = null; entry.probeRequested = false; @@ -942,14 +945,15 @@ export class PeerConnectionManager { return check; } - private async checkHealth(entry: ConnectionEntry, verifyHiddenAttachment: boolean): Promise { + private async checkHealth(entry: ConnectionEntry): Promise { try { const { capabilities, status } = await this.probeCapabilities(entry); // The host may have dropped this controller (presence loss, routing // restart) while every request still succeeded; re-attach instead of // reporting `ready` for a link that receives no events. const lostAttachment = status.callerAttached === false - || (verifyHiddenAttachment && status.callerAttached === null); + || (entry.verifyHiddenAttachment && status.callerAttached === null); + entry.verifyHiddenAttachment = false; if (lostAttachment) { log.info('Peer host no longer has this controller attached; re-attaching', { deviceId: entry.deviceId, diff --git a/src/web-ui/src/locales/en-US/scenes/capabilities.json b/src/web-ui/src/locales/en-US/scenes/capabilities.json index 5fd49ec551..f0f02a49bc 100644 --- a/src/web-ui/src/locales/en-US/scenes/capabilities.json +++ b/src/web-ui/src/locales/en-US/scenes/capabilities.json @@ -332,6 +332,7 @@ "title": "Remote Connect, Bots & Peer Devices", "summary": "Follow sessions, approve permissions, and keep working from Mobile Web or a WeChat, Feishu, or Telegram bot—or enter Peer Device Mode to browse and drive another same-account computer right from your current OpenBitFun window.", "items": { + "device-control-permission": "Allow control of this device", "connection-methods": "Use the zero-setup official Relay or Desktop LAN Relay concurrently", "start-stop-status": "Start or stop Remote Connect channels and inspect live connection status", "network": "Inspect LAN IP addresses, network interfaces, and shareable QR invitations", diff --git a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json index 9062362e51..21e91e8ca6 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json @@ -332,6 +332,7 @@ "title": "Remote Connect 远控与多设备互控", "summary": "离开工位也能用手机网页,或接入微信、飞书、Telegram 中的聊天机器人查看对话进度、审批权限并继续指挥;同账号多台电脑还能开启 Peer Device Mode,在一个窗口里直接切换操作另一台机器的工作区与会话。", "items": { + "device-control-permission": "本机可被控制", "connection-methods": "使用免部署官方 Relay 或桌面端局域网 Relay(可同时开启)", "start-stop-status": "一键启动、停用远控渠道并查看实时连接与设备信息", "network": "查看本机局域网地址、网络网卡状态与扫码邀请链接", diff --git a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json index 53f93efd16..7f3ca0f876 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json @@ -332,6 +332,7 @@ "title": "Remote Connect 遠控與多裝置互控", "summary": "離開座位也能用手機網頁,或接入微信、飛書、Telegram 中的聊天機器人檢視對話進度、審批權限並繼續指揮;同帳號多台電腦還能開啟 Peer Device Mode,在一個視窗裡直接切換操作另一台機器的工作區與工作階段。", "items": { + "device-control-permission": "本機可被控制", "connection-methods": "使用免部署官方 Relay 或桌面端區域網路 Relay(可同時開啟)", "start-stop-status": "一鍵啟動、停用遠控管道並檢視即時連線與裝置資訊", "network": "檢視本機區域網路位址、網路介面卡狀態與掃碼邀請連結",