diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 290598a868..ba568cdfc6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -174,6 +174,12 @@ jobs: if: runner.os == 'Windows' run: cargo test --locked -p openbitfun-cli --test terminal_process_contracts -- --test-threads=1 + # Windows file replacement and process ownership differ from POSIX. The + # terminal process target does not run these daemon and TUI unit tests. + - name: Run Windows CLI daemon and QR regressions + if: runner.os == 'Windows' + run: "cargo test --locked -p openbitfun-cli --bin openbitfun -- daemon:: ui::tool_cards::tests::" + - name: Run SDK Host tests if: runner.os == 'Linux' run: cargo test --locked -p openbitfun-sdk-host -p openbitfun-sdk-host-app diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index e9aa99c3a5..d2555b6ddb 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -33,12 +33,12 @@ Docs, website, search, and agents see only features, settings, and documented su ## 控制边界 / Control boundary -- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **56**、委托 **72**、需交互 **208**、不支持 **0**。 +- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **58**、委托 **72**、需交互 **206**、不支持 **0**。 - 稳定行为声明为带 JSON 输入契约的 `operations` 或 `options`,并绑定原生产品控制 Provider;智能体不接触原始 Tauri Command。 - `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 336 项子能力都不会写入 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 **56 direct**, **72 delegated**, **208 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 **58 direct**, **72 delegated**, **206 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 336 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. diff --git a/docs/interactive-capabilities/capabilities.json b/docs/interactive-capabilities/capabilities.json index fd1ca70369..8ba33cd4e6 100644 --- a/docs/interactive-capabilities/capabilities.json +++ b/docs/interactive-capabilities/capabilities.json @@ -4,8 +4,8 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "516e1cab17ad7c33ff1be2777de1c52bb8a47ef0292bed32928843b8d1ee72ae", - "ownerDigest": "f27c231da2e536e4f2123910f34f862b55d21feb0528bc915d4d13edbd528af9", + "digest": "2eb272d6820970e0c8ac677714ca03495729fa4a9cd458f1b89a4de726971107", + "ownerDigest": "df28e5eed6e3190741899ebf236bc5fb426d2469187e437839a349a7136c7c34", "searchAcceptance": [ { "id": "native-image-generation", @@ -177,9 +177,9 @@ "userFacing": 44, "documentedItems": 336, "controlCoverage": { - "direct": 56, + "direct": 58, "delegated": 72, - "interactive": 208, + "interactive": 206, "unsupported": 0 } }, @@ -9128,102 +9128,417 @@ } }, { - "id": "feature.remote-connect:open:connection-methods", + "id": "feature.remote-connect:operation:status", "capabilityId": "feature.remote-connect", "itemIds": [ - "connection-methods" + "start-stop-status", + "bots" ], - "kind": "open", - "risk": "ui", - "executionHost": "presentationSurface", + "kind": "operation", + "risk": "read", + "executionHost": "productHost", "availability": { "desktop": { "available": true }, "cli": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true }, "peer": { "available": true, "requiredCapabilities": [ "product_control_v1", - "product_control_presentation_v1" + "remote_connect_control_v1" ] }, "remoteControl": { "available": true }, "detachedDispatch": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true } }, "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + }, + "outputSchema": { "type": "object", - "additionalProperties": false + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:start", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "start-stop-status", + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "lanIp": { + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" }, "outputSchema": { "type": "object", "additionalProperties": true }, - "openReason": "unstructuredInteraction", + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, "presentationTarget": { "kind": "event", "eventName": "openbitfun:open-remote-connect" } }, { - "id": "feature.remote-connect:open:start-stop-status", + "id": "feature.remote-connect:operation:stop", "capabilityId": "feature.remote-connect", "itemIds": [ - "start-stop-status" + "start-stop-status", + "bots" ], - "kind": "open", - "risk": "ui", - "executionHost": "presentationSurface", + "kind": "operation", + "risk": "write", + "executionHost": "productHost", "availability": { "desktop": { "available": true }, "cli": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true }, "peer": { "available": true, "requiredCapabilities": [ "product_control_v1", - "product_control_presentation_v1" + "remote_connect_control_v1" ] }, "remoteControl": { "available": true }, "detachedDispatch": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true } }, "inputSchema": { + "additionalProperties": false, + "properties": { + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" + }, + "outputSchema": { "type": "object", - "additionalProperties": false + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:configure-bot", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "credentialsFile": { + "minLength": 1, + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu" + ], + "type": "string" + } + }, + "required": [ + "method", + "credentialsFile" + ], + "type": "object" }, "outputSchema": { "type": "object", "additionalProperties": true }, - "openReason": "unstructuredInteraction", + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, "presentationTarget": { "kind": "event", "eventName": "openbitfun:open-remote-connect" } }, { - "id": "feature.remote-connect:open:network", + "id": "feature.remote-connect:operation:weixin-login-start", "capabilityId": "feature.remote-connect", "itemIds": [ - "network" + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:weixin-login-poll", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "sessionKey": { + "minLength": 1, + "type": "string" + }, + "verifyCode": { + "type": "string" + } + }, + "required": [ + "sessionKey" + ], + "type": "object" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:set-bot-verbose", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + } + }, + "required": [ + "enabled" + ], + "type": "object" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:open:connection-methods", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "connection-methods" ], "kind": "open", "risk": "ui", @@ -9266,10 +9581,10 @@ } }, { - "id": "feature.remote-connect:open:bots", + "id": "feature.remote-connect:open:network", "capabilityId": "feature.remote-connect", "itemIds": [ - "bots" + "network" ], "kind": "open", "risk": "ui", @@ -25007,10 +25322,13 @@ "titleZh": "启动、停止 Remote Connect 并查看实时连接状态和设备信息", "titleEn": "Start or stop Remote Connect and inspect live status and device information", "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“启动、停止 Remote Connect 并查看实时连接状态和设备信息”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Start or stop Remote Connect and inspect live status and device information” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user." + "kind": "direct", + "operations": [ + "status", + "start", + "stop" + ], + "options": [] } }, { @@ -25029,10 +25347,17 @@ "titleZh": "配置飞书、Telegram、微信等 Bot 并单独停止 Bot", "titleEn": "Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently", "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“配置飞书、Telegram、微信等 Bot 并单独停止 Bot”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user." + "kind": "direct", + "operations": [ + "configure-bot", + "weixin-login-start", + "weixin-login-poll", + "set-bot-verbose", + "start", + "stop", + "status" + ], + "options": [] } }, { @@ -25082,18 +25407,187 @@ "agentExamplesZh": [ "打开 Remote Connect", "我想配置手机远程控制", - "带我管理已连接设备" + "带我管理已连接设备", + "启动微信机器人并持续监听消息", + "关闭 Telegram 机器人", + "开启手机网页远控" ], "agentExamplesEn": [ "Open Remote Connect", "I want to configure mobile remote control", - "Take me to connected-device management" + "Take me to connected-device management", + "Start the WeChat bot and keep listening", + "Stop the Telegram bot", + "Enable Mobile Web remote control" ], "destination": { "kind": "event", "eventName": "openbitfun:open-remote-connect" }, - "operations": [], + "operations": [ + { + "id": "status", + "titleZh": "查看远控状态", + "titleEn": "Inspect Remote Connect status", + "descriptionZh": "读取当前执行主机的监听、配对、停用与恢复错误;不返回凭据,监听任务存活不等于消息已完成往返。", + "descriptionEn": "Read listener, pairing, disabled and restore-error state on the executing host without credentials. A live listener task does not prove a message round trip.", + "risk": "read", + "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + } + }, + { + "id": "start", + "titleZh": "启动远控渠道", + "titleEn": "Start a Remote Connect channel", + "descriptionZh": "启动指定机器人或手机网页远控。CLI 自动启动 daemon,退出当前聊天后继续监听。新机器人需将返回的配对码发给机器人;CLI 不支持局域网 Relay。", + "descriptionEn": "Start the selected bot or Mobile Web. CLI starts its daemon and keeps listening after this chat exits. Send the returned pairing code to a new bot. CLI does not host a LAN Relay.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "lanIp": { + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" + } + }, + { + "id": "stop", + "titleZh": "停用远控渠道", + "titleEn": "Stop a Remote Connect channel", + "descriptionZh": "停用选定渠道并保留配置和会话。机器人停用状态跨重启保留。关闭手机网页会同时断开该主机的 Peer 设备路由,机器人保持运行。", + "descriptionEn": "Stop the selected channel while retaining configuration and sessions. Bot disablement survives restart. Stopping Mobile Web also disconnects Peer routing on this host; bots keep running.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" + } + }, + { + "id": "configure-bot", + "titleZh": "从主机凭据文件配置机器人", + "titleEn": "Configure a bot from a private host credential file", + "descriptionZh": "读取执行主机上用户提供的私有 JSON 凭据文件并保存配置;不会自动启动。文件包含 bot_type 和对应凭据字段,需绝对路径和仅所有者可读权限;不要把凭据贴到聊天中。远程工作区路径不能用作主机凭据路径。", + "descriptionEn": "Load a user-supplied private JSON BotConfig file on the executing host, with bot_type and provider credential fields; save without starting. Requires an absolute host path and owner-only permissions. Do not paste credentials into chat or use a remote-workspace path.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "credentialsFile": { + "minLength": 1, + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu" + ], + "type": "string" + } + }, + "required": [ + "method", + "credentialsFile" + ], + "type": "object" + }, + "argumentScopes": { + "credentialsFile": "productHostLocal" + } + }, + { + "id": "weixin-login-start", + "titleZh": "开始微信扫码登录", + "titleEn": "Begin WeChat QR login", + "descriptionZh": "生成微信登录二维码。CLI TUI 在工具卡片中直接显示 qrTerminal,无需模型重写;其他终端逐字显示,图形界面显示 qrImageUrl,再用 sessionKey 轮询。扫码本身尚未完成机器人监听和配对。", + "descriptionEn": "Create a WeChat login QR. CLI TUI renders qrTerminal in the tool card without model transcription; other terminals show it verbatim and graphical surfaces show qrImageUrl. Poll using sessionKey; scanning alone does not complete listening and pairing.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + } + }, + { + "id": "weixin-login-poll", + "titleZh": "完成微信登录并启动监听", + "titleEn": "Complete WeChat login and start listening", + "descriptionZh": "轮询同一登录会话。确认后在主机保存凭据并启动监听,向用户展示返回的机器人配对码。凭据不会返回给模型。", + "descriptionEn": "Poll the same login session. Confirmation saves credentials on the host and starts listening; show the returned bot pairing code. Credentials are never returned to the model.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "sessionKey": { + "minLength": 1, + "type": "string" + }, + "verifyCode": { + "type": "string" + } + }, + "required": [ + "sessionKey" + ], + "type": "object" + } + }, + { + "id": "set-bot-verbose", + "titleZh": "设置机器人详细输出", + "titleEn": "Set bot verbose output", + "descriptionZh": "切换所有机器人的详细输出模式并保存。", + "descriptionEn": "Persist verbose output mode for all bot channels.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + } + }, + "required": [ + "enabled" + ], + "type": "object" + } + } + ], "options": [], "searchTerms": [ "feature.remote-connect", @@ -25140,9 +25634,15 @@ "打开 Remote Connect", "我想配置手机远程控制", "带我管理已连接设备", + "启动微信机器人并持续监听消息", + "关闭 Telegram 机器人", + "开启手机网页远控", "Open Remote Connect", "I want to configure mobile remote control", - "Take me to connected-device management" + "Take me to connected-device management", + "Start the WeChat bot and keep listening", + "Stop the Telegram bot", + "Enable Mobile Web remote control" ], "docsUrl": "https://playbook.openbitfun.com/capabilities/feature.remote-connect/" }, diff --git a/docs/interactive-capabilities/capabilities/feature.remote-connect.md b/docs/interactive-capabilities/capabilities/feature.remote-connect.md index bc350ef80f..7f717ecb79 100644 --- a/docs/interactive-capabilities/capabilities/feature.remote-connect.md +++ b/docs/interactive-capabilities/capabilities/feature.remote-connect.md @@ -19,11 +19,11 @@ Connect to this host from mobile, a bot, or another OpenBitFun device to inspect - **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 选择局域网或官方 Relay - Choose LAN or the official Relay -- **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 启动、停止 Remote Connect 并查看实时连接状态和设备信息 +- **智能体可直接控制 / Direct Agent control** · 启动、停止 Remote Connect 并查看实时连接状态和设备信息 - Start or stop Remote Connect and inspect live status and device information - **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 查看局域网 IP、网络信息与可分享的连接配置 - Inspect LAN IP, network details, and shareable connection configuration -- **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 配置飞书、Telegram、微信等 Bot 并单独停止 Bot +- **智能体可直接控制 / Direct Agent control** · 配置飞书、Telegram、微信等 Bot 并单独停止 Bot - Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently - **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 使用 GitHub 登录、退出并查看身份状态 - Sign in with GitHub, sign out, and inspect identity status @@ -47,7 +47,13 @@ Connect to this host from mobile, a bot, or another OpenBitFun device to inspect | 操作 / Action | 中文说明 | English description | | --- | --- | --- | -| 打开对应界面 / Open the UI | 进入 OpenBitFun 中对应的功能界面。 | Open the matching feature in OpenBitFun. | +| 查看远控状态 / Inspect Remote Connect status | 读取当前执行主机的监听、配对、停用与恢复错误;不返回凭据,监听任务存活不等于消息已完成往返。 | Read listener, pairing, disabled and restore-error state on the executing host without credentials. A live listener task does not prove a message round trip. | +| 启动远控渠道 / Start a Remote Connect channel | 启动指定机器人或手机网页远控。CLI 自动启动 daemon,退出当前聊天后继续监听。新机器人需将返回的配对码发给机器人;CLI 不支持局域网 Relay。 | Start the selected bot or Mobile Web. CLI starts its daemon and keeps listening after this chat exits. Send the returned pairing code to a new bot. CLI does not host a LAN Relay. | +| 停用远控渠道 / Stop a Remote Connect channel | 停用选定渠道并保留配置和会话。机器人停用状态跨重启保留。关闭手机网页会同时断开该主机的 Peer 设备路由,机器人保持运行。 | Stop the selected channel while retaining configuration and sessions. Bot disablement survives restart. Stopping Mobile Web also disconnects Peer routing on this host; bots keep running. | +| 从主机凭据文件配置机器人 / Configure a bot from a private host credential file | 读取执行主机上用户提供的私有 JSON 凭据文件并保存配置;不会自动启动。文件包含 bot_type 和对应凭据字段,需绝对路径和仅所有者可读权限;不要把凭据贴到聊天中。远程工作区路径不能用作主机凭据路径。 | Load a user-supplied private JSON BotConfig file on the executing host, with bot_type and provider credential fields; save without starting. Requires an absolute host path and owner-only permissions. Do not paste credentials into chat or use a remote-workspace path. | +| 开始微信扫码登录 / Begin WeChat QR login | 生成微信登录二维码。CLI TUI 在工具卡片中直接显示 qrTerminal,无需模型重写;其他终端逐字显示,图形界面显示 qrImageUrl,再用 sessionKey 轮询。扫码本身尚未完成机器人监听和配对。 | Create a WeChat login QR. CLI TUI renders qrTerminal in the tool card without model transcription; other terminals show it verbatim and graphical surfaces show qrImageUrl. Poll using sessionKey; scanning alone does not complete listening and pairing. | +| 完成微信登录并启动监听 / Complete WeChat login and start listening | 轮询同一登录会话。确认后在主机保存凭据并启动监听,向用户展示返回的机器人配对码。凭据不会返回给模型。 | Poll the same login session. Confirmation saves credentials on the host and starts listening; show the returned bot pairing code. Credentials are never returned to the model. | +| 设置机器人详细输出 / Set bot verbose output | 切换所有机器人的详细输出模式并保存。 | Persist verbose output mode for all bot channels. | ## 可配置选项 / Configurable options @@ -63,6 +69,12 @@ Connect to this host from mobile, a bot, or another OpenBitFun device to inspect - “I want to configure mobile remote control” - “带我管理已连接设备” - “Take me to connected-device management” +- “启动微信机器人并持续监听消息” + - “Start the WeChat bot and keep listening” +- “关闭 Telegram 机器人” + - “Stop the Telegram bot” +- “开启手机网页远控” + - “Enable Mobile Web remote control” 智能体会先查找相关功能或设置,确认目标后再替你打开、执行或修改。完整能力目录不会预先塞进对话上下文。 diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index b9d0d817b5..d1f625fa37 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": "516e1cab17ad7c33ff1be2777de1c52bb8a47ef0292bed32928843b8d1ee72ae", - "count": 208, + "catalogDigest": "2eb272d6820970e0c8ac677714ca03495729fa4a9cd458f1b89a4de726971107", + "count": 206, "reasonCounts": { "externalAuth": 4, "secretEntry": 5, - "unstructuredInteraction": 174, + "unstructuredInteraction": 172, "visualSelection": 25 }, "entries": [ @@ -1965,25 +1965,6 @@ "command:remote_connect_get_methods" ] }, - { - "capabilityId": "feature.remote-connect", - "itemId": "start-stop-status", - "titleZh": "启动、停止 Remote Connect 并查看实时连接状态和设备信息", - "titleEn": "Start or stop Remote Connect and inspect live status and device information", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“启动、停止 Remote Connect 并查看实时连接状态和设备信息”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Start or stop Remote Connect and inspect live status and device information” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user.", - "presentationTarget": { - "kind": "event", - "eventName": "openbitfun:open-remote-connect" - }, - "evidence": [ - "command:remote_connect_start", - "command:remote_connect_stop", - "command:remote_connect_status", - "command:remote_connect_get_device_info" - ] - }, { "capabilityId": "feature.remote-connect", "itemId": "network", @@ -2003,27 +1984,6 @@ "command:remote_connect_set_form_state" ] }, - { - "capabilityId": "feature.remote-connect", - "itemId": "bots", - "titleZh": "配置飞书、Telegram、微信等 Bot 并单独停止 Bot", - "titleEn": "Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“配置飞书、Telegram、微信等 Bot 并单独停止 Bot”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user.", - "presentationTarget": { - "kind": "event", - "eventName": "openbitfun:open-remote-connect" - }, - "evidence": [ - "command:remote_connect_configure_bot", - "command:remote_connect_stop_bot", - "command:remote_connect_weixin_qr_start", - "command:remote_connect_weixin_qr_poll", - "command:remote_connect_get_bot_verbose_mode", - "command:remote_connect_set_bot_verbose_mode" - ] - }, { "capabilityId": "feature.remote-connect", "itemId": "account", diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index a904911751..e8d4aa17d9 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -1,7 +1,7 @@ { "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "516e1cab17ad7c33ff1be2777de1c52bb8a47ef0292bed32928843b8d1ee72ae", + "catalogDigest": "2eb272d6820970e0c8ac677714ca03495729fa4a9cd458f1b89a4de726971107", "commandCount": 707, "coverage": { "commandCount": 707, diff --git a/scripts/generate-interactive-capabilities.mjs b/scripts/generate-interactive-capabilities.mjs index f6967839bd..622d4b14d6 100644 --- a/scripts/generate-interactive-capabilities.mjs +++ b/scripts/generate-interactive-capabilities.mjs @@ -1292,6 +1292,9 @@ function definitionAvailability(kind, handler) { detachedDispatch: availability(false, reason), }; } + if (handler?.kind === 'provider' && handler.providerId === 'remote-connect') { + return { desktop, cli: availability(true), peer: peer('remote_connect_control_v1'), remoteControl: remote, detachedDispatch: availability(true) }; + } const presentationOnly = handler?.kind === 'productAction'; const nativeProvider = handler?.kind === 'provider'; const headlessReason = presentationOnly diff --git a/src/apps/cli/AGENTS.md b/src/apps/cli/AGENTS.md index a5ac8f2bc0..b1c9e11c3b 100644 --- a/src/apps/cli/AGENTS.md +++ b/src/apps/cli/AGENTS.md @@ -201,3 +201,21 @@ For `/goal` prompt routing (including the pending-session guard): cargo test --locked -p openbitfun-cli --bin openbitfun goal_prompts_ cargo test --locked -p openbitfun-cli --bin openbitfun -- modes::exec::tests:: dispatch::worker::tests:: ``` + +For daemon Remote Connect management, private IPC authentication/frame bounds, +and daemon lifecycle regressions: + +```bash +cargo test --locked -p openbitfun-cli --bin openbitfun daemon:: +``` + +Bot listeners belong to the daemon. Chat/Shared/dispatch processes call its +private, versioned endpoint and never replay a mutation after an unknown outcome. +The executing account is checked before control requests reach the shared owner. +These loopback fixtures do not establish live Relay or provider connectivity. + +For the inline WeChat QR card, collapsed output, theme contrast and narrow terminals: + +```bash +cargo test --locked -p openbitfun-cli --bin openbitfun ui::tool_cards::tests:: +``` diff --git a/src/apps/cli/README.md b/src/apps/cli/README.md index 4331ed9a71..23fb0c2b4a 100644 --- a/src/apps/cli/README.md +++ b/src/apps/cli/README.md @@ -312,6 +312,42 @@ currently install an auto-start service; use `openbitfun daemon run` under a supervisor instead. Run `openbitfun daemon --help` for lifecycle commands and platform diagnostics. +### Bots and Mobile Web from Claw + +In Claw chat, ask to start a WeChat, Telegram, or Feishu bot, inspect Remote +Connect, stop a channel, or enable Mobile Web. Claw uses `OpenBitFunControl` +(`feature.remote-connect`) on the executing host. Starting a channel launches +the local CLI daemon when needed; closing the chat leaves listeners running. +Use `daemon install` if they should also return after a machine reboot. + +For WeChat, the TUI displays a full black-on-white QR in the tool card, including +when tool details are collapsed. Widen the terminal if the card asks for more +columns; scroll to the latest QR if a login refreshes it. Scan the QR and let Claw finish login polling, then +send the returned six-digit pairing code to the bot. QR login only obtains the +credentials; the separate pairing step authorizes message routing. Telegram +and Feishu accept a private JSON credential file on the executing host, for +example `{"bot_type":"telegram","bot_token":"..."}` or +`{"bot_type":"feishu","app_id":"...","app_secret":"..."}`. On Unix, give it +owner-only permissions (`chmod 600`). Supply the file path to Claw, never the +secret values in the conversation. + +The daemon restores paired, enabled channels after restart. Stopping a bot +retains its credentials, selected workspace and session, and keeps it disabled +until explicitly started. One process may listen to each bot channel in a +product home; stop it in Desktop before starting it in the daemon, or vice +versa. A listener reported as running may still be retrying its provider; +check a real inbound message and reply to verify connectivity. + +Mobile Web uses the configured account Relay and returns a device URL. Sign in +with the same OpenBitFun account on the phone. Stopping Mobile Web also stops +Peer Device routing on this daemon until an explicit start or daemon restart; +bot channels remain active. CLI does not host an embedded LAN Relay. All +management targets the executing host, including Peer and detached jobs. Direct +Peer RPC supports bot management; use a Claw conversation for Relay start/stop so +the mutation does not hold the connection it replaces. +remote workspace paths cannot be used as local credential-file paths. An older +daemon must be upgraded and restarted before it supports these controls. + ## Updates and troubleshooting ```bash diff --git a/src/apps/cli/src/account.rs b/src/apps/cli/src/account.rs index cd8a875e4d..394c919d3f 100644 --- a/src/apps/cli/src/account.rs +++ b/src/apps/cli/src/account.rs @@ -242,6 +242,16 @@ impl CliAccountRoutingHost { self.stop_routing_locked().await; } + pub(crate) async fn connection_state( + &self, + ) -> openbitfun_core::service::remote_connect::relay_client::ConnectionState { + let client = self.relay_client.read().await.clone(); + match client { + Some(client) => client.connection_state().await, + None => openbitfun_core::service::remote_connect::relay_client::ConnectionState::Disconnected, + } + } + pub(crate) async fn stop_device_routing(&self) { self.stop_routing().await; } @@ -675,6 +685,7 @@ impl AccountRuntimeHost for CliAccountRoutingHost { } async fn stop_device_routing(&self) { + crate::remote_control::retire_daemon_account().await; self.stop_routing().await; } } diff --git a/src/apps/cli/src/daemon/control.rs b/src/apps/cli/src/daemon/control.rs new file mode 100644 index 0000000000..0060813b21 --- /dev/null +++ b/src/apps/cli/src/daemon/control.rs @@ -0,0 +1,533 @@ +//! Private, versioned, bounded local management for the daemon's Remote Connect owner. +//! A failed reply has unknown outcome: clients never replay a submitted mutation. + +use crate::{remote_control::CliRemoteControlHost, runtime::CliRuntimeContext}; +use anyhow::{anyhow, Context, Result}; +use fs2::FileExt; +use openbitfun_product_domains::remote_control::{RemoteControlRequest, REMOTE_CONTROL_CAPABILITY}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::{ + fs::{File, OpenOptions}, + io::Write, + path::PathBuf, + sync::Arc, + time::Duration, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; + +const VERSION: u32 = 1; +const MAX_FRAME: usize = 64 * 1024; +const TIMEOUT: Duration = Duration::from_secs(100); +static START_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +#[derive(Serialize, Deserialize)] +struct Discovery { + version: u32, + port: u16, + token: String, +} +#[derive(Debug, Serialize, Deserialize)] +struct Request { + version: u32, + token: String, + command: RemoteControlRequest, + account_user_id: String, + #[serde(default)] + shutdown: bool, +} +#[derive(Serialize, Deserialize)] +struct Response { + result: Option, + error: Option, +} + +fn directory() -> Result { + let path = openbitfun_core::infrastructure::PathManager::new()? + .product_home_dir() + .join("cli-daemon-control"); + std::fs::create_dir_all(&path)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))?; + } + Ok(path) +} + +fn private_options() -> OpenOptions { + let mut options = OpenOptions::new(); + options.read(true).write(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + } + options +} + +#[derive(Clone)] +pub(crate) struct OwnerLease { + _file: Arc, +} + +pub(crate) struct Server { + lease: OwnerLease, + path: PathBuf, + listener: TcpListener, + discovery: Discovery, +} + +impl Server { + pub(crate) async fn reserve() -> Result { + Self::reserve_in(directory()?).await + } + + async fn reserve_in(directory: PathBuf) -> Result { + let lease = private_options() + .create(true) + .truncate(false) + .open(directory.join("owner.lock"))?; + FileExt::try_lock_exclusive(&lease).context("another CLI daemon owns Remote Connect")?; + let path = directory.join("endpoint.json"); + // A crashed owner can leave discovery behind. Only the new exclusive + // owner may remove it; Windows rename cannot replace an existing file. + match std::fs::remove_file(&path) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error).context("retire stale CLI daemon discovery"), + } + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).await?; + let discovery = Discovery { + version: VERSION, + port: listener.local_addr()?.port(), + token: format!("{}{}", uuid::Uuid::new_v4(), uuid::Uuid::new_v4()), + }; + Ok(Self { + lease: OwnerLease { + _file: Arc::new(lease), + }, + path, + listener, + discovery, + }) + } + + /// The listener can stop before bot and account cleanup completes. Retain + /// this guard in the daemon runner until the entire shutdown has finished. + pub(crate) fn owner_lease(&self) -> OwnerLease { + self.lease.clone() + } + + fn publish(&self) -> Result<()> { + let temp = self + .path + .with_extension(format!("{}.tmp", uuid::Uuid::new_v4())); + let mut file = private_options().create_new(true).open(&temp)?; + file.write_all(&serde_json::to_vec(&self.discovery)?)?; + file.sync_all()?; + drop(file); + std::fs::rename(&temp, &self.path)?; + Ok(()) + } + + pub(crate) async fn run(self, host: Arc) -> Result<()> { + // Publish only after the account, bot owner and command router are ready. + self.publish()?; + let mut clients = tokio::task::JoinSet::new(); + loop { + tokio::select! { + stream = self.listener.accept() => { + let (stream, _) = stream?; + let token = self.discovery.token.clone(); + let host = host.clone(); + clients.spawn(async move { + let _ = serve(stream, &token, host).await; + }); + } + Some(_) = clients.join_next(), if !clients.is_empty() => {} + } + } + } +} +impl Drop for Server { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } +} + +async fn read_frame(stream: &mut TcpStream) -> Result { + let length = stream.read_u32().await? as usize; + anyhow::ensure!( + length > 0 && length <= MAX_FRAME, + "Invalid daemon management frame length" + ); + let mut bytes = vec![0; length]; + stream.read_exact(&mut bytes).await?; + Ok(serde_json::from_slice(&bytes)?) +} +async fn write_frame(stream: &mut TcpStream, value: &T) -> Result<()> { + let bytes = serde_json::to_vec(value)?; + anyhow::ensure!( + bytes.len() <= MAX_FRAME, + "Daemon management result exceeds frame limit" + ); + stream.write_u32(bytes.len() as u32).await?; + stream.write_all(&bytes).await?; + Ok(()) +} +async fn serve(stream: TcpStream, token: &str, host: Arc) -> Result<()> { + serve_with(stream, token, move |request| async move { + if request.shutdown { + anyhow::ensure!( + matches!(request.command, RemoteControlRequest::Status), + "Invalid shutdown envelope" + ); + host.request_shutdown(); + Ok(json!({"shutdownRequested":true})) + } else { + host.execute_for_account(request.command, &request.account_user_id) + .await + } + }) + .await +} + +async fn serve_with(mut stream: TcpStream, token: &str, execute: F) -> Result<()> +where + F: FnOnce(Request) -> Fut, + Fut: std::future::Future>, +{ + let request: Request = + tokio::time::timeout(Duration::from_secs(5), read_frame(&mut stream)).await??; + anyhow::ensure!( + request.version == VERSION && request.token == token, + "Unauthorized daemon management request" + ); + let response = match execute(request).await { + Ok(result) => Response { + result: Some(result), + error: None, + }, + Err(error) => Response { + result: None, + error: Some(error.to_string()), + }, + }; + tokio::time::timeout(Duration::from_secs(5), write_frame(&mut stream, &response)).await??; + Ok(()) +} + +async fn connect() -> Result<(TcpStream, Discovery)> { + let discovery: Discovery = + serde_json::from_slice(&std::fs::read(directory()?.join("endpoint.json"))?)?; + anyhow::ensure!( + discovery.version == VERSION, + "unsupported: Upgrade and restart the CLI daemon for Remote Connect management" + ); + let stream = tokio::time::timeout( + Duration::from_secs(1), + TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, discovery.port)), + ) + .await??; + Ok((stream, discovery)) +} + +pub(crate) async fn invoke( + runtime: &Arc, + command: RemoteControlRequest, +) -> Result { + if matches!( + &command, + RemoteControlRequest::Start { + method: openbitfun_product_domains::remote_control::RemoteControlMethod::Lan, + .. + } | RemoteControlRequest::Stop { + method: openbitfun_product_domains::remote_control::RemoteControlMethod::Lan + } + ) { + anyhow::bail!("unsupported: This CLI host has no embedded LAN Relay; use Mobile Web with the configured account Relay"); + } + if let Some(host) = crate::remote_control::daemon_host() { + return host.execute(command).await; + } + let account_user_id = match runtime.account_runtime().account_info().await { + Ok(info) => info.user_id, + Err(_) if command.is_readonly() => { + return Ok(json!({"daemonRunning":false,"state":"account_required"})) + } + Err(error) => return Err(error), + }; + let connection = match connect().await { + Ok(connection) => connection, + Err(_) if command.is_readonly() => { + return Ok( + json!({"daemonRunning":false,"state":"unavailable", "nextStep":"Start a channel to launch the CLI daemon; if an older daemon is running, upgrade and restart it"}), + ) + } + Err(_) => { + let _startup = START_LOCK.lock().await; + if let Ok(connection) = connect().await { + connection + } else { + anyhow::ensure!(!super::is_daemon_running(), "unsupported: The running daemon has no Remote Connect management endpoint; upgrade and restart it"); + runtime.account_runtime().read_account_context().await?; + runtime.account_routing().stop_device_routing().await; + let executable = std::env::current_exe()?; + let mut process = + openbitfun_services_core::process_manager::create_command(executable); + process + .arg("daemon") + .arg("run") + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + unsafe { + process.pre_exec(|| { + if libc::setsid() == -1 { + Err(std::io::Error::last_os_error()) + } else { + Ok(()) + } + }); + } + } + let mut child = match process.spawn().context("start CLI Remote Connect daemon") { + Ok(child) => child, + Err(error) => { + restore_caller_routing(runtime).await; + return Err(error); + } + }; + let started = std::time::Instant::now(); + loop { + if let Ok(connection) = connect().await { + // Reap when the detached process eventually exits. + std::thread::spawn(move || { + let _ = child.wait(); + }); + break connection; + } + if let Some(status) = child.try_wait()? { + restore_caller_routing(runtime).await; + return Err(anyhow!("CLI daemon exited before becoming ready: {status}. Run openbitfun daemon run to inspect the startup failure")); + } + if started.elapsed() > Duration::from_secs(60) { + std::thread::spawn(move || { + let _ = child.wait(); + }); + return Err(anyhow!("CLI daemon startup is still pending; inspect daemon status before retrying")); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + } + } + }; + let (mut stream, discovery) = connection; + let request = Request { + version: VERSION, + token: discovery.token, + command, + account_user_id, + shutdown: false, + }; + let result = tokio::time::timeout(TIMEOUT, async { + write_frame(&mut stream, &request).await?; + read_frame::(&mut stream).await + }) + .await; + let response = result + .map_err(|_| { + anyhow!( + "outcome_unknown: Daemon request timed out; inspect status before another mutation" + ) + })? + .map_err(|_| { + anyhow!( + "outcome_unknown: Daemon connection closed; inspect status before another mutation" + ) + })?; + match (response.result, response.error) { + (Some(mut result), None) => { + result["managementCapability"] = json!(REMOTE_CONTROL_CAPABILITY); + Ok(result) + } + (_, Some(error)) => Err(anyhow!(error)), + _ => Err(anyhow!("Invalid daemon management response")), + } +} + +/// OS-independent liveness proof, including Windows where a Unix PID probe +/// cannot observe the supervised daemon. +pub(crate) fn owner_is_running() -> bool { + let Ok(directory) = directory() else { + return false; + }; + let Ok(file) = private_options().open(directory.join("owner.lock")) else { + return false; + }; + match FileExt::try_lock_exclusive(&file) { + Ok(()) => { + let _ = FileExt::unlock(&file); + false + } + Err(error) => error.kind() == std::io::ErrorKind::WouldBlock, + } +} + +/// Used by account retirement and `daemon stop`; no provider token is involved. +/// A successfully submitted request is followed by the caller's existing +/// bounded wait for owner release. Never infer shutdown from the send alone. +pub(crate) fn request_shutdown() -> bool { + let result = (|| -> Result<()> { + let discovery: Discovery = + serde_json::from_slice(&std::fs::read(directory()?.join("endpoint.json"))?)?; + anyhow::ensure!( + discovery.version == VERSION, + "Unsupported daemon management protocol" + ); + let address = std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, discovery.port)); + let mut stream = std::net::TcpStream::connect_timeout(&address, Duration::from_secs(1))?; + stream.set_write_timeout(Some(Duration::from_secs(1)))?; + let bytes = serde_json::to_vec(&Request { + version: VERSION, + token: discovery.token, + command: RemoteControlRequest::Status, + account_user_id: String::new(), + shutdown: true, + })?; + stream.write_all(&(bytes.len() as u32).to_be_bytes())?; + stream.write_all(&bytes)?; + Ok(()) + })(); + result.is_ok() +} + +async fn restore_caller_routing(runtime: &Arc) { + if super::is_daemon_running() || connect().await.is_ok() { + return; + } + if let Ok(info) = runtime.account_runtime().account_info().await { + if let Err(error) = runtime + .account_runtime() + .restore_device_routing(&info.device_name) + .await + { + tracing::warn!("Could not restore caller routing after daemon startup failed: {error}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn daemon_owner_outlives_endpoint_until_cleanup_finishes() { + let root = tempfile::tempdir().unwrap(); + let server = Server::reserve_in(root.path().to_path_buf()).await.unwrap(); + let cleanup_owner = server.owner_lease(); + server.publish().unwrap(); + assert!(Server::reserve_in(root.path().to_path_buf()).await.is_err()); + assert!( + root.path().join("endpoint.json").exists(), + "A competing start must not remove the current owner's discovery" + ); + drop(server); + assert!(!root.path().join("endpoint.json").exists()); + assert!( + Server::reserve_in(root.path().to_path_buf()).await.is_err(), + "A replacement daemon must wait for bot and account cleanup, even after discovery is withdrawn" + ); + drop(cleanup_owner); + assert!(Server::reserve_in(root.path().to_path_buf()).await.is_ok()); + } + + #[tokio::test] + async fn stale_discovery_is_replaced_after_exclusive_owner_recovery() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("endpoint.json"); + std::fs::write(&path, b"old crashed owner").unwrap(); + let server = Server::reserve_in(root.path().to_path_buf()).await.unwrap(); + assert!( + !path.exists(), + "Stale discovery must not be advertised during startup" + ); + server.publish().unwrap(); + let discovery: Discovery = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(discovery.version, VERSION); + assert_eq!(discovery.port, server.listener.local_addr().unwrap().port()); + drop(server); + assert!(!path.exists()); + } + + #[tokio::test] + async fn management_authentication_precedes_all_effects_and_returns_state() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for (version, token, accepted) in [ + (VERSION, "wrong", false), + (VERSION + 1, "secret", false), + (VERSION, "secret", true), + ] { + let effects = Arc::new(AtomicUsize::new(0)); + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)) + .await + .unwrap(); + let address = listener.local_addr().unwrap(); + let count = effects.clone(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + serve_with(stream, "secret", move |request| async move { + assert_eq!(request.account_user_id, "account"); + count.fetch_add(1, Ordering::SeqCst); + Ok(json!({"listenerRunning":true})) + }) + .await + }); + let mut stream = TcpStream::connect(address).await.unwrap(); + write_frame( + &mut stream, + &Request { + version, + token: token.into(), + command: RemoteControlRequest::Status, + account_user_id: "account".into(), + shutdown: false, + }, + ) + .await + .unwrap(); + let response = read_frame::(&mut stream).await; + assert_eq!(response.is_ok(), accepted); + assert_eq!(server.await.unwrap().is_ok(), accepted); + assert_eq!(effects.load(Ordering::SeqCst), usize::from(accepted)); + if accepted { + assert_eq!(response.unwrap().result.unwrap()["listenerRunning"], true); + } + } + } + + #[tokio::test] + async fn frame_bounds_and_closed_protocol() { + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)) + .await + .unwrap(); + let address = listener.local_addr().unwrap(); + let client = tokio::spawn(async move { + let mut stream = TcpStream::connect(address).await.unwrap(); + stream.write_u32(MAX_FRAME as u32 + 1).await.unwrap(); + }); + let (mut stream, _) = listener.accept().await.unwrap(); + assert!(read_frame::(&mut stream) + .await + .unwrap_err() + .to_string() + .contains("length")); + client.await.unwrap(); + } +} diff --git a/src/apps/cli/src/daemon/mod.rs b/src/apps/cli/src/daemon/mod.rs index 02d969b716..75cd6ea0d7 100644 --- a/src/apps/cli/src/daemon/mod.rs +++ b/src/apps/cli/src/daemon/mod.rs @@ -7,6 +7,7 @@ //! AuthConnect wins). `install`/`uninstall` register it with the platform //! service manager (systemd user unit / LaunchAgent) so it survives reboots. +pub(crate) mod control; mod pid; mod provision; mod runner; diff --git a/src/apps/cli/src/daemon/pid.rs b/src/apps/cli/src/daemon/pid.rs index 12c557848e..79a48d0423 100644 --- a/src/apps/cli/src/daemon/pid.rs +++ b/src/apps/cli/src/daemon/pid.rs @@ -52,6 +52,9 @@ pub(crate) fn remove_pid_file() { /// Whether a daemon process recorded in the pid file is alive right now. pub(crate) fn is_daemon_running() -> bool { + if super::control::owner_is_running() { + return true; + } default_pid_file_path() .ok() .and_then(|path| read_pid_file_from(&path)) @@ -62,6 +65,9 @@ pub(crate) fn is_daemon_running() -> bool { /// daemon was signalled. #[cfg(unix)] pub(crate) fn request_daemon_shutdown() -> bool { + if super::control::request_shutdown() { + return true; + } let Some(pid) = default_pid_file_path() .ok() .and_then(|path| read_pid_file_from(&path)) @@ -77,7 +83,7 @@ pub(crate) fn request_daemon_shutdown() -> bool { #[cfg(not(unix))] pub(crate) fn request_daemon_shutdown() -> bool { - false + super::control::request_shutdown() } /// Whether the given pid refers to a live process. diff --git a/src/apps/cli/src/daemon/runner.rs b/src/apps/cli/src/daemon/runner.rs index a71c53fc5a..9b0b770f67 100644 --- a/src/apps/cli/src/daemon/runner.rs +++ b/src/apps/cli/src/daemon/runner.rs @@ -24,6 +24,9 @@ pub(crate) async fn run_daemon() -> Result<()> { )); } + let management = super::control::Server::reserve().await?; + let _management_owner = management.owner_lease(); + // The daemon is not bound to the caller's cwd; peer commands carry their // own workspace paths. Home is a stable root for the runtime context. let workspace_root = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from(".")); @@ -44,7 +47,10 @@ pub(crate) async fn run_daemon() -> Result<()> { let device = DeviceIdentity::from_current_machine().map_err(|e| anyhow!("detect device: {e}"))?; - account.restore_device_routing(&device.device_name).await?; + let remote = crate::remote_control::activate_daemon(&runtime).await?; + if let Err(error) = account.restore_device_routing(&device.device_name).await { + tracing::warn!("Initial daemon Relay connection failed; will retry: {error}"); + } // Continuous account settings sync (30s pull + debounced push) so this // always-on host converges with cloud changes made on other devices and @@ -53,10 +59,32 @@ pub(crate) async fn run_daemon() -> Result<()> { pid::write_pid_file()?; tracing::info!("openbitfun daemon running (pid {})", std::process::id()); + let mut management_task = tokio::spawn(management.run(remote.clone())); + let relay_owner = remote.clone(); + let reconnect_task = tokio::spawn(async move { + let mut retry = tokio::time::interval(Duration::from_secs(5)); + retry.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + retry.tick().await; + if let Err(error) = relay_owner.reconcile_relay().await { + tracing::warn!("Daemon Relay reconnect failed: {error}"); + } + } + }); + let mut exit_error = None; let mut expired_check = tokio::time::interval(Duration::from_secs(5)); expired_check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); loop { tokio::select! { + result = &mut management_task => { + tracing::error!("Daemon management server stopped: {result:?}"); + exit_error = Some(anyhow!("Daemon management server stopped unexpectedly")); + break; + } + _ = remote.wait_for_shutdown_request() => { + tracing::info!("Daemon management shutdown requested"); + break; + } _ = shutdown_signal() => { tracing::info!("Daemon shutdown signal received"); break; @@ -72,11 +100,17 @@ pub(crate) async fn run_daemon() -> Result<()> { } } + reconnect_task.abort(); + management_task.abort(); + remote.shutdown().await; runtime.account_routing().stop_device_routing().await; pid::remove_pid_file(); crate::shutdown_mcp_servers().await; tracing::info!("openbitfun daemon stopped"); - Ok(()) + match exit_error { + Some(error) => Err(error), + None => Ok(()), + } } #[cfg(unix)] diff --git a/src/apps/cli/src/main.rs b/src/apps/cli/src/main.rs index b362f98007..c57d3b61a1 100644 --- a/src/apps/cli/src/main.rs +++ b/src/apps/cli/src/main.rs @@ -31,6 +31,7 @@ mod plugin_host_activation; mod product_assembly; mod prompt_stash; mod prompts; +mod remote_control; mod root_handlers; mod runtime; mod self_update; @@ -993,6 +994,7 @@ async fn initialize_core_services_for_deployment( )?); // Restore on the executing host for TUI, exec, Shared and detached jobs alike. runtime.account_runtime().try_restore_session().await; + remote_control::install(&runtime); debug_assert!(runtime .product() .service_availability() diff --git a/src/apps/cli/src/peer_host/commands/product_control.rs b/src/apps/cli/src/peer_host/commands/product_control.rs index e0005cb1d2..af10dd1a05 100644 --- a/src/apps/cli/src/peer_host/commands/product_control.rs +++ b/src/apps/cli/src/peer_host/commands/product_control.rs @@ -14,12 +14,23 @@ use serde_json::Value; use crate::peer_host::args::request_value; use crate::peer_host::state::PeerHostState; -pub(crate) async fn invoke(state: &PeerHostState, args: &Value) -> Result { +pub(crate) async fn invoke(_state: &PeerHostState, args: &Value) -> Result { let mut request: ProductControlRequest = serde_json::from_value(request_value(args).clone()) .map_err(|error| format!("Invalid ProductControl request: {error}"))?; // Source is trusted transport metadata, never caller-controlled behavior. request.source = ProductControlSource::Peer; + if request.capability_id.as_deref() == Some("feature.remote-connect") { + if request.action == ProductControlAction::Execute { + openbitfun_product_domains::remote_control::RemoteControlRequest::from_operation( + request.operation_id.as_deref().unwrap_or_default(), + request.arguments.as_ref(), + )? + .ensure_direct_peer_safe()?; + } + return openbitfun_core::agentic::tools::openbitfun_control_host::invoke_openbitfun_control(request).await; + } + match request.action { ProductControlAction::List | ProductControlAction::Search => discover(&request), ProductControlAction::Get => { diff --git a/src/apps/cli/src/remote_control.rs b/src/apps/cli/src/remote_control.rs new file mode 100644 index 0000000000..74a680f3c9 --- /dev/null +++ b/src/apps/cli/src/remote_control.rs @@ -0,0 +1,321 @@ +//! CLI adapters for the shared Remote Connect owner and ProductControl tool. +//! +//! The daemon owns listeners. Interactive, Shared and headless Agent processes +//! use its authenticated local management endpoint instead of polling providers. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, OnceLock, Weak}; + +use anyhow::{anyhow, Result}; +use openbitfun_core::agentic::tools::openbitfun_control_config::global_shared_product_control_executor; +use openbitfun_core::agentic::tools::openbitfun_control_host::set_openbitfun_control_port; +use openbitfun_core::service::remote_connect::{ + bot, + control::{RemoteBotControl, RemoteConnectServiceHolder}, + embedded_relay_host::EmbeddedRelayHost, + relay_client::ConnectionState, + AccountClient, DeviceIdentity, QrGenerator, RemoteConnectConfig, RemoteConnectService, +}; +use openbitfun_product_domains::product_control::{ + capability, discover, validate_operation_arguments, ProductCapabilityOperationHandler, + ProductControlAction, ProductControlDeliveryProfile, ProductControlFuture, ProductControlPort, + ProductControlRequest, +}; +use openbitfun_product_domains::remote_control::{ + RemoteControlMethod, RemoteControlRequest, REMOTE_CONTROL_PROVIDER, +}; +use serde_json::{json, Value}; +use tokio::sync::{Mutex, RwLock}; + +use crate::runtime::CliRuntimeContext; + +static DAEMON_HOST: OnceLock> = OnceLock::new(); + +pub(crate) fn daemon_host() -> Option> { + DAEMON_HOST.get().cloned() +} + +pub(crate) fn install(runtime: &Arc) { + set_openbitfun_control_port(Arc::new(CliProductControlPort { + runtime: Arc::downgrade(runtime), + })); +} + +pub(crate) async fn activate_daemon( + runtime: &Arc, +) -> Result> { + let host = CliRemoteControlHost::new(runtime)?; + DAEMON_HOST + .set(host.clone()) + .map_err(|_| anyhow!("CLI Remote Connect daemon owner is already installed"))?; + let account = Arc::downgrade(runtime.account_runtime()); + bot::set_delegated_identity_provider(move || { + let account = account.clone(); + async move { + let account = account.upgrade()?; + let generation = account.account_context_generation(); + let (session, relay_url) = account + .read_account_context_for_generation(generation) + .await + .ok()?; + let delegated = AccountClient::new() + .delegate_token(&relay_url, &session) + .await + .ok()?; + account.account_context_is_current(generation).then_some(( + relay_url, + delegated.token, + delegated.device_secret.to_vec(), + )) + } + }); + 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}"); + } + Ok(host) +} + +pub(crate) async fn retire_daemon_account() { + if let Some(host) = daemon_host() { + host.shutdown().await; + } +} + +pub(crate) struct CliRemoteControlHost { + runtime: Weak, + service: RemoteConnectServiceHolder, + bots: RemoteBotControl, + relay_operation: Mutex<()>, + relay_enabled: AtomicBool, + relay_error: RwLock>, + shutdown_requested: tokio::sync::Notify, +} + +impl CliRemoteControlHost { + fn new(runtime: &Arc) -> Result> { + let service = Arc::new(RwLock::new(Some(RemoteConnectService::new( + RemoteConnectConfig::default(), + Arc::new(CliEmbeddedRelayUnavailable), + )?))); + Ok(Arc::new(Self { + runtime: Arc::downgrade(runtime), + bots: RemoteBotControl::new(service.clone()), + service, + relay_operation: Mutex::new(()), + relay_enabled: AtomicBool::new(true), + relay_error: RwLock::new(None), + shutdown_requested: tokio::sync::Notify::new(), + })) + } + + fn runtime(&self) -> Result> { + self.runtime + .upgrade() + .ok_or_else(|| anyhow!("CLI runtime is shutting down")) + } + + 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) { + return Ok(()); + } + let runtime = self.runtime()?; + if !matches!( + runtime.account_routing().connection_state().await, + ConnectionState::Disconnected + ) { + return Ok(()); + } + let device = DeviceIdentity::from_current_machine()?; + let result = runtime + .account_runtime() + .restore_device_routing(&device.device_name) + .await; + *self.relay_error.write().await = result.as_ref().err().map(ToString::to_string); + result + } + + pub(crate) async fn execute_for_account( + &self, + request: RemoteControlRequest, + expected_user: &str, + ) -> Result { + anyhow::ensure!(self.runtime()?.account_runtime().account_info().await?.user_id == expected_user, + "account_changed: This chat and the daemon have different account identities; reload this chat before managing Remote Connect"); + self.execute(request).await + } + + pub(crate) async fn execute(&self, request: RemoteControlRequest) -> Result { + let runtime = self.runtime()?; + let account = runtime.account_runtime(); + if !request.is_readonly() { + account.read_account_context().await?; + } + match request { + RemoteControlRequest::Status => { + let mut result = self.bots.status().await?; + let info = account.account_info().await?; + 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), + "routingState": format!("{:?}", runtime.account_routing().connection_state().await).to_ascii_lowercase(), + "relayUrl":info.relay_url, "lastError":self.relay_error.read().await.clone(), + }); + result["lan"] = json!({"available":false,"reason":"This CLI build uses the configured Relay for Mobile Web; it does not host an embedded LAN Relay"}); + Ok(result) + } + RemoteControlRequest::Start { method: RemoteControlMethod::MobileWeb, .. } => { + let _operation = self.relay_operation.lock().await; + self.relay_enabled.store(true, Ordering::Release); + self.connect_relay_if_enabled().await?; + let info = account.account_info().await?; + let url = QrGenerator::build_device_url(&info.relay_url, &info.device_id)?; + Ok(json!({"started":true,"method":"mobile_web", "url":url, + "routingState":format!("{:?}", runtime.account_routing().connection_state().await).to_ascii_lowercase(), + "deviceId":info.device_id, "nextStep":"Open the URL in Mobile Web and sign in with the same OpenBitFun account. The daemon owns the session and continues when this chat disconnects."})) + } + RemoteControlRequest::Stop { method: RemoteControlMethod::MobileWeb } => { + let _operation = self.relay_operation.lock().await; + self.relay_enabled.store(false, Ordering::Release); + runtime.account_routing().stop_device_routing().await; + Ok(json!({"stopped":true,"method":"mobile_web", "affects":"Mobile Web and Peer Device routing on this daemon; bot listeners remain active", "until":"next daemon restart or explicit start"})) + } + RemoteControlRequest::Start { method: RemoteControlMethod::Lan, .. } + | RemoteControlRequest::Stop { method: RemoteControlMethod::Lan } => { + Err(anyhow!("unsupported: This CLI build has no embedded LAN Relay. Use method mobile_web with the configured Relay; no local or controller fallback was performed")) + } + other => self.bots.execute(other).await, + } + } + + pub(crate) fn request_shutdown(&self) { + self.shutdown_requested.notify_one(); + } + + pub(crate) async fn wait_for_shutdown_request(&self) { + self.shutdown_requested.notified().await; + } + + pub(crate) async fn shutdown(&self) { + self.relay_enabled.store(false, Ordering::Release); + if let Some(service) = self.service.read().await.as_ref() { + service.set_bot_account(None).await; + } + } +} + +struct CliEmbeddedRelayUnavailable; +#[async_trait::async_trait] +impl EmbeddedRelayHost for CliEmbeddedRelayUnavailable { + async fn start(&self, _: u16, _: Option) -> Result<()> { + Err(anyhow!( + "unsupported: Embedded LAN Relay is not available in this CLI host" + )) + } + async fn stop(&self) {} +} + +struct CliProductControlPort { + runtime: Weak, +} + +impl ProductControlPort for CliProductControlPort { + fn invoke<'a>(&'a self, request: ProductControlRequest) -> ProductControlFuture<'a> { + Box::pin(async move { + let runtime = self + .runtime + .upgrade() + .ok_or("CLI product host is unavailable")?; + match request.action { + ProductControlAction::List | ProductControlAction::Search => discover(&request), + ProductControlAction::Get => { + let id = request + .capability_id + .as_deref() + .ok_or("capabilityId is required")?; + let mut result = global_shared_product_control_executor() + .await? + .inspect(id, ProductControlDeliveryProfile::Cli) + .await?; + if id == "feature.remote-connect" { + result["operationAvailability"] = Value::Object( + capability(id)? + .operations + .iter() + .map(|operation| { + ( + operation.id.clone(), + json!({"status":"available", "owner":"cli-daemon"}), + ) + }) + .collect(), + ); + result["controlAvailability"] = json!({"status":"available", "adapter":"cli-daemon", "readBack":true, "actions":{"execute":{"status":"available"}}}); + result["remoteConnect"] = match crate::daemon::control::invoke( + &runtime, + RemoteControlRequest::Status, + ) + .await + { + Ok(status) => status, + Err(error) => { + json!({"status":"unavailable", "reason":error.to_string()}) + } + }; + } + Ok(result) + } + ProductControlAction::Configure => { + global_shared_product_control_executor() + .await? + .configure(&request) + .await + } + ProductControlAction::Open => Err( + "product_control_presentation_unavailable: CLI has no presentation surface" + .into(), + ), + ProductControlAction::Execute => { + let capability = capability( + request + .capability_id + .as_deref() + .ok_or("capabilityId is required")?, + )?; + let operation = capability + .operations + .iter() + .find(|op| Some(op.id.as_str()) == request.operation_id.as_deref()) + .ok_or("Unknown product-control operation")?; + validate_operation_arguments( + &operation.input_schema, + request.arguments.as_ref(), + )?; + let ProductCapabilityOperationHandler::Provider { + provider_id, + operation_id, + } = &operation.handler + else { + return Err("product_control_native_operation_unavailable: CLI has no provider for this operation".into()); + }; + if provider_id != REMOTE_CONTROL_PROVIDER { + return Err("product_control_native_operation_unavailable: CLI has no provider for this operation".into()); + } + let command = RemoteControlRequest::from_operation( + operation_id, + request.arguments.as_ref(), + )?; + crate::daemon::control::invoke(&runtime, command) + .await + .map_err(|error| error.to_string()) + } + } + }) + } +} diff --git a/src/apps/cli/src/ui/theme.rs b/src/apps/cli/src/ui/theme.rs index c721f71d56..aba3e8c421 100644 --- a/src/apps/cli/src/ui/theme.rs +++ b/src/apps/cli/src/ui/theme.rs @@ -66,6 +66,12 @@ impl Appearance { } } +/// QR modules are machine-readable data. Theme accents and terminal defaults +/// cannot guarantee the dark modules and light quiet zone required by scanners. +pub(super) fn qr_code_style() -> Style { + Style::default().fg(Color::Black).bg(Color::White) +} + pub(crate) fn resolve_effective_color_scheme(preference: &str) -> EffectiveColorScheme { if std::env::var_os("NO_COLOR").is_some() { return EffectiveColorScheme::Monochrome; diff --git a/src/apps/cli/src/ui/tool_cards.rs b/src/apps/cli/src/ui/tool_cards.rs index 31541d415e..a614468219 100644 --- a/src/apps/cli/src/ui/tool_cards.rs +++ b/src/apps/cli/src/ui/tool_cards.rs @@ -131,6 +131,8 @@ fn tool_display_mode(tool_name: &str, tool_state: &ToolDisplayState) -> ToolDisp // Always block tools "TodoWrite" | "AskUserQuestion" | "CreatePlan" => ToolDisplayMode::Block, + "OpenBitFunControl" if login_qr_result(tool_state).is_some() => ToolDisplayMode::Block, + // MCP tools: inline when pending, block when has output _ if tool_name.starts_with("mcp_") => { if tool_state.result.is_some() { @@ -635,6 +637,9 @@ fn render_block_dispatch( available_width, ), "Delete" => render_delete_block(tool_state, theme, focused, spinner_frame, available_width), + "OpenBitFunControl" if login_qr_result(tool_state).is_some() => { + render_login_qr_block(tool_state, theme, focused, spinner_frame, available_width) + } "Task" | "AgentSpawn" => { render_task_block(tool_state, theme, focused, spinner_frame, available_width) } @@ -666,6 +671,79 @@ fn render_block_dispatch( } } +fn login_qr_result(tool_state: &ToolDisplayState) -> Option<&serde_json::Value> { + let result = tool_state.metadata.as_ref()?; + (tool_state.status == ToolDisplayStatus::Success + && result + .get("loginStatus") + .and_then(|value| value.as_str()) + .is_some() + && (result + .get("qrTerminal") + .and_then(|value| value.as_str()) + .is_some() + || result + .get("qrImageUrl") + .and_then(|value| value.as_str()) + .is_some())) + .then_some(result) +} + +fn render_login_qr_block( + tool_state: &ToolDisplayState, + theme: &Theme, + focused: bool, + spinner_frame: &str, + available_width: u16, +) -> ToolCardRenderOutput { + let result = login_qr_result(tool_state).expect("QR display mode requires login metadata"); + let max_width = block_content_max_width(available_width); + let mut content_lines = Vec::new(); + let qr = result.get("qrTerminal").and_then(|value| value.as_str()); + let rows: Vec<&str> = qr.unwrap_or_default().lines().collect(); + let qr_width = rows.first().map_or(0, |line| line.chars().count()); + // QR versions are at most 177 modules, plus the 4-module quiet zone. + // Never wrap, trim, collapse, or interpret escape sequences in QR data. + let valid = (1..=185).contains(&qr_width) + && !rows.is_empty() + && rows.len() <= 93 + && rows.iter().all(|line| { + line.chars().count() == qr_width + && line.chars().all(|ch| matches!(ch, ' ' | '▀' | '▄' | '█')) + }); + let message = if valid && qr_width <= max_width { + "Scan with WeChat, then confirm on your phone. Use the latest QR shown.".to_string() + } else if valid { + format!( + "Widen the terminal to at least {} columns to show the QR without wrapping.", + qr_width + 8 + ) + } else { + "This login QR cannot be rendered in the terminal. Display qrImageUrl in a graphical client.".to_string() + }; + for line in wrap_display_lines(&message, max_width) { + content_lines.push(Line::from(Span::styled(line, theme.style(StyleKind::Info)))); + } + if valid && qr_width <= max_width { + content_lines.extend( + rows.into_iter().map(|line| { + Line::from(Span::styled(line.to_owned(), super::theme::qr_code_style())) + }), + ); + } + assemble_block(BlockAssembly { + title: "WeChat login", + content_lines, + theme, + is_running: false, + error: None, + focused, + tool_state, + spinner_frame, + available_width, + }) +} + fn filter_hmos_errors(stderr: &str) -> Vec<&str> { if stderr.trim().is_empty() { return Vec::new(); @@ -2119,7 +2197,103 @@ fn capitalize_first(s: &str) -> String { #[cfg(test)] mod tests { - use super::skill_display_name; + use super::*; + use ratatui::{backend::TestBackend, style::Color, widgets::List, Terminal}; + + fn login_qr_state() -> ToolDisplayState { + let qr = openbitfun_core::service::remote_connect::QrGenerator::present_content( + "https://example.test/wechat-login?code=terminal-fixture", + ) + .unwrap(); + ToolDisplayState { + tool_id: "login-qr-fixture".into(), + tool_name: "OpenBitFunControl".into(), + // History replay does not retain the original tool parameters. + parameters: serde_json::Value::Null, + status: ToolDisplayStatus::Success, + result: Some("Model summary without the QR".into()), + progress_message: None, + duration_ms: None, + metadata: Some(serde_json::json!({ + "loginStatus": "awaiting_scan", "qrTerminal": qr.terminal, + "qrImageUrl": qr.image_url, "sessionKey": "private-login-session" + })), + subagent_progress: None, + } + } + + #[test] + fn login_qr_is_complete_and_scannable_without_expanding_or_model_transcription() { + let state = login_qr_state(); + let qr = state.metadata.as_ref().unwrap()["qrTerminal"] + .as_str() + .unwrap(); + let expected: Vec<_> = qr.lines().collect(); + for theme in [Theme::dark(), Theme::light(), Theme::monochrome()] { + for expanded in [false, true] { + let rendered = render_tool_card_inner(&state, &theme, expanded, true, "", 80); + assert!(!rendered + .plain_lines + .join("\n") + .contains("private-login-session")); + let height = rendered.items.len() as u16; + let mut terminal = Terminal::new(TestBackend::new(80, height)).unwrap(); + terminal + .draw(|frame| frame.render_widget(List::new(rendered.items), frame.area())) + .unwrap(); + let buffer = terminal.backend().buffer(); + let mut actual = Vec::new(); + for y in 0..height { + // The actual List renderer must preserve foreground/background, + // including all-space rows in the QR's light quiet zone. + if buffer[(7, y)].fg == Color::Black && buffer[(7, y)].bg == Color::White { + let mut row = String::new(); + for x in 7..7 + expected[0].chars().count() as u16 { + let cell = &buffer[(x, y)]; + assert_eq!((cell.fg, cell.bg), (Color::Black, Color::White)); + row.push_str(cell.symbol()); + } + actual.push(row); + } + } + assert_eq!(actual, expected); + } + } + } + + #[test] + fn narrow_terminal_hides_qr_until_resize_instead_of_corrupting_modules() { + clear_tool_card_cache(); + let state = login_qr_state(); + let qr = state.metadata.as_ref().unwrap()["qrTerminal"] + .as_str() + .unwrap(); + let width = qr.lines().next().unwrap().chars().count() as u16; + let narrow = render_tool_card(&state, &Theme::dark(), false, false, "", width + 7); + let text = narrow.plain_lines.join("\n"); + assert!(text.contains("Widen the terminal")); + assert!(!text.contains('█')); + let resized = render_tool_card(&state, &Theme::dark(), false, false, "", width + 8); + assert!(resized.plain_lines.join("\n").contains('█')); + clear_tool_card_cache(); + } + + #[test] + fn image_only_and_invalid_qr_data_have_explicit_fallbacks() { + let mut state = login_qr_state(); + for value in [ + serde_json::Value::Null, + serde_json::json!("█\u{1b}[2J"), + serde_json::json!("█\n██"), + ] { + state.metadata.as_mut().unwrap()["qrTerminal"] = value; + let rendered = render_tool_card_inner(&state, &Theme::dark(), false, false, "", 80); + let text = rendered.plain_lines.join("\n"); + assert!(text.contains("graphical client")); + assert!(!text.contains('\u{1b}')); + assert!(!text.contains('█')); + } + } #[test] fn skill_name_is_read_from_command_parameter() { diff --git a/src/apps/desktop/src/api/peer_host_invoke.rs b/src/apps/desktop/src/api/peer_host_invoke.rs index fdf83aa875..2e899e30a2 100644 --- a/src/apps/desktop/src/api/peer_host_invoke.rs +++ b/src/apps/desktop/src/api/peer_host_invoke.rs @@ -346,6 +346,35 @@ pub async fn dispatch(command: &str, args: Value) -> HostInvokeBridgeResult { PeerHostVerdict::Execute => {} } + if command == "product_control_invoke" { + use openbitfun_product_domains::{ + product_control::{ProductControlAction, ProductControlRequest}, + remote_control::RemoteControlRequest, + }; + let payload = args.get("request").unwrap_or(&args); + let validation = serde_json::from_value::(payload.clone()) + .map_err(|error| error.to_string()) + .and_then(|request| { + if request.capability_id.as_deref() == Some("feature.remote-connect") + && request.action == ProductControlAction::Execute + { + RemoteControlRequest::from_operation( + request.operation_id.as_deref().unwrap_or_default(), + request.arguments.as_ref(), + )? + .ensure_direct_peer_safe()?; + } + Ok(()) + }); + if let Err(error) = validation { + return HostInvokeBridgeResult { + ok: false, + value: None, + error: Some(error), + }; + } + } + let app = match account_app_handle() { Some(app) => app.clone(), None => { diff --git a/src/apps/desktop/src/api/remote_connect_api.rs b/src/apps/desktop/src/api/remote_connect_api.rs index 8bf601aef6..bf4eb99b5e 100644 --- a/src/apps/desktop/src/api/remote_connect_api.rs +++ b/src/apps/desktop/src/api/remote_connect_api.rs @@ -1351,6 +1351,96 @@ fn get_service_holder() -> &'static Arc>> { RelayRoute::Official.service() } +fn bot_control() -> &'static openbitfun_core::service::remote_connect::control::RemoteBotControl { + static CONTROL: OnceLock = + OnceLock::new(); + CONTROL.get_or_init(|| { + openbitfun_core::service::remote_connect::control::RemoteBotControl::new( + get_service_holder().clone(), + ) + }) +} + +/// ProductControl adapter: all mutations execute on this host without requiring +/// a visible window. Account login remains a separate user-owned flow. +pub(crate) async fn execute_remote_control( + request: openbitfun_product_domains::remote_control::RemoteControlRequest, +) -> Result { + use openbitfun_product_domains::remote_control::{ + RemoteControlMethod as Method, RemoteControlRequest as Request, + }; + use serde_json::json; + ensure_service().await?; + if matches!(request, Request::Status) { + let mut status = bot_control() + .status() + .await + .map_err(|error| error.to_string())?; + status["host"] = json!({"kind":"desktop"}); + status["connections"] = serde_json::to_value(remote_connect_status().await?) + .map_err(|error| error.to_string())?; + return Ok(status); + } + // Do not open an unanswerable host-only login dialog from a remote Agent. + read_account_context().await.map_err(|_| { + "account_required: Sign in to OpenBitFun on the executing Desktop host first".to_string() + })?; + match request { + Request::Start { + method: Method::MobileWeb, + .. + } => { + let result = remote_connect_start(StartRemoteConnectRequest { + method: "openbitfun_server".into(), + lan_ip: None, + }) + .await?; + serde_json::to_value(result).map_err(|error| error.to_string()) + } + Request::Start { + method: Method::Lan, + lan_ip, + } => { + let result = remote_connect_start(StartRemoteConnectRequest { + method: "lan".into(), + lan_ip, + }) + .await?; + serde_json::to_value(result).map_err(|error| error.to_string()) + } + Request::Stop { + method: Method::MobileWeb, + } => { + remote_connect_stop(Some(StopRemoteConnectRequest { + method: "openbitfun_server".into(), + })) + .await?; + Ok(json!({"stopped":true,"method":"mobile_web"})) + } + Request::Stop { + method: Method::Lan, + } => { + remote_connect_stop(Some(StopRemoteConnectRequest { + method: "lan".into(), + })) + .await?; + Ok(json!({"stopped":true,"method":"lan"})) + } + other => { + let generation = account_context_generation(); + let _account_guard = lock_account_operation(generation).await?; + let (session, _) = read_account_context_for_generation(generation).await?; + if let Some(service) = get_service_holder().read().await.as_ref() { + service.set_bot_account(Some(session.user_id)).await; + } + bot_control() + .execute(other) + .await + .map_err(|error| error.to_string()) + } + } +} + /// Called from Tauri setup to register the resolved resource directory path /// for the bundled mobile-web files. pub fn set_mobile_web_resource_path(path: PathBuf) { @@ -1550,8 +1640,6 @@ fn new_remote_connect_service(config: RemoteConnectConfig) -> anyhow::Result "feishu", + ConnectionMethod::BotTelegram => "telegram", + _ => "weixin", + }; + return bot_control() + .start_connection(bot_type) .await - .map_err(|e| format!("start remote connect: {e}")); + .map_err(|error| error.to_string()); } if matches!(method, ConnectionMethod::Lan { .. }) { return relay_routes::start_lan(method).await; @@ -2096,13 +2166,12 @@ pub async fn remote_connect_stop(request: Option) -> R #[tauri::command] pub async fn remote_connect_stop_bot() -> Result<(), String> { - let holder = get_service_holder(); - let guard = holder.read().await; - if let Some(service) = guard.as_ref() { - service.stop_bots().await; + for method in ["weixin", "telegram", "feishu"] { + bot_control() + .stop(method) + .await + .map_err(|error| error.to_string())?; } - // Remove persistence so the bot is not auto-restored - bot::update_bot_persistence(|data| data.connections.clear()); Ok(()) } @@ -2199,9 +2268,7 @@ pub struct WeixinQrPollRequest { #[tauri::command] pub async fn remote_connect_configure_bot(request: ConfigureBotRequest) -> Result<(), String> { - let holder = get_service_holder(); - let mut guard = holder.write().await; - + ensure_service().await?; let bot_config = match request.bot_type.as_str() { "feishu" => BotConfig::Feishu { app_id: request.app_id.unwrap_or_default(), @@ -2218,31 +2285,10 @@ pub async fn remote_connect_configure_bot(request: ConfigureBotRequest) -> Resul _ => return Err(format!("unknown bot type: {}", request.bot_type)), }; - if guard.is_none() { - let config = match bot_config { - BotConfig::Feishu { .. } => RemoteConnectConfig { - mobile_web_dir: detect_mobile_web_dir(), - bot_feishu: Some(bot_config), - ..RemoteConnectConfig::default() - }, - BotConfig::Telegram { .. } => RemoteConnectConfig { - mobile_web_dir: detect_mobile_web_dir(), - bot_telegram: Some(bot_config), - ..RemoteConnectConfig::default() - }, - BotConfig::Weixin { .. } => RemoteConnectConfig { - mobile_web_dir: detect_mobile_web_dir(), - bot_weixin: Some(bot_config), - ..RemoteConnectConfig::default() - }, - }; - let service = new_remote_connect_service(config).map_err(|e| format!("init: {e}"))?; - *guard = Some(service); - } else if let Some(service) = guard.as_mut() { - service.update_bot_config(bot_config); - } - - Ok(()) + bot_control() + .configure(bot_config) + .await + .map_err(|error| error.to_string()) } #[tauri::command] diff --git a/src/apps/desktop/src/openbitfun_control_host.rs b/src/apps/desktop/src/openbitfun_control_host.rs index b6d3b4d226..5c05b97e1d 100644 --- a/src/apps/desktop/src/openbitfun_control_host.rs +++ b/src/apps/desktop/src/openbitfun_control_host.rs @@ -568,6 +568,16 @@ async fn inspect_desktop( }), ); } + if capability_id == "feature.remote-connect" { + let status = crate::api::remote_connect_api::execute_remote_control( + openbitfun_product_domains::remote_control::RemoteControlRequest::Status, + ) + .await; + option_values.insert( + "remoteConnect".into(), + status.unwrap_or_else(|error| json!({"status":"unavailable", "reason":error})), + ); + } if capability_id == "setting.application.pet" { let provider_state = match companion_state(&state).await { Ok(value) => value, @@ -845,6 +855,7 @@ async fn configure_desktop_provider_option( enum DesktopProviderOperation { MiniApp(miniapps::Operation), Mcp(openbitfun_core::service::mcp::control::MCPControlOperation), + RemoteConnect(&'static str), ListCompanionPets, UseCompanionPet, DeleteCompanionPet, @@ -855,6 +866,18 @@ fn desktop_provider_operation( operation_id: &str, ) -> Option { match (provider_id, operation_id) { + ("remote-connect", id) => [ + "status", + "start", + "stop", + "configure-bot", + "weixin-login-start", + "weixin-login-poll", + "set-bot-verbose", + ] + .into_iter() + .find(|operation| *operation == id) + .map(DesktopProviderOperation::RemoteConnect), ("miniapp", id) => miniapps::operation(id).map(DesktopProviderOperation::MiniApp), ("mcp", id) => { openbitfun_core::service::mcp::control::operation(id).map(DesktopProviderOperation::Mcp) @@ -893,6 +916,13 @@ async fn execute_desktop_provider_operation( ) -> Result { let state = app.state::(); match operation { + DesktopProviderOperation::RemoteConnect(operation) => { + let request = + openbitfun_product_domains::remote_control::RemoteControlRequest::from_operation( + operation, arguments, + )?; + crate::api::remote_connect_api::execute_remote_control(request).await + } DesktopProviderOperation::Mcp(operation) => { let mut result = state .mcp_service diff --git a/src/crates/assembly/agent-content/prompts/agents/claw_mode.md b/src/crates/assembly/agent-content/prompts/agents/claw_mode.md index 4a2df8e54d..c98f9ccfd4 100644 --- a/src/crates/assembly/agent-content/prompts/agents/claw_mode.md +++ b/src/crates/assembly/agent-content/prompts/agents/claw_mode.md @@ -14,6 +14,23 @@ When a first-class tool exists for an action, use the tool directly instead of a Use only tools in the current tool list. ControlHub handles browser pages and existing UI terminal signals; ComputerUse handles native apps, browser chrome and OS dialogs. Follow the shared browser and desktop guidance below. Do not load a separate browser-automation skill for these built-in capabilities. +# Remote Connect + +When `OpenBitFunControl` is available, use its search/get flow for Remote Connect +before starting or managing bots, Mobile Web, or LAN access. Execute the returned +operations on the current host. On CLI, the daemon owns persistent listeners and +can be started by the management tool; do not build a separate polling script. +The CLI TUI renders WeChat `qrTerminal` directly in the tool card; tell the user to +scan that card without retyping its QR. Other terminal surfaces can show `qrTerminal` +verbatim in a code block; on a graphical surface display `qrImageUrl`. +Poll the same login session, refresh the displayed QR +when the result supplies a new one, then give the user the returned bot pairing +code. QR login alone is not a running, paired bot. +Read status after changes and distinguish listening, awaiting pairing, stopped, +and failed states. Use the supported private credential-file flow for other bots; +never print or ask users to paste tokens into chat. A remote workspace's files are +not the executing host's credential files. Report unsupported methods as returned. + # Session Coordination For complex coding tasks or office-style multi-step tasks, prefer multi-session coordination when the required session tools are available. Otherwise, keep ownership in the current session. diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md index 32a127f339..251f3d64ce 100644 --- a/src/crates/assembly/core/AGENTS.md +++ b/src/crates/assembly/core/AGENTS.md @@ -632,3 +632,12 @@ For HTML preview workspace identity and shared resource-service wiring: ```bash cargo test --locked -p openbitfun-core --no-default-features --features remote-connect --lib service::filesystem::html_preview::tests ``` + +For Remote Connect bot restore eligibility and listener shutdown/status: + +```bash +cargo test --locked -p openbitfun-core --no-default-features --features remote-connect --lib -- service::remote_connect::control:: listener_lifecycle_tests +``` + +The lifecycle fixtures cover account/config replacement, explicit disablement, +and task release; real provider message delivery requires a signed-in host. diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/openbitfun_control_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/openbitfun_control_tool.rs index cc41cf1953..69dff77434 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/openbitfun_control_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/openbitfun_control_tool.rs @@ -310,7 +310,7 @@ impl Tool for OpenBitFunControlTool { async fn description(&self) -> OpenBitFunResult { Ok( - "Control OpenBitFun features and settings, including MCP servers. Prefer this tool over ComputerUse. Use the two-step flow: `list` or `search`, then `get` the matching capability and follow its schema and availability to `configure`, `execute`, or `open`. Open a root with capability_id only. destination.actionId is presentation metadata, never an item_id or operation_id. The catalog loads on demand; never guess IDs or values." + "Control OpenBitFun features and settings, including MCP servers and Remote Connect bots/Mobile Web. Prefer this tool over ComputerUse. Use the two-step flow: `list` or `search`, then `get` the matching capability and follow its schema and availability to `configure`, `execute`, or `open`. Open a root with capability_id only. destination.actionId is presentation metadata, never an item_id or operation_id. The catalog loads on demand; never guess IDs or values." .to_string(), ) } @@ -892,6 +892,41 @@ mod tests { } } + #[tokio::test] + async fn remote_connect_management_preserves_permissions_and_remote_path_scope() { + let tool = OpenBitFunControlTool::new(); + let status = json!({"action":"execute", "capability_id":"feature.remote-connect", "operation_id":"status"}); + assert!(tool.validate_input(&status, Some(&context())).await.result); + assert!(tool + .permission_intents(&status, &context()) + .unwrap() + .is_empty()); + let start = json!({"action":"execute", "capability_id":"feature.remote-connect", "operation_id":"start", "arguments":{"method":"weixin"}}); + assert!( + tool.validate_input(&start, Some(&remote_context())) + .await + .result + ); + assert!(!tool + .permission_intents(&start, &context()) + .unwrap() + .is_empty()); + let credential_file = json!({"action":"execute", "capability_id":"feature.remote-connect", "operation_id":"configure-bot", "arguments":{"method":"telegram", "credentialsFile":"/host/private.json"}}); + assert!( + tool.validate_input(&credential_file, Some(&context())) + .await + .result + ); + let remote = tool + .validate_input(&credential_file, Some(&remote_context())) + .await; + assert!(!remote.result); + assert!(remote + .message + .unwrap() + .contains("local OpenBitFun product-host path")); + } + #[tokio::test] async fn validates_the_discover_then_execute_contract() { let tool = OpenBitFunControlTool::new(); diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/mod.rs b/src/crates/assembly/core/src/service/remote_connect/bot/mod.rs index 8412bcfc1d..d7e87bdf1b 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/mod.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/mod.rs @@ -20,10 +20,11 @@ pub use openbitfun_services_integrations::remote_connect::bot::{ auto_push_failed_message, auto_push_intro, auto_push_skip_too_large_message, collect_auto_push_files, detect_mime_type, extract_computer_file_paths, extract_downloadable_file_paths, extract_output_file_references, format_file_size, - get_file_metadata, load_bot_persistence, read_workspace_file, resolve_workspace_path, - save_bot_persistence, update_bot_persistence, AutoPushFile, BotConfig, BotLanguage, - BotPairingInfo, BotPersistenceData, MenuItem, MenuItemStyle, MenuView, RemoteConnectFormState, - RemoteDeviceTarget, SavedBotConnection, WorkspaceFileContent, + get_file_metadata, load_bot_persistence, read_bot_credentials_file, read_workspace_file, + resolve_workspace_path, save_bot_persistence, try_load_bot_persistence, + try_update_bot_persistence, update_bot_persistence, AutoPushFile, BotConfig, BotLanguage, + BotListenerLease, BotPairingInfo, BotPersistenceData, MenuItem, MenuItemStyle, MenuView, + RemoteConnectFormState, RemoteDeviceTarget, SavedBotConnection, WorkspaceFileContent, }; use std::collections::HashMap; diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs index 794ba68b2d..3a509aa514 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs @@ -699,6 +699,10 @@ impl WeixinBot { self.api.notify_start().await } + pub fn requires_login(&self) -> bool { + self.api.requires_login() + } + pub async fn notify_stop(&self) -> Result<()> { self.api.notify_stop().await } diff --git a/src/crates/assembly/core/src/service/remote_connect/control.rs b/src/crates/assembly/core/src/service/remote_connect/control.rs new file mode 100644 index 0000000000..97786b299a --- /dev/null +++ b/src/crates/assembly/core/src/service/remote_connect/control.rs @@ -0,0 +1,548 @@ +//! Shared bot management used by Desktop commands and the CLI daemon. +//! +//! Hosts supply their authenticated account and the existing service instance. +//! Provider IO, chat routing and Agent execution remain in their existing owners. + +use super::{bot, ConnectionMethod, ConnectionResult, RemoteConnectService}; +use anyhow::{anyhow, Result}; +use openbitfun_product_domains::remote_control::RemoteControlRequest; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use tokio::sync::{Mutex, RwLock}; + +pub type RemoteConnectServiceHolder = Arc>>; + +struct Login { + account: (String, u64), + generation: u64, + started: std::time::Instant, + completed: Option, +} + +pub struct RemoteBotControl { + service: RemoteConnectServiceHolder, + mutation: Mutex<()>, + invitations: Mutex>, + restore_errors: Mutex>, + logins: Mutex>, + login_generation: AtomicU64, +} + +impl RemoteBotControl { + pub fn new(service: RemoteConnectServiceHolder) -> Self { + Self { + service, + mutation: Mutex::new(()), + invitations: Mutex::new(HashMap::new()), + restore_errors: Mutex::new(HashMap::new()), + logins: Mutex::new(HashMap::new()), + login_generation: AtomicU64::new(0), + } + } + + async fn account_scope(&self) -> Result<(String, u64)> { + self.service.read().await.as_ref() + .ok_or_else(|| anyhow!("Remote Connect host is unavailable"))? + .bot_account_scope().await + .ok_or_else(|| anyhow!("account_required: Sign in to OpenBitFun on the executing host before starting a bot")) + } + + pub async fn restore(&self, user_id: &str) -> Result<()> { + let _mutation = self.mutation.lock().await; + let data = bot::try_load_bot_persistence()?; + let holder = self.service.read().await; + let service = holder + .as_ref() + .ok_or_else(|| anyhow!("Remote Connect host is unavailable"))?; + service.set_bot_account(Some(user_id.into())).await; + for saved in &data.connections { + if !restore_eligible(&data, saved, user_id) { + continue; + } + if service.is_bot_running(&saved.bot_type).await { + continue; + } + match service.restore_bot(saved).await { + Ok(()) => { + self.restore_errors.lock().await.remove(&saved.bot_type); + } + Err(error) => { + // One unavailable channel must not prevent other channels or + // device routing from starting. Keep the saved connection. + log::warn!("Failed to restore {} bot: {error}", saved.bot_type); + self.restore_errors + .lock() + .await + .insert(saved.bot_type.clone(), error.to_string()); + } + } + } + Ok(()) + } + + pub async fn status(&self) -> Result { + let data = bot::try_load_bot_persistence()?; + let holder = self.service.read().await; + let service = holder.as_ref(); + let account = match service { + Some(service) => service.bot_account_scope().await, + None => None, + }; + let mut channels = Vec::new(); + for bot_type in ["weixin", "telegram", "feishu"] { + let saved = data.get(bot_type); + let paired = saved.is_some_and(|saved| { + saved.chat_state.paired + && configured_bot(&data, bot_type) + .as_ref() + .is_none_or(|config| same_config(config, &saved.config)) + && account + .as_ref() + .is_some_and(|(id, _)| *id == saved.account_user_id) + }); + let listener_running = match service { + Some(service) => service.is_bot_running(bot_type).await, + None => false, + }; + let login_required = match service { + Some(service) => service.bot_requires_login(bot_type).await, + None => false, + }; + let disabled = data.disabled_bots.iter().any(|id| id == bot_type); + channels.push(json!({ + "method": bot_type, + "configured": configured_bot(&data, bot_type).is_some() || paired, + "paired": paired, + "listenerRunning": listener_running, + "loginRequired": login_required, + "state": if login_required { "login_required" } else if listener_running { if paired { "listening" } else { "awaiting_pairing" } } else { "stopped" }, + "lastError": if login_required { Some("WeChat credentials expired; use weixin-login-start to sign in again") } else { None }, + "restoreOnRestart": paired && !disabled, + "requiresPairing": configured_bot(&data, bot_type).is_some() && !paired, + "lastRestoreError": self.restore_errors.lock().await.get(bot_type).cloned(), + })); + } + Ok(json!({ "bots": channels, "botVerbose": data.verbose_mode, + "listenerStatusMeaning": "listenerRunning reports a live host task, including network retries; it does not assert a verified message round trip" })) + } + + pub async fn execute(&self, request: RemoteControlRequest) -> Result { + match request { + RemoteControlRequest::Status => self.status().await, + RemoteControlRequest::Start { method, .. } => { + let bot_type = method + .bot_type() + .ok_or_else(|| anyhow!("Mobile Web is managed by the host Relay adapter"))?; + let _mutation = self.mutation.lock().await; + self.start_locked(bot_type).await + } + RemoteControlRequest::Stop { method } => { + let bot_type = method + .bot_type() + .ok_or_else(|| anyhow!("Mobile Web is managed by the host Relay adapter"))?; + self.stop(bot_type).await?; + self.status().await + } + RemoteControlRequest::ConfigureBot { + method, + credentials_file, + } => { + let bot_type = method + .bot_type() + .ok_or_else(|| anyhow!("configure-bot requires a bot method"))?; + let scope = self.account_scope().await?; + let config = bot::read_bot_credentials_file(credentials_file.into()).await?; + anyhow::ensure!( + config.bot_type() == bot_type, + "Credential file does not match the requested bot method" + ); + let _mutation = self.mutation.lock().await; + anyhow::ensure!( + self.account_scope().await? == scope, + "Account changed while reading bot credentials" + ); + if bot_type == "weixin" { + self.login_generation.fetch_add(1, Ordering::AcqRel); + } + self.configure_locked(config).await?; + self.status().await + } + RemoteControlRequest::WeixinLoginStart => self.weixin_login_start().await, + RemoteControlRequest::WeixinLoginPoll { + session_key, + verify_code, + } => self.weixin_login_poll(&session_key, verify_code).await, + RemoteControlRequest::SetBotVerbose { enabled } => { + let _mutation = self.mutation.lock().await; + bot::try_update_bot_persistence(|data| data.verbose_mode = enabled)?; + self.status().await + } + } + } + + /// Also used by the existing GUI secret-entry adapter. Credentials never + /// enter ProductControl responses or discovery. + pub async fn configure(&self, config: bot::BotConfig) -> Result<()> { + let _mutation = self.mutation.lock().await; + if config.bot_type() == "weixin" { + self.login_generation.fetch_add(1, Ordering::AcqRel); + } + self.configure_locked(config).await + } + + async fn configure_locked(&self, config: bot::BotConfig) -> Result<()> { + config.validate()?; + let bot_type = config.bot_type(); + let data = bot::try_load_bot_persistence()?; + let unchanged = configured_bot(&data, bot_type) + .as_ref() + .is_some_and(|previous| { + serde_json::to_value(previous).ok() == serde_json::to_value(&config).ok() + }); + let _ownership = if !unchanged { + if let Some(service) = self.service.read().await.as_ref() { + service.stop_bot(bot_type).await?; + } + self.invitations.lock().await.remove(bot_type); + Some(bot::BotListenerLease::acquire(bot_type)?) + } else { + None + }; + bot::try_update_bot_persistence(|data| { + store_config(data, &config); + if !unchanged && !data.disabled_bots.iter().any(|id| id == bot_type) { + data.disabled_bots.push(bot_type.into()); + } + })?; + self.service + .write() + .await + .as_mut() + .ok_or_else(|| anyhow!("Remote Connect host is unavailable"))? + .update_bot_config(config); + Ok(()) + } + + async fn start_locked(&self, bot_type: &str) -> Result { + let scope = self.account_scope().await?; + let data = bot::try_load_bot_persistence()?; + { + let holder = self.service.read().await; + let service = holder + .as_ref() + .ok_or_else(|| anyhow!("Remote Connect host is unavailable"))?; + if service.is_bot_running(bot_type).await { + anyhow::ensure!(!service.bot_requires_login(bot_type).await, + "weixin_login_required: The provider rejected the saved credentials; use weixin-login-start to sign in again"); + let effective = self.status_without_holder(&data, bot_type, true, &scope.0); + let connection = if effective["paired"] == true { + None + } else { + self.invitations.lock().await.get(bot_type).cloned() + }; + return Ok( + json!({ "alreadyRunning": true, "connection": connection, "effectiveState":effective }), + ); + } + } + let config = configured_bot(&data, bot_type) + .or_else(|| data.get(bot_type).filter(|saved| saved.account_user_id == scope.0).map(|saved| saved.config.clone())) + .ok_or_else(|| anyhow!(if bot_type == "weixin" { + "weixin_login_required: Use weixin-login-start, show its QR image, then weixin-login-poll to complete login and start listening" + } else { + "bot_credentials_required: Configure this bot through Remote Connect or configure-bot with a private credential file on the executing host" + }))?; + config.validate()?; + { + let mut holder = self.service.write().await; + holder + .as_mut() + .ok_or_else(|| anyhow!("Remote Connect host is unavailable"))? + .update_bot_config(config.clone()); + } + let holder = self.service.read().await; + let service = holder + .as_ref() + .ok_or_else(|| anyhow!("Remote Connect host is unavailable"))?; + anyhow::ensure!( + service.bot_account_scope().await.as_ref() == Some(&scope), + "Account changed before bot start" + ); + let saved = data.get(bot_type).filter(|saved| { + saved.account_user_id == scope.0 + && saved.chat_state.paired + && serde_json::to_value(&saved.config).ok() == serde_json::to_value(&config).ok() + }); + let connection = if let Some(saved) = saved { + service.restore_bot(saved).await?; + None + } else { + let result = service.start(bot_method(bot_type)?).await?; + self.invitations + .lock() + .await + .insert(bot_type.into(), result.clone()); + Some(result) + }; + if let Err(error) = bot::try_update_bot_persistence(|data| { + data.disabled_bots.retain(|id| id != bot_type); + store_config(data, &config); + }) { + service.stop_bot(bot_type).await?; + return Err(error); + } + self.restore_errors.lock().await.remove(bot_type); + anyhow::ensure!(service.is_bot_running(bot_type).await, + "bot_listener_stopped: The provider listener exited during startup; inspect status before retrying"); + Ok(json!({ "started": true, "connection": connection, + "effectiveState": self.status_without_holder(&data, bot_type, true, &scope.0), + "nextStep": if connection.is_some() { "Send the returned 6-digit bot_pairing_code to the bot. The host is already listening; pairing then routes messages to the shared Claw runtime." } else { "The saved paired channel has resumed listening." } })) + } + + fn status_without_holder( + &self, + data: &bot::BotPersistenceData, + bot_type: &str, + running: bool, + account: &str, + ) -> Value { + json!({ "method": bot_type, "listenerRunning": running, + "paired": data.get(bot_type).is_some_and(|saved| saved.chat_state.paired && saved.account_user_id == account + && configured_bot(data, bot_type).as_ref().is_none_or(|config| same_config(config, &saved.config))) }) + } + + /// Preserve the legacy GUI response while sharing the lifecycle transaction. + pub async fn start_connection(&self, bot_type: &str) -> Result { + let _mutation = self.mutation.lock().await; + let result = self.start_locked(bot_type).await?; + if let Some(connection) = result.get("connection").filter(|value| !value.is_null()) { + return Ok(serde_json::from_value(connection.clone())?); + } + anyhow::ensure!(result.pointer("/effectiveState/paired").and_then(Value::as_bool) == Some(true), + "Bot is listening but its pairing invitation is unavailable; stop and start this channel to pair again"); + Ok(ConnectionResult { + method: bot_method(bot_type)?, + qr_data: None, + qr_svg: None, + qr_url: None, + bot_pairing_code: None, + bot_link: None, + pairing_state: super::PairingState::Connected, + }) + } + + pub async fn stop(&self, bot_type: &str) -> Result<()> { + bot_method(bot_type)?; + let _mutation = self.mutation.lock().await; + if bot_type == "weixin" { + self.login_generation.fetch_add(1, Ordering::AcqRel); + } + if let Some(service) = self.service.read().await.as_ref() { + service.stop_bot(bot_type).await?; + } + let _ownership = bot::BotListenerLease::acquire(bot_type)?; + self.invitations.lock().await.remove(bot_type); + bot::try_update_bot_persistence(|data| { + if !data.disabled_bots.iter().any(|id| id == bot_type) { + data.disabled_bots.push(bot_type.into()); + } + })?; + Ok(()) + } + + pub async fn weixin_login_start(&self) -> Result { + let account = self.account_scope().await?; + let generation = self.login_generation.fetch_add(1, Ordering::AcqRel) + 1; + let data = bot::try_load_bot_persistence()?; + let form = data.form_state; + let response = bot::weixin::weixin_qr_start_with_existing( + Some(form.weixin_base_url), + Some(form.weixin_ilink_token), + Some(form.weixin_bot_account_id), + ) + .await?; + anyhow::ensure!( + self.account_scope().await? == account + && self.login_generation.load(Ordering::Acquire) == generation, + "WeChat login was replaced or the account changed" + ); + let mut logins = self.logins.lock().await; + logins.retain(|_, login| login.started.elapsed() < std::time::Duration::from_secs(300)); + logins.insert( + response.session_key.clone(), + Login { + account, + generation, + started: std::time::Instant::now(), + completed: None, + }, + ); + let qr = super::QrGenerator::present_content(&response.qr_image_url)?; + Ok( + json!({ "sessionKey": response.session_key, "qrImageUrl": qr.image_url, "qrTerminal": qr.terminal, + "loginStatus": "awaiting_scan", "message": response.message, + "nextStep": "The CLI TUI displays qrTerminal in the tool card; ask the user to scan it without retyping the QR. Other terminal surfaces may show qrTerminal verbatim; graphical surfaces display qrImageUrl. Then call weixin-login-poll with sessionKey. QR confirmation saves credentials on this host and starts the bot listener; send the returned pairing code in WeChat." }), + ) + } + + pub async fn weixin_login_poll( + &self, + session_key: &str, + verify_code: Option, + ) -> Result { + let scope = self.account_scope().await?; + let generation = self.login_generation.load(Ordering::Acquire); + { + let logins = self.logins.lock().await; + let login = logins.get(session_key).ok_or_else(|| { + anyhow!("WeChat login is unavailable on this host; start login again") + })?; + anyhow::ensure!( + login.account == scope && login.generation == generation, + "WeChat login was cancelled or belongs to a previous account" + ); + if let Some(result) = &login.completed { + return Ok(result.clone()); + } + } + // Do not hold the management lock during the provider's long poll. + // 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; + anyhow::ensure!( + self.account_scope().await? == scope + && self.login_generation.load(Ordering::Acquire) == generation, + "WeChat login was cancelled or the account changed" + ); + if let Some(result) = self + .logins + .lock() + .await + .get(session_key) + .and_then(|login| login.completed.clone()) + { + return Ok(result); + } + let mut result = json!({ "loginStatus": response.status, "message": response.message }); + if let Some(content) = response.qr_image_url.as_deref() { + let qr = super::QrGenerator::present_content(content)?; + result["qrImageUrl"] = json!(qr.image_url); + result["qrTerminal"] = json!(qr.terminal); + } + if matches!(response.status, bot::weixin::WeixinQrPollStatus::Confirmed) { + let config = bot::BotConfig::Weixin { + ilink_token: response + .ilink_token + .ok_or_else(|| anyhow!("Confirmed WeChat login has no credential"))?, + base_url: response + .base_url + .unwrap_or_else(|| "https://ilinkai.weixin.qq.com".into()), + bot_account_id: response + .bot_account_id + .ok_or_else(|| anyhow!("Confirmed WeChat login has no account id"))?, + }; + self.configure_locked(config).await?; + result["listener"] = self.start_locked("weixin").await?; + if let Some(login) = self.logins.lock().await.get_mut(session_key) { + login.completed = Some(result.clone()); + } + } + Ok(result) + } +} + +pub fn bot_method(bot_type: &str) -> Result { + match bot_type { + "weixin" => Ok(ConnectionMethod::BotWeixin), + "telegram" => Ok(ConnectionMethod::BotTelegram), + "feishu" => Ok(ConnectionMethod::BotFeishu), + _ => Err(anyhow!("Unknown bot type")), + } +} + +fn configured_bot(data: &bot::BotPersistenceData, bot_type: &str) -> Option { + let form = &data.form_state; + let config = match bot_type { + "weixin" => bot::BotConfig::Weixin { + ilink_token: form.weixin_ilink_token.clone(), + base_url: form.weixin_base_url.clone(), + bot_account_id: form.weixin_bot_account_id.clone(), + }, + "telegram" => bot::BotConfig::Telegram { + bot_token: form.telegram_bot_token.clone(), + }, + "feishu" => bot::BotConfig::Feishu { + app_id: form.feishu_app_id.clone(), + app_secret: form.feishu_app_secret.clone(), + }, + _ => return None, + }; + config.validate().ok().map(|_| config) +} + +fn store_config(data: &mut bot::BotPersistenceData, config: &bot::BotConfig) { + let form = &mut data.form_state; + match config { + bot::BotConfig::Weixin { + ilink_token, + base_url, + bot_account_id, + } => { + form.weixin_ilink_token = ilink_token.clone(); + form.weixin_base_url = base_url.clone(); + form.weixin_bot_account_id = bot_account_id.clone(); + } + bot::BotConfig::Telegram { bot_token } => form.telegram_bot_token = bot_token.clone(), + bot::BotConfig::Feishu { app_id, app_secret } => { + form.feishu_app_id = app_id.clone(); + form.feishu_app_secret = app_secret.clone(); + } + } +} + +fn same_config(left: &bot::BotConfig, right: &bot::BotConfig) -> bool { + serde_json::to_value(left).ok() == serde_json::to_value(right).ok() +} + +fn restore_eligible( + data: &bot::BotPersistenceData, + saved: &bot::SavedBotConnection, + user_id: &str, +) -> bool { + saved.chat_state.paired + && saved.account_user_id == user_id + && !data.disabled_bots.contains(&saved.bot_type) + && configured_bot(data, &saved.bot_type) + .as_ref() + .is_none_or(|config| same_config(config, &saved.config)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn restart_requires_enabled_pairing_for_current_account_and_credentials() { + let saved: bot::SavedBotConnection = serde_json::from_value(json!({ + "account_user_id":"alice", "bot_type":"telegram", "chat_id":"chat", + "config":{"bot_type":"telegram", "bot_token":"old-token"}, "connected_at":1, + "chat_state":{"chat_id":"chat", "paired":true, "current_workspace":"/legacy/workspace", "current_assistant":null, "current_session_id":"session"} + })).unwrap(); + let mut data = bot::BotPersistenceData::default(); + data.connections.push(saved.clone()); + assert!(restore_eligible(&data, &saved, "alice")); + assert!(!restore_eligible(&data, &saved, "bob")); + data.disabled_bots.push("telegram".into()); + assert!(!restore_eligible(&data, &saved, "alice")); + data.disabled_bots.clear(); + data.form_state.telegram_bot_token = "replacement-token".into(); + assert!(!restore_eligible(&data, &saved, "alice")); + data.form_state.telegram_bot_token = "old-token".into(); + assert!(restore_eligible(&data, &saved, "alice")); + let mut unpaired = saved; + unpaired.chat_state.paired = false; + assert!(!restore_eligible(&data, &unpaired, "alice")); + } +} 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 e8166e3ef9..eeb0d88ea6 100644 --- a/src/crates/assembly/core/src/service/remote_connect/mod.rs +++ b/src/crates/assembly/core/src/service/remote_connect/mod.rs @@ -10,6 +10,7 @@ pub mod account_runtime; pub mod bot; +pub mod control; pub mod embedded_relay_host; pub mod lan; mod permission_publication; @@ -130,11 +131,29 @@ pub struct ConnectionResult { /// Handle to a running bot (Telegram, Feishu, or Weixin). struct BotHandle { stop_tx: tokio::sync::watch::Sender, + task: Option>, } impl BotHandle { - fn stop(&self) { + fn is_running(&self) -> bool { + self.task.as_ref().is_some_and(|task| !task.is_finished()) + } + + async fn stop(mut self) { + let _ = self.stop_tx.send(true); + if let Some(task) = self.task.take() { + task.abort(); + let _ = task.await; + } + } +} + +impl Drop for BotHandle { + fn drop(&mut self) { let _ = self.stop_tx.send(true); + if let Some(task) = &self.task { + task.abort(); + } } } @@ -232,6 +251,15 @@ impl RemoteConnectService { ); } + /// Used to reject QR completions from a retired account without exposing credentials. + pub async fn bot_account_scope(&self) -> Option<(String, u64)> { + let account = self.bot_account_user_id.read().await.clone()?; + Some(( + account, + self.bot_account_identity_epoch.load(Ordering::Acquire), + )) + } + pub fn device_identity(&self) -> &DeviceIdentity { &self.device_identity } @@ -363,8 +391,9 @@ impl RemoteConnectService { // Stop any existing Telegram bot let generation = self.bot_telegram_slot.advance(); if let Some(handle) = self.bot_telegram_handle.write().await.take() { - handle.stop(); + handle.stop().await; } + let lease = bot::BotListenerLease::acquire("telegram")?; let tg_bot = Arc::new(bot::telegram::TelegramBot::new_fenced( bot::telegram::TelegramConfig { @@ -390,7 +419,8 @@ impl RemoteConnectService { *tg_bot_ref.write().await = Some(tg_bot.clone()); - tokio::spawn(async move { + let task = tokio::spawn(async move { + let _listener_lease = lease; let mut stop_rx = stop_rx; match bot_for_pair.wait_for_pairing(&mut stop_rx).await { Ok(chat_id) => { @@ -414,7 +444,10 @@ impl RemoteConnectService { } }); - *self.bot_telegram_handle.write().await = Some(BotHandle { stop_tx }); + *self.bot_telegram_handle.write().await = Some(BotHandle { + stop_tx, + task: Some(task), + }); "https://t.me/BotFather".to_string() } @@ -432,8 +465,9 @@ impl RemoteConnectService { { let generation = self.bot_feishu_slot.advance(); if let Some(handle) = self.bot_feishu_handle.write().await.take() { - handle.stop(); + handle.stop().await; } + let lease = bot::BotListenerLease::acquire("feishu")?; let fs_bot = Arc::new(bot::feishu::FeishuBot::new_fenced( bot::feishu::FeishuConfig { @@ -460,7 +494,8 @@ impl RemoteConnectService { *fs_bot_ref.write().await = Some(fs_bot.clone()); - tokio::spawn(async move { + let task = tokio::spawn(async move { + let _listener_lease = lease; let mut stop_rx = stop_rx; match bot_for_pair.wait_for_pairing(&mut stop_rx).await { Ok(chat_id) => { @@ -484,7 +519,10 @@ impl RemoteConnectService { } }); - *self.bot_feishu_handle.write().await = Some(BotHandle { stop_tx }); + *self.bot_feishu_handle.write().await = Some(BotHandle { + stop_tx, + task: Some(task), + }); "https://open.feishu.cn/app".to_string() } @@ -505,8 +543,9 @@ impl RemoteConnectService { }) if !ilink_token.is_empty() && !bot_account_id.is_empty() => { let generation = self.bot_weixin_slot.advance(); if let Some(handle) = self.bot_weixin_handle.write().await.take() { - handle.stop(); + handle.stop().await; } + let lease = bot::BotListenerLease::acquire("weixin")?; if let Some(previous_bot) = self.weixin_bot.write().await.take() { if let Err(err) = previous_bot.notify_stop().await { warn!("Weixin notify-stop failed during replacement: {err}"); @@ -545,7 +584,8 @@ impl RemoteConnectService { *wx_bot_ref.write().await = Some(wx_bot.clone()); - tokio::spawn(async move { + let task = tokio::spawn(async move { + let _listener_lease = lease; if let Err(err) = bot_for_pair.notify_start().await { warn!("Weixin notify-start failed; continuing: {err}"); } @@ -574,7 +614,10 @@ impl RemoteConnectService { } }); - *self.bot_weixin_handle.write().await = Some(BotHandle { stop_tx }); + *self.bot_weixin_handle.write().await = Some(BotHandle { + stop_tx, + task: Some(task), + }); "https://www.wechat.com".to_string() } @@ -620,8 +663,9 @@ impl RemoteConnectService { bot::BotConfig::Telegram { ref bot_token } => { let generation = self.bot_telegram_slot.advance(); if let Some(handle) = self.bot_telegram_handle.write().await.take() { - handle.stop(); + handle.stop().await; } + let lease = bot::BotListenerLease::acquire("telegram")?; let tg_bot = Arc::new(bot::telegram::TelegramBot::new_fenced( bot::telegram::TelegramConfig { @@ -647,12 +691,16 @@ impl RemoteConnectService { *self.bot_connected_info.write().await = Some(format!("Telegram({chat_id})")); let bot_for_loop = tg_bot.clone(); - tokio::spawn(async move { + let task = tokio::spawn(async move { + let _listener_lease = lease; info!("Telegram bot restored from persistence, starting message loop"); bot_for_loop.run_message_loop(stop_rx).await; }); - *self.bot_telegram_handle.write().await = Some(BotHandle { stop_tx }); + *self.bot_telegram_handle.write().await = Some(BotHandle { + stop_tx, + task: Some(task), + }); info!("Telegram bot restored for chat_id={chat_id}"); } bot::BotConfig::Feishu { @@ -661,8 +709,9 @@ impl RemoteConnectService { } => { let generation = self.bot_feishu_slot.advance(); if let Some(handle) = self.bot_feishu_handle.write().await.take() { - handle.stop(); + handle.stop().await; } + let lease = bot::BotListenerLease::acquire("feishu")?; let fs_bot = Arc::new(bot::feishu::FeishuBot::new_fenced( bot::feishu::FeishuConfig { @@ -688,12 +737,16 @@ impl RemoteConnectService { *self.bot_connected_info.write().await = Some(format!("Feishu({cid})")); let bot_for_loop = fs_bot.clone(); - tokio::spawn(async move { + let task = tokio::spawn(async move { + let _listener_lease = lease; info!("Feishu bot restored from persistence, starting message loop"); bot_for_loop.run_message_loop(stop_rx).await; }); - *self.bot_feishu_handle.write().await = Some(BotHandle { stop_tx }); + *self.bot_feishu_handle.write().await = Some(BotHandle { + stop_tx, + task: Some(task), + }); info!("Feishu bot restored for chat_id={}", saved.chat_id); } bot::BotConfig::Weixin { @@ -703,8 +756,9 @@ impl RemoteConnectService { } => { let generation = self.bot_weixin_slot.advance(); if let Some(handle) = self.bot_weixin_handle.write().await.take() { - handle.stop(); + handle.stop().await; } + let lease = bot::BotListenerLease::acquire("weixin")?; if let Some(previous_bot) = self.weixin_bot.write().await.take() { if let Err(err) = previous_bot.notify_stop().await { warn!("Weixin notify-stop failed during restore replacement: {err}"); @@ -743,7 +797,8 @@ impl RemoteConnectService { let bot_for_loop = wx_bot.clone(); let bot_for_notify = wx_bot.clone(); let bot_slot = self.bot_weixin_slot.clone(); - tokio::spawn(async move { + let task = tokio::spawn(async move { + let _listener_lease = lease; if let Err(err) = bot_for_notify.notify_start().await { warn!("Weixin notify-start failed during restore; continuing: {err}"); } @@ -756,7 +811,10 @@ impl RemoteConnectService { } }); - *self.bot_weixin_handle.write().await = Some(BotHandle { stop_tx }); + *self.bot_weixin_handle.write().await = Some(BotHandle { + stop_tx, + task: Some(task), + }); info!("Weixin bot restored for chat_id={}", saved.chat_id); } } @@ -790,22 +848,63 @@ impl RemoteConnectService { self.stop_bots_inner().await; } + /// Stop only this provider; other bots and Relay routes keep running. + pub async fn stop_bot(&self, bot_type: &str) -> Result<()> { + let _lifecycle = self.bot_lifecycle.lock().await; + match bot_type { + "telegram" => { + self.bot_telegram_slot.advance(); + if let Some(handle) = self.bot_telegram_handle.write().await.take() { + handle.stop().await; + } + *self.telegram_bot.write().await = None; + } + "feishu" => { + self.bot_feishu_slot.advance(); + if let Some(handle) = self.bot_feishu_handle.write().await.take() { + handle.stop().await; + } + *self.feishu_bot.write().await = None; + } + "weixin" => { + self.bot_weixin_slot.advance(); + if let Some(handle) = self.bot_weixin_handle.write().await.take() { + handle.stop().await; + } + if let Some(bot) = self.weixin_bot.write().await.take() { + if let Err(error) = bot.notify_stop().await { + warn!("Weixin notify-stop failed: {error}"); + } + } + } + _ => anyhow::bail!("Unknown bot type"), + } + let mut info = self.bot_connected_info.write().await; + if info + .as_deref() + .is_some_and(|info| info.to_ascii_lowercase().starts_with(bot_type)) + { + *info = None; + } + Ok(()) + } + async fn stop_bots_inner(&self) { self.bot_telegram_slot.advance(); if let Some(handle) = self.bot_telegram_handle.write().await.take() { - handle.stop(); + handle.stop().await; } *self.telegram_bot.write().await = None; self.bot_feishu_slot.advance(); if let Some(handle) = self.bot_feishu_handle.write().await.take() { - handle.stop(); + handle.stop().await; } *self.feishu_bot.write().await = None; self.bot_weixin_slot.advance(); if let Some(handle) = self.bot_weixin_handle.write().await.take() { - handle.stop(); + handle.stop().await; } if let Some(weixin_bot) = self.weixin_bot.write().await.take() { if let Err(err) = weixin_bot.notify_stop().await { @@ -840,9 +939,36 @@ impl RemoteConnectService { /// Check whether a specific bot type is currently running. pub async fn is_bot_running(&self, bot_type: &str) -> bool { match bot_type { - "telegram" => self.bot_telegram_handle.read().await.is_some(), - "feishu" => self.bot_feishu_handle.read().await.is_some(), - "weixin" => self.bot_weixin_handle.read().await.is_some(), + "telegram" => self + .bot_telegram_handle + .read() + .await + .as_ref() + .is_some_and(BotHandle::is_running), + "feishu" => self + .bot_feishu_handle + .read() + .await + .as_ref() + .is_some_and(BotHandle::is_running), + "weixin" => self + .bot_weixin_handle + .read() + .await + .as_ref() + .is_some_and(BotHandle::is_running), + _ => false, + } + } + + pub async fn bot_requires_login(&self, bot_type: &str) -> bool { + match bot_type { + "weixin" => self + .weixin_bot + .read() + .await + .as_ref() + .is_some_and(|bot| bot.requires_login()), _ => false, } } @@ -1291,3 +1417,52 @@ pub fn notify_session_catalog_event(event: &openbitfun_events::AgenticEvent) { crate::service::session::SessionMetadataStore::notify_catalog_changed(); } } + +#[cfg(test)] +mod listener_lifecycle_tests { + use super::BotHandle; + use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }; + + struct Released(Arc); + impl Drop for Released { + fn drop(&mut self) { + self.0.store(true, Ordering::SeqCst); + } + } + + #[tokio::test] + async fn stop_waits_for_listener_release_before_restart() { + let released = Arc::new(AtomicBool::new(false)); + let guard = Released(released.clone()); + let (stop_tx, _stop_rx) = tokio::sync::watch::channel(false); + let task = tokio::spawn(async move { + let _guard = guard; + std::future::pending::<()>().await; + }); + let handle = BotHandle { + stop_tx, + task: Some(task), + }; + assert!(handle.is_running()); + handle.stop().await; + assert!(released.load(Ordering::SeqCst)); + } + + #[tokio::test] + async fn completed_listener_is_reported_stopped() { + let (stop_tx, _stop_rx) = tokio::sync::watch::channel(false); + let task = tokio::spawn(async {}); + while !task.is_finished() { + tokio::task::yield_now().await; + } + let handle = BotHandle { + stop_tx, + task: Some(task), + }; + assert!(!handle.is_running()); + handle.stop().await; + } +} 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 446c8abcb1..efece5837b 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,8 +4,8 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "516e1cab17ad7c33ff1be2777de1c52bb8a47ef0292bed32928843b8d1ee72ae", - "ownerDigest": "f27c231da2e536e4f2123910f34f862b55d21feb0528bc915d4d13edbd528af9", + "digest": "2eb272d6820970e0c8ac677714ca03495729fa4a9cd458f1b89a4de726971107", + "ownerDigest": "df28e5eed6e3190741899ebf236bc5fb426d2469187e437839a349a7136c7c34", "searchAcceptance": [ { "id": "native-image-generation", @@ -177,9 +177,9 @@ "userFacing": 44, "documentedItems": 336, "controlCoverage": { - "direct": 56, + "direct": 58, "delegated": 72, - "interactive": 208, + "interactive": 206, "unsupported": 0 } }, @@ -9128,102 +9128,417 @@ } }, { - "id": "feature.remote-connect:open:connection-methods", + "id": "feature.remote-connect:operation:status", "capabilityId": "feature.remote-connect", "itemIds": [ - "connection-methods" + "start-stop-status", + "bots" ], - "kind": "open", - "risk": "ui", - "executionHost": "presentationSurface", + "kind": "operation", + "risk": "read", + "executionHost": "productHost", "availability": { "desktop": { "available": true }, "cli": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true }, "peer": { "available": true, "requiredCapabilities": [ "product_control_v1", - "product_control_presentation_v1" + "remote_connect_control_v1" ] }, "remoteControl": { "available": true }, "detachedDispatch": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true } }, "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + }, + "outputSchema": { "type": "object", - "additionalProperties": false + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:start", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "start-stop-status", + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "lanIp": { + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" }, "outputSchema": { "type": "object", "additionalProperties": true }, - "openReason": "unstructuredInteraction", + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, "presentationTarget": { "kind": "event", "eventName": "openbitfun:open-remote-connect" } }, { - "id": "feature.remote-connect:open:start-stop-status", + "id": "feature.remote-connect:operation:stop", "capabilityId": "feature.remote-connect", "itemIds": [ - "start-stop-status" + "start-stop-status", + "bots" ], - "kind": "open", - "risk": "ui", - "executionHost": "presentationSurface", + "kind": "operation", + "risk": "write", + "executionHost": "productHost", "availability": { "desktop": { "available": true }, "cli": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true }, "peer": { "available": true, "requiredCapabilities": [ "product_control_v1", - "product_control_presentation_v1" + "remote_connect_control_v1" ] }, "remoteControl": { "available": true }, "detachedDispatch": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true } }, "inputSchema": { + "additionalProperties": false, + "properties": { + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" + }, + "outputSchema": { "type": "object", - "additionalProperties": false + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:configure-bot", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "credentialsFile": { + "minLength": 1, + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu" + ], + "type": "string" + } + }, + "required": [ + "method", + "credentialsFile" + ], + "type": "object" }, "outputSchema": { "type": "object", "additionalProperties": true }, - "openReason": "unstructuredInteraction", + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, "presentationTarget": { "kind": "event", "eventName": "openbitfun:open-remote-connect" } }, { - "id": "feature.remote-connect:open:network", + "id": "feature.remote-connect:operation:weixin-login-start", "capabilityId": "feature.remote-connect", "itemIds": [ - "network" + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:weixin-login-poll", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "sessionKey": { + "minLength": 1, + "type": "string" + }, + "verifyCode": { + "type": "string" + } + }, + "required": [ + "sessionKey" + ], + "type": "object" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:set-bot-verbose", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + } + }, + "required": [ + "enabled" + ], + "type": "object" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:open:connection-methods", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "connection-methods" ], "kind": "open", "risk": "ui", @@ -9266,10 +9581,10 @@ } }, { - "id": "feature.remote-connect:open:bots", + "id": "feature.remote-connect:open:network", "capabilityId": "feature.remote-connect", "itemIds": [ - "bots" + "network" ], "kind": "open", "risk": "ui", @@ -25048,10 +25363,13 @@ "titleZh": "启动、停止 Remote Connect 并查看实时连接状态和设备信息", "titleEn": "Start or stop Remote Connect and inspect live status and device information", "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“启动、停止 Remote Connect 并查看实时连接状态和设备信息”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Start or stop Remote Connect and inspect live status and device information” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user." + "kind": "direct", + "operations": [ + "status", + "start", + "stop" + ], + "options": [] } }, { @@ -25070,10 +25388,17 @@ "titleZh": "配置飞书、Telegram、微信等 Bot 并单独停止 Bot", "titleEn": "Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently", "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“配置飞书、Telegram、微信等 Bot 并单独停止 Bot”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user." + "kind": "direct", + "operations": [ + "configure-bot", + "weixin-login-start", + "weixin-login-poll", + "set-bot-verbose", + "start", + "stop", + "status" + ], + "options": [] } }, { @@ -25123,18 +25448,222 @@ "agentExamplesZh": [ "打开 Remote Connect", "我想配置手机远程控制", - "带我管理已连接设备" + "带我管理已连接设备", + "启动微信机器人并持续监听消息", + "关闭 Telegram 机器人", + "开启手机网页远控" ], "agentExamplesEn": [ "Open Remote Connect", "I want to configure mobile remote control", - "Take me to connected-device management" + "Take me to connected-device management", + "Start the WeChat bot and keep listening", + "Stop the Telegram bot", + "Enable Mobile Web remote control" ], "destination": { "kind": "event", "eventName": "openbitfun:open-remote-connect" }, - "operations": [], + "operations": [ + { + "id": "status", + "titleZh": "查看远控状态", + "titleEn": "Inspect Remote Connect status", + "descriptionZh": "读取当前执行主机的监听、配对、停用与恢复错误;不返回凭据,监听任务存活不等于消息已完成往返。", + "descriptionEn": "Read listener, pairing, disabled and restore-error state on the executing host without credentials. A live listener task does not prove a message round trip.", + "risk": "read", + "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + }, + "handler": { + "kind": "provider", + "providerId": "remote-connect", + "operationId": "status" + } + }, + { + "id": "start", + "titleZh": "启动远控渠道", + "titleEn": "Start a Remote Connect channel", + "descriptionZh": "启动指定机器人或手机网页远控。CLI 自动启动 daemon,退出当前聊天后继续监听。新机器人需将返回的配对码发给机器人;CLI 不支持局域网 Relay。", + "descriptionEn": "Start the selected bot or Mobile Web. CLI starts its daemon and keeps listening after this chat exits. Send the returned pairing code to a new bot. CLI does not host a LAN Relay.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "lanIp": { + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" + }, + "handler": { + "kind": "provider", + "providerId": "remote-connect", + "operationId": "start" + } + }, + { + "id": "stop", + "titleZh": "停用远控渠道", + "titleEn": "Stop a Remote Connect channel", + "descriptionZh": "停用选定渠道并保留配置和会话。机器人停用状态跨重启保留。关闭手机网页会同时断开该主机的 Peer 设备路由,机器人保持运行。", + "descriptionEn": "Stop the selected channel while retaining configuration and sessions. Bot disablement survives restart. Stopping Mobile Web also disconnects Peer routing on this host; bots keep running.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" + }, + "handler": { + "kind": "provider", + "providerId": "remote-connect", + "operationId": "stop" + } + }, + { + "id": "configure-bot", + "titleZh": "从主机凭据文件配置机器人", + "titleEn": "Configure a bot from a private host credential file", + "descriptionZh": "读取执行主机上用户提供的私有 JSON 凭据文件并保存配置;不会自动启动。文件包含 bot_type 和对应凭据字段,需绝对路径和仅所有者可读权限;不要把凭据贴到聊天中。远程工作区路径不能用作主机凭据路径。", + "descriptionEn": "Load a user-supplied private JSON BotConfig file on the executing host, with bot_type and provider credential fields; save without starting. Requires an absolute host path and owner-only permissions. Do not paste credentials into chat or use a remote-workspace path.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "credentialsFile": { + "minLength": 1, + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu" + ], + "type": "string" + } + }, + "required": [ + "method", + "credentialsFile" + ], + "type": "object" + }, + "argumentScopes": { + "credentialsFile": "productHostLocal" + }, + "handler": { + "kind": "provider", + "providerId": "remote-connect", + "operationId": "configure-bot" + } + }, + { + "id": "weixin-login-start", + "titleZh": "开始微信扫码登录", + "titleEn": "Begin WeChat QR login", + "descriptionZh": "生成微信登录二维码。CLI TUI 在工具卡片中直接显示 qrTerminal,无需模型重写;其他终端逐字显示,图形界面显示 qrImageUrl,再用 sessionKey 轮询。扫码本身尚未完成机器人监听和配对。", + "descriptionEn": "Create a WeChat login QR. CLI TUI renders qrTerminal in the tool card without model transcription; other terminals show it verbatim and graphical surfaces show qrImageUrl. Poll using sessionKey; scanning alone does not complete listening and pairing.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + }, + "handler": { + "kind": "provider", + "providerId": "remote-connect", + "operationId": "weixin-login-start" + } + }, + { + "id": "weixin-login-poll", + "titleZh": "完成微信登录并启动监听", + "titleEn": "Complete WeChat login and start listening", + "descriptionZh": "轮询同一登录会话。确认后在主机保存凭据并启动监听,向用户展示返回的机器人配对码。凭据不会返回给模型。", + "descriptionEn": "Poll the same login session. Confirmation saves credentials on the host and starts listening; show the returned bot pairing code. Credentials are never returned to the model.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "sessionKey": { + "minLength": 1, + "type": "string" + }, + "verifyCode": { + "type": "string" + } + }, + "required": [ + "sessionKey" + ], + "type": "object" + }, + "handler": { + "kind": "provider", + "providerId": "remote-connect", + "operationId": "weixin-login-poll" + } + }, + { + "id": "set-bot-verbose", + "titleZh": "设置机器人详细输出", + "titleEn": "Set bot verbose output", + "descriptionZh": "切换所有机器人的详细输出模式并保存。", + "descriptionEn": "Persist verbose output mode for all bot channels.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + } + }, + "required": [ + "enabled" + ], + "type": "object" + }, + "handler": { + "kind": "provider", + "providerId": "remote-connect", + "operationId": "set-bot-verbose" + } + } + ], "options": [], "searchTerms": [ "feature.remote-connect", @@ -25181,9 +25710,15 @@ "打开 Remote Connect", "我想配置手机远程控制", "带我管理已连接设备", + "启动微信机器人并持续监听消息", + "关闭 Telegram 机器人", + "开启手机网页远控", "Open Remote Connect", "I want to configure mobile remote control", - "Take me to connected-device management" + "Take me to connected-device management", + "Start the WeChat bot and keep listening", + "Stop the Telegram bot", + "Enable Mobile Web remote control" ], "docsUrl": "https://playbook.openbitfun.com/capabilities/feature.remote-connect/" }, 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 c6348b5cba..3fac9c608a 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:96fc351cf4dd6568", + "digest": "fnv1a64:0e26746186f2b4ad", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -35,6 +35,7 @@ "wsl_workspaces_v1", "computer_use_sharing_v1", "product_control_v1", + "remote_connect_control_v1", "product_control_native_v1", "product_control_presentation_v1", "cancel_tool", @@ -75,6 +76,7 @@ "wsl_workspaces_v1", "computer_use_sharing_v1", "product_control_v1", + "remote_connect_control_v1", "product_control_native_v1", "product_control_presentation_v1", "cancel_tool", @@ -101,6 +103,7 @@ "token_usage_statistics", "model_channel_routing_v1", "product_control_v1", + "remote_connect_control_v1", "cancel_tool", "tool_catalog", "session_trajectory_v1", diff --git a/src/crates/contracts/product-domains/src/lib.rs b/src/crates/contracts/product-domains/src/lib.rs index 5d59631e0f..a9a5b22cf1 100644 --- a/src/crates/contracts/product-domains/src/lib.rs +++ b/src/crates/contracts/product-domains/src/lib.rs @@ -13,6 +13,7 @@ pub mod product_control; pub mod product_control_owner_registry; pub mod product_release; pub mod product_search; +pub mod remote_control; pub mod remote_surface; #[cfg(feature = "external-sources")] pub mod session_import; diff --git a/src/crates/contracts/product-domains/src/product_control_owner_registry.rs b/src/crates/contracts/product-domains/src/product_control_owner_registry.rs index 54cea23de8..0d78de3244 100644 --- a/src/crates/contracts/product-domains/src/product_control_owner_registry.rs +++ b/src/crates/contracts/product-domains/src/product_control_owner_registry.rs @@ -289,6 +289,62 @@ pub fn owner_definitions() -> Vec { use ProductControlRisk::{Destructive, Read, Ui, Write}; vec![ + operation( + "feature.remote-connect", + "status", + Read, + json!({"type": "object", "properties": {}, "required": [], "additionalProperties": false}), + &[], + operation_provider("remote-connect", "status"), + ), + operation( + "feature.remote-connect", + "start", + Write, + json!({"type": "object", "properties": {"method": {"type": "string", "enum": ["weixin", "telegram", "feishu", "mobile_web", "lan"]}, "lanIp": {"type": "string"}}, "required": ["method"], "additionalProperties": false}), + &[], + operation_provider("remote-connect", "start"), + ), + operation( + "feature.remote-connect", + "stop", + Write, + json!({"type": "object", "properties": {"method": {"type": "string", "enum": ["weixin", "telegram", "feishu", "mobile_web", "lan"]}}, "required": ["method"], "additionalProperties": false}), + &[], + operation_provider("remote-connect", "stop"), + ), + operation( + "feature.remote-connect", + "configure-bot", + Write, + json!({"type": "object", "properties": {"method": {"type": "string", "enum": ["weixin", "telegram", "feishu"]}, "credentialsFile": {"type": "string", "minLength": 1}}, "required": ["method", "credentialsFile"], "additionalProperties": false}), + &[("credentialsFile", ProductHostLocal)], + operation_provider("remote-connect", "configure-bot"), + ), + operation( + "feature.remote-connect", + "weixin-login-start", + Write, + json!({"type": "object", "properties": {}, "required": [], "additionalProperties": false}), + &[], + operation_provider("remote-connect", "weixin-login-start"), + ), + operation( + "feature.remote-connect", + "weixin-login-poll", + Write, + json!({"type": "object", "properties": {"sessionKey": {"type": "string", "minLength": 1}, "verifyCode": {"type": "string"}}, "required": ["sessionKey"], "additionalProperties": false}), + &[], + operation_provider("remote-connect", "weixin-login-poll"), + ), + operation( + "feature.remote-connect", + "set-bot-verbose", + Write, + json!({"type": "object", "properties": {"enabled": {"type": "boolean"}}, "required": ["enabled"], "additionalProperties": false}), + &[], + operation_provider("remote-connect", "set-bot-verbose"), + ), operation( "setting.tools.mcp", "list-servers", diff --git a/src/crates/contracts/product-domains/src/remote_control.rs b/src/crates/contracts/product-domains/src/remote_control.rs new file mode 100644 index 0000000000..96b74ceddc --- /dev/null +++ b/src/crates/contracts/product-domains/src/remote_control.rs @@ -0,0 +1,197 @@ +//! Closed management requests for the executing OpenBitFun host's Remote Connect. +//! +//! This is independent of workspace file routing and contains no provider secrets. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub const REMOTE_CONTROL_PROVIDER: &str = "remote-connect"; +pub const REMOTE_CONTROL_CAPABILITY: &str = "remote_connect_control_v1"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RemoteControlMethod { + Weixin, + Telegram, + Feishu, + MobileWeb, + Lan, +} + +impl RemoteControlMethod { + pub fn bot_type(self) -> Option<&'static str> { + match self { + Self::Weixin => Some("weixin"), + Self::Telegram => Some("telegram"), + Self::Feishu => Some("feishu"), + Self::MobileWeb | Self::Lan => None, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde( + tag = "operation", + rename_all = "kebab-case", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +pub enum RemoteControlRequest { + Status, + Start { + method: RemoteControlMethod, + #[serde(default)] + lan_ip: Option, + }, + Stop { + method: RemoteControlMethod, + }, + ConfigureBot { + method: RemoteControlMethod, + credentials_file: String, + }, + WeixinLoginStart, + WeixinLoginPoll { + session_key: String, + #[serde(default)] + verify_code: Option, + }, + SetBotVerbose { + enabled: bool, + }, +} + +impl RemoteControlRequest { + pub fn from_operation(operation: &str, arguments: Option<&Value>) -> Result { + let mut arguments = arguments.cloned().unwrap_or_else(|| serde_json::json!({})); + let object = arguments + .as_object_mut() + .ok_or("Remote Connect arguments must be an object")?; + if object.contains_key("operation") { + return Err( + "Remote Connect operation must be supplied by the registered handler".into(), + ); + } + object.insert("operation".into(), Value::String(operation.into())); + serde_json::from_value(arguments) + .map_err(|_| "Invalid Remote Connect operation or arguments".into()) + } + + /// Direct HostInvoke holds the route's read lease through its response. + /// A turn submitted to the Agent runtime is independent of that lease. + pub fn ensure_direct_peer_safe(&self) -> Result<(), String> { + if matches!( + self, + Self::Start { + method: RemoteControlMethod::MobileWeb | RemoteControlMethod::Lan, + .. + } | Self::Stop { + method: RemoteControlMethod::MobileWeb | RemoteControlMethod::Lan + } + ) { + return Err("remote_control_transport_lifecycle_unsupported: Start or stop Relay through a Claw conversation or on the executing host; a direct Peer RPC cannot replace its own transport".into()); + } + Ok(()) + } + + pub fn operation_id(&self) -> &'static str { + match self { + Self::Status => "status", + Self::Start { .. } => "start", + Self::Stop { .. } => "stop", + Self::ConfigureBot { .. } => "configure-bot", + Self::WeixinLoginStart => "weixin-login-start", + Self::WeixinLoginPoll { .. } => "weixin-login-poll", + Self::SetBotVerbose { .. } => "set-bot-verbose", + } + } + + pub fn is_readonly(&self) -> bool { + matches!(self, Self::Status) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn controls_declare_risk_host_paths_and_peer_negotiation() { + use crate::product_control::*; + let registry = ProductControlRegistry::global(); + let operation = registry + .operation("feature.remote-connect", "configure-bot") + .unwrap(); + let args = serde_json::json!({"method":"telegram", "credentialsFile":"/host/private.json"}); + validate_operation_arguments(&operation.input_schema, Some(&args)).unwrap(); + assert!(validate_operation_argument_scopes(operation, Some(&args), true).is_err()); + assert_eq!( + registry + .operation("feature.remote-connect", "status") + .unwrap() + .risk, + ProductControlRisk::Read + ); + assert_eq!( + registry + .operation("feature.remote-connect", "start") + .unwrap() + .risk, + ProductControlRisk::Write + ); + let definition = registry + .definition("feature.remote-connect:operation:start") + .unwrap(); + assert!(definition.availability[&ProductControlDeliveryProfile::Cli].available); + assert!( + definition.availability[&ProductControlDeliveryProfile::Peer] + .required_capabilities + .contains(&REMOTE_CONTROL_CAPABILITY.to_owned()) + ); + assert!(RemoteControlRequest::from_operation( + "weixin-login-poll", + Some(&serde_json::json!({"sessionKey":"one"})) + ) + .is_ok()); + } + + #[test] + fn direct_peer_lifecycle_refuses_to_replace_its_own_route() { + for method in [RemoteControlMethod::MobileWeb, RemoteControlMethod::Lan] { + assert!(RemoteControlRequest::Start { + method, + lan_ip: None + } + .ensure_direct_peer_safe() + .is_err()); + assert!(RemoteControlRequest::Stop { method } + .ensure_direct_peer_safe() + .is_err()); + } + assert!(RemoteControlRequest::Start { + method: RemoteControlMethod::Weixin, + lan_ip: None + } + .ensure_direct_peer_safe() + .is_ok()); + assert!(RemoteControlRequest::Status + .ensure_direct_peer_safe() + .is_ok()); + } + + #[test] + fn closed_requests_reject_secret_arguments_and_unknown_methods() { + assert!( + RemoteControlRequest::from_operation("start", Some(&json!({"method":"weixin"}))) + .is_ok() + ); + for arguments in [ + json!({"method":"weixin", "token":"secret"}), + json!({"method":"shell"}), + json!({"operation":"stop", "method":"weixin"}), + ] { + assert!(RemoteControlRequest::from_operation("start", Some(&arguments)).is_err()); + } + } +} diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index b2b33d1b4a..88607364e0 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -73,6 +73,8 @@ pub enum PeerHostCapability { ComputerUseSharingV1, /// `product_control_invoke` is implemented (shared config contract). ProductControlV1, + /// Remote Connect bot and Mobile Web management on the executing host. + RemoteConnectControlV1, /// ProductControl definitions that need a host-native provider run here. ProductControlNativeV1, /// ProductControl definitions that need a live presentation surface run here. @@ -128,6 +130,7 @@ impl PeerHostCapability { Self::WslWorkspacesV1, Self::ComputerUseSharingV1, Self::ProductControlV1, + Self::RemoteConnectControlV1, Self::ProductControlNativeV1, Self::ProductControlPresentationV1, Self::CancelTool, @@ -171,6 +174,7 @@ impl PeerHostCapability { Self::WslWorkspacesV1 => "wsl_workspaces_v1", Self::ComputerUseSharingV1 => "computer_use_sharing_v1", Self::ProductControlV1 => "product_control_v1", + Self::RemoteConnectControlV1 => "remote_connect_control_v1", Self::ProductControlNativeV1 => "product_control_native_v1", Self::ProductControlPresentationV1 => "product_control_presentation_v1", Self::CancelTool => "cancel_tool", @@ -209,6 +213,7 @@ const CLI_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::TokenUsageStatistics, PeerHostCapability::ModelChannelRoutingV1, PeerHostCapability::ProductControlV1, + PeerHostCapability::RemoteConnectControlV1, PeerHostCapability::CancelTool, PeerHostCapability::ToolCatalog, PeerHostCapability::SessionTrajectoryV1, diff --git a/src/crates/services/legacy-migration-adapters/src/remote_connect.rs b/src/crates/services/legacy-migration-adapters/src/remote_connect.rs index 7d8e871cb3..62fec3ac41 100644 --- a/src/crates/services/legacy-migration-adapters/src/remote_connect.rs +++ b/src/crates/services/legacy-migration-adapters/src/remote_connect.rs @@ -1412,6 +1412,7 @@ mod tests { }], form_state: RemoteConnectFormStateRecord::default(), verbose_mode: false, + disabled_bots: Vec::new(), } } diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs b/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs index 48e3d464d1..0f8ec22804 100644 --- a/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs +++ b/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs @@ -7,6 +7,7 @@ mod command; pub mod feishu; mod locale; mod menu; +mod ownership; pub mod remote_turn; mod state; pub mod telegram; @@ -19,6 +20,7 @@ pub use command::{parse_command, BotCommand}; pub use feishu::{FeishuBotApi, FeishuConfig}; pub use locale::{fmt_count, strings_for, BotLanguage, BotStrings}; pub use menu::{MenuItem, MenuItemStyle, MenuView}; +pub use ownership::BotListenerLease; pub use state::{ BotAction, BotActionStyle, BotChatState, BotDisplayMode, BotInteractionHandler, BotInteractiveRequest, BotMessageSender, BotQuestion, BotQuestionOption, BotWorkspaceChoice, @@ -45,6 +47,72 @@ pub enum BotConfig { }, } +impl BotConfig { + pub fn bot_type(&self) -> &'static str { + match self { + Self::Feishu { .. } => "feishu", + Self::Telegram { .. } => "telegram", + Self::Weixin { .. } => "weixin", + } + } + + pub fn validate(&self) -> anyhow::Result<()> { + let valid = match self { + Self::Feishu { app_id, app_secret } => { + !app_id.trim().is_empty() && !app_secret.trim().is_empty() + } + Self::Telegram { bot_token } => !bot_token.trim().is_empty(), + Self::Weixin { + ilink_token, + bot_account_id, + .. + } => !ilink_token.trim().is_empty() && !bot_account_id.trim().is_empty(), + }; + anyhow::ensure!(valid, "Bot credentials are incomplete"); + Ok(()) + } +} + +/// Read credentials supplied explicitly by the user on the executing product host. +/// Never return file contents or credential values in an error or management result. +pub async fn read_bot_credentials_file(path: std::path::PathBuf) -> anyhow::Result { + tokio::task::spawn_blocking(move || { + use std::io::Read; + anyhow::ensure!( + path.is_absolute(), + "credentialsFile must be an absolute path on the executing product host" + ); + let metadata = std::fs::symlink_metadata(&path)?; + anyhow::ensure!( + metadata.file_type().is_file(), + "Bot credentials must be supplied in a regular file" + ); + let file = std::fs::File::open(&path)?; + let metadata = file.metadata()?; + anyhow::ensure!( + metadata.is_file() && metadata.len() <= 16 * 1024, + "Bot credential file is too large or not a regular file" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + anyhow::ensure!( + metadata.permissions().mode() & 0o077 == 0, + "Bot credential file must have owner-only permissions (chmod 600)" + ); + } + let mut bytes = Vec::new(); + file.take(16 * 1024 + 1).read_to_end(&mut bytes)?; + anyhow::ensure!(bytes.len() <= 16 * 1024, "Bot credential file is too large"); + let config: BotConfig = serde_json::from_slice(&bytes).map_err(|_| { + anyhow::anyhow!("Invalid bot credential file; expected a BotConfig JSON object") + })?; + config.validate()?; + Ok(config) + }) + .await? +} + /// Pairing state for bot-based connections. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BotPairingInfo { @@ -68,6 +136,7 @@ pub struct SavedBotConnection { /// Persisted remote-connect form values shown in the desktop dialog. #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(default)] pub struct RemoteConnectFormState { pub telegram_bot_token: String, pub feishu_app_id: String, @@ -98,6 +167,10 @@ pub struct BotPersistenceData { /// Defaults to `false` (concise mode). #[serde(default)] pub verbose_mode: bool, + /// Explicitly stopped channels retain their credentials and chat state. + /// Older records have no disabled channels and keep their restore behavior. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub disabled_bots: Vec, } impl BotPersistenceData { @@ -526,23 +599,35 @@ fn bot_persistence_backup_path(path: &std::path::Path) -> std::path::PathBuf { } fn load_bot_persistence_unlocked() -> BotPersistenceData { - let Some(path) = bot_persistence_path() else { - return BotPersistenceData::default(); - }; - match crate::remote_persistence::read_bot_persistence(&path) { - Ok(Some(data)) => serde_json::to_value(data) - .ok() - .and_then(|value| serde_json::from_value(value).ok()) - .unwrap_or_default(), - Ok(None) | Err(_) => { - // A backup without the canonical file means the process stopped - // during the Windows replace dance. Fail closed instead of - // restoring a pre-clear account context. - BotPersistenceData::default() + try_load_bot_persistence_unlocked().unwrap_or_else(|error| { + log::error!("Bot persistence is unavailable; existing data was preserved: {error}"); + BotPersistenceData::default() + }) +} + +fn try_load_bot_persistence_unlocked() -> anyhow::Result { + let path = bot_persistence_path() + .ok_or_else(|| anyhow::anyhow!("Cannot determine bot persistence location"))?; + load_bot_persistence_at(&path) +} + +fn load_bot_persistence_at(path: &std::path::Path) -> anyhow::Result { + match crate::remote_persistence::read_bot_persistence(path)? { + Some(data) => Ok(serde_json::from_value(serde_json::to_value(data)?)?), + None if bot_persistence_backup_path(path).exists() => { + anyhow::bail!( + "Bot persistence has an unfinished replacement; preserve the backup for recovery" + ) } + None => Ok(BotPersistenceData::default()), } } +pub fn try_load_bot_persistence() -> anyhow::Result { + let _persistence = bot_persistence_lock(); + try_load_bot_persistence_unlocked() +} + fn write_bot_persistence_atomic(path: &std::path::Path, json: &[u8]) -> std::io::Result<()> { use std::io::Write; @@ -645,12 +730,44 @@ pub fn save_bot_persistence(data: &BotPersistenceData) { /// Apply one read-modify-write transaction to the shared bot persistence /// document. Individual platform loops run concurrently, so separate /// `load`/`save` calls can otherwise overwrite another bot's update. -pub fn update_bot_persistence(update: impl FnOnce(&mut BotPersistenceData) -> R) -> R { +pub fn try_update_bot_persistence( + update: impl FnOnce(&mut BotPersistenceData) -> R, +) -> anyhow::Result { let _persistence = bot_persistence_lock(); - let mut data = load_bot_persistence_unlocked(); + let path = bot_persistence_path() + .ok_or_else(|| anyhow::anyhow!("Cannot determine bot persistence location"))?; + update_bot_persistence_at(&path, update) +} + +fn update_bot_persistence_at( + path: &std::path::Path, + update: impl FnOnce(&mut BotPersistenceData) -> R, +) -> anyhow::Result { + // Desktop and daemon may own different providers in the same product home. + // The process mutex alone cannot protect their shared persistence document. + let parent = path + .parent() + .ok_or_else(|| anyhow::anyhow!("Missing persistence directory"))?; + std::fs::create_dir_all(parent)?; + let lock = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(path.with_extension("lock"))?; + fs2::FileExt::lock_exclusive(&lock)?; + let mut data = load_bot_persistence_at(path)?; let result = update(&mut data); - save_bot_persistence_unlocked(&data); - result + let json = serde_json::to_vec_pretty(&data)?; + serde_json::from_slice::(&json)?.validate()?; + write_bot_persistence_atomic(path, &json)?; + Ok(result) +} + +pub fn update_bot_persistence(update: impl FnOnce(&mut BotPersistenceData)) { + if let Err(error) = try_update_bot_persistence(update) { + log::error!("Failed to update bot persistence; existing data was preserved: {error}"); + } } /// Remove persisted account-device context for every bot connection. This is @@ -670,6 +787,11 @@ mod tests { bot_persistence_backup_path, collect_auto_push_files, extract_downloadable_file_paths, resolve_workspace_path, write_bot_persistence_atomic, }; + use super::{ + load_bot_persistence_at, update_bot_persistence_at, RemoteConnectFormState, + SavedBotConnection, + }; + use serde::Deserialize; fn make_temp_workspace() -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) { let base = std::env::temp_dir().join(format!( @@ -684,6 +806,81 @@ mod tests { (base, workspace, report) } + #[test] + fn bot_management_legacy_roundtrip_and_disabled_restart_state() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("remote_connect_persistence.json"); + let legacy = serde_json::json!({ + "connections": [{"account_user_id":"account", "bot_type":"telegram", "chat_id":"chat", "config":{"bot_type":"telegram", "bot_token":"fixture-token"}, + "chat_state":{"chat_id":"chat", "paired":true,"current_workspace":null,"current_assistant":null,"current_session_id":"session"}, "connected_at":1}], + "form_state":{"telegram_bot_token":"fixture-token"}, "verbose_mode":false + }); + std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap(); + assert!(load_bot_persistence_at(&path) + .unwrap() + .disabled_bots + .is_empty()); + update_bot_persistence_at(&path, |data| data.disabled_bots.push("telegram".into())) + .unwrap(); + let stopped = load_bot_persistence_at(&path).unwrap(); + assert_eq!(stopped.disabled_bots, ["telegram"]); + assert_eq!( + stopped.connections[0] + .chat_state + .current_session_id + .as_deref(), + Some("session") + ); + assert_eq!(stopped.form_state.telegram_bot_token, "fixture-token"); + // A pre-field reader ignores the additive field and can still decode + // the original connection and credentials. + #[derive(Deserialize)] + struct Legacy { + connections: Vec, + form_state: RemoteConnectFormState, + } + let old: Legacy = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(old.connections.len(), 1); + assert_eq!(old.form_state.telegram_bot_token, "fixture-token"); + update_bot_persistence_at(&path, |data| data.disabled_bots.clear()).unwrap(); + assert!(load_bot_persistence_at(&path) + .unwrap() + .disabled_bots + .is_empty()); + } + + #[test] + fn bot_management_preserves_unreadable_records() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("remote_connect_persistence.json"); + let corrupt = br#"{"connections":[{"bot_type":"future-provider"}]}"#; + std::fs::write(&path, corrupt).unwrap(); + assert!(update_bot_persistence_at(&path, |data| data.verbose_mode = true).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), corrupt); + } + + #[test] + fn bot_management_concurrent_writers_preserve_both_channels() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("remote_connect_persistence.json"); + let workers: Vec<_> = ["telegram", "weixin"] + .into_iter() + .map(|method| { + let path = path.clone(); + std::thread::spawn(move || { + update_bot_persistence_at(&path, |data| data.disabled_bots.push(method.into())) + .unwrap() + }) + }) + .collect(); + for worker in workers { + worker.join().unwrap(); + } + let saved = load_bot_persistence_at(&path).unwrap(); + assert!(saved.disabled_bots.contains(&"telegram".into())); + assert!(saved.disabled_bots.contains(&"weixin".into())); + } + #[test] fn bot_persistence_replaces_existing_file_via_same_directory_temp() { let root = tempfile::tempdir().expect("temporary persistence directory"); diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/ownership.rs b/src/crates/services/services-integrations/src/remote_connect/bot/ownership.rs new file mode 100644 index 0000000000..def7fb1387 --- /dev/null +++ b/src/crates/services/services-integrations/src/remote_connect/bot/ownership.rs @@ -0,0 +1,57 @@ +//! A provider polling cursor must have exactly one process owner per product home. + +use anyhow::{anyhow, Context, Result}; +use fs2::FileExt; +use std::fs::{File, OpenOptions}; +use std::path::Path; + +pub struct BotListenerLease(File); + +impl BotListenerLease { + pub fn acquire(bot_type: &str) -> Result { + let home = super::super::product_home_dir() + .ok_or_else(|| anyhow!("Cannot determine the Remote Connect product home"))?; + Self::acquire_in(&home, bot_type) + } + + fn acquire_in(home: &Path, bot_type: &str) -> Result { + if !matches!(bot_type, "weixin" | "telegram" | "feishu") { + anyhow::bail!("Unknown bot type"); + } + let directory = home.join("remote-connect-runtime"); + std::fs::create_dir_all(&directory).context("create bot runtime directory")?; + let file = OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(directory.join(format!("{bot_type}.lock"))) + .context("open bot listener ownership lock")?; + file.try_lock_exclusive().map_err(|error| { + anyhow!("bot_listener_in_use: Cannot acquire {bot_type} listener ownership. Stop that channel in the other Desktop or CLI host before starting it here: {error}") + })?; + Ok(Self(file)) + } +} + +impl Drop for BotListenerLease { + fn drop(&mut self) { + let _ = FileExt::unlock(&self.0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_one_listener_consumes_each_channel_and_release_allows_restart() { + let home = tempfile::tempdir().unwrap(); + let first = BotListenerLease::acquire_in(home.path(), "weixin").unwrap(); + assert!(BotListenerLease::acquire_in(home.path(), "weixin").is_err()); + let other = BotListenerLease::acquire_in(home.path(), "telegram").unwrap(); + drop(first); + assert!(BotListenerLease::acquire_in(home.path(), "weixin").is_ok()); + drop(other); + } +} diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/weixin.rs b/src/crates/services/services-integrations/src/remote_connect/bot/weixin.rs index f9a0156f97..2bf64cdb56 100644 --- a/src/crates/services/services-integrations/src/remote_connect/bot/weixin.rs +++ b/src/crates/services/services-integrations/src/remote_connect/bot/weixin.rs @@ -14,6 +14,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::HashMap; use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use tokio::sync::RwLock; @@ -143,6 +144,7 @@ pub struct WeixinProviderClient { http_client: reqwest::Client, typing_tickets: Arc>>, session_pause_until_ms: Arc>>, + login_required: AtomicBool, } pub struct TypingHandle { @@ -203,6 +205,7 @@ impl WeixinProviderClient { http_client: crate::reqwest_client(), typing_tickets: Arc::new(RwLock::new(HashMap::new())), session_pause_until_ms: Arc::new(RwLock::new(HashMap::new())), + login_required: AtomicBool::new(false), } } @@ -210,6 +213,12 @@ impl WeixinProviderClient { &self.config } + /// A live polling task can be waiting for reauthentication. Retain this + /// fact until a successful authenticated poll, even after retry backoff ends. + pub fn requires_login(&self) -> bool { + self.login_required.load(Ordering::Acquire) + } + fn base_url(&self) -> String { ensure_trailing_slash(&self.config.base_url) } @@ -229,6 +238,7 @@ impl WeixinProviderClient { } async fn pause_session(&self) { + self.login_required.store(true, Ordering::Release); let until = now_ms() + (SESSION_PAUSE_SECS as i64) * 1000; self.session_pause_until_ms .write() @@ -289,6 +299,11 @@ impl WeixinProviderClient { let ret = value["ret"].as_i64().unwrap_or(0); let errcode = value["errcode"].as_i64().unwrap_or(0); if ret != 0 || errcode != 0 { + if ret == WEIXIN_SESSION_EXPIRED_ERRCODE + || errcode == WEIXIN_SESSION_EXPIRED_ERRCODE + { + self.pause_session().await; + } let errmsg = value["errmsg"] .as_str() .or_else(|| value["msg"].as_str()) @@ -339,6 +354,8 @@ impl WeixinProviderClient { let errcode = value["errcode"].as_i64().unwrap_or(0); if errcode == WEIXIN_SESSION_EXPIRED_ERRCODE || ret == WEIXIN_SESSION_EXPIRED_ERRCODE { self.pause_session().await; + } else if value["ret"].as_i64() == Some(0) && errcode == 0 { + self.login_required.store(false, Ordering::Release); } debug!( "weixin: getupdates ret={ret} errcode={errcode} messages={}", @@ -1913,22 +1930,48 @@ mod tests { async fn stale_token_remains_an_error_while_requests_are_paused() { let (base, mut requests, task) = mock_ilink(vec![(0, r#"{"ret":-14}"#)]).await; let client = test_client(base); + assert!(!client.requires_login()); let response = client .get_updates_once("cursor", Duration::from_secs(1)) .await .unwrap(); assert!(updates_failed(&response)); + assert!(client.requires_login()); let paused = client .get_updates_once("cursor", Duration::from_secs(1)) .await .unwrap(); assert!(updates_failed(&paused)); + assert!(client.requires_login()); assert!(paused.get("get_updates_buf").is_none()); task.await.unwrap(); assert!(requests.recv().await.is_some()); assert!(requests.recv().await.is_none()); } + #[tokio::test] + async fn notify_token_expiry_requires_login_until_a_successful_authenticated_poll() { + let (base, _requests, task) = mock_ilink(vec![ + (0, r#"{"ret":0,"errcode":-14,"errmsg":"session timeout"}"#), + (0, r#"{"ret":0,"msgs":[]}"#), + ]) + .await; + let client = test_client(base); + assert!(client.notify_start().await.is_err()); + assert!(client.requires_login()); + client.session_pause_until_ms.write().await.clear(); + assert!( + client.requires_login(), + "Backoff expiry is not successful authentication" + ); + client + .get_updates_once("cursor", Duration::from_secs(1)) + .await + .unwrap(); + assert!(!client.requires_login()); + task.await.unwrap(); + } + #[tokio::test] async fn send_response_must_be_valid_json_and_successful() { for response in [ diff --git a/src/crates/services/services-integrations/src/remote_connect/qr_generator.rs b/src/crates/services/services-integrations/src/remote_connect/qr_generator.rs index 7ef2bbcb2c..56170e9d97 100644 --- a/src/crates/services/services-integrations/src/remote_connect/qr_generator.rs +++ b/src/crates/services/services-integrations/src/remote_connect/qr_generator.rs @@ -6,7 +6,44 @@ use qrcode::QrCode; pub struct QrGenerator; +pub struct QrPresentation { + pub image_url: String, + pub terminal: Option, +} + impl QrGenerator { + /// Provider QR content may be an existing image or the text to encode. + /// A login/deep-link URL is not an image URL. + pub fn present_content(content: &str) -> Result { + let content = content.trim(); + let image_url = content.to_ascii_lowercase().starts_with("data:image/") + || reqwest::Url::parse(content).ok().is_some_and(|url| { + matches!(url.scheme(), "http" | "https") + && [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"] + .iter() + .any(|extension| url.path().to_ascii_lowercase().ends_with(extension)) + }); + if image_url { + return Ok(QrPresentation { + image_url: content.into(), + terminal: None, + }); + } + let code = QrCode::new(content.as_bytes()) + .map_err(|error| anyhow!("QR code generation failed: {error}"))?; + Ok(QrPresentation { + image_url: format!( + "data:image/png;base64,{}", + Self::generate_png_base64_from_url(content)? + ), + terminal: Some( + code.render::() + .quiet_zone(true) + .build(), + ), + }) + } + /// Account-device invitations carry only a target id. Identity and public /// keys are resolved through the authenticated same-account directory. pub fn build_device_url(web_app_url: &str, device_id: &str) -> Result { @@ -57,6 +94,33 @@ impl QrGenerator { #[cfg(test)] mod account_device_tests { use super::QrGenerator; + use base64::Engine; + + #[test] + fn provider_login_link_is_encoded_instead_of_treated_as_an_image() { + let presentation = + QrGenerator::present_content("https://liteapp.weixin.qq.com/login?code=example") + .unwrap(); + let png = super::BASE64 + .decode( + presentation + .image_url + .strip_prefix("data:image/png;base64,") + .unwrap(), + ) + .unwrap(); + assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n"); + assert!(presentation.terminal.unwrap().contains('\u{2588}')); + for image in [ + "https://example.test/qr.png?code=1", + "data:image/png;base64,aGVsbG8=", + ] { + let presentation = QrGenerator::present_content(image).unwrap(); + assert_eq!(presentation.image_url, image); + assert!(presentation.terminal.is_none()); + } + } + #[test] fn invitation_uses_only_the_authenticated_device_target() { assert_eq!( diff --git a/src/crates/services/services-integrations/src/remote_persistence.rs b/src/crates/services/services-integrations/src/remote_persistence.rs index 42c2504e37..cb98da8c58 100644 --- a/src/crates/services/services-integrations/src/remote_persistence.rs +++ b/src/crates/services/services-integrations/src/remote_persistence.rs @@ -439,6 +439,7 @@ pub struct SavedBotConnectionRecord { } #[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] pub struct RemoteConnectFormStateRecord { pub telegram_bot_token: String, pub feishu_app_id: String, @@ -459,6 +460,8 @@ pub struct BotPersistenceRecord { pub form_state: RemoteConnectFormStateRecord, #[serde(default)] pub verbose_mode: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub disabled_bots: Vec, } impl std::fmt::Debug for BotPersistenceRecord { diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index 08afb99b31..aa2d828db2 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -4548,10 +4548,13 @@ "titleZh": "启动、停止 Remote Connect 并查看实时连接状态和设备信息", "titleEn": "Start or stop Remote Connect and inspect live status and device information", "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“启动、停止 Remote Connect 并查看实时连接状态和设备信息”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Start or stop Remote Connect and inspect live status and device information” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user." + "kind": "direct", + "operations": [ + "status", + "start", + "stop" + ], + "options": [] }, "evidence": [ "command:remote_connect_start", @@ -4582,10 +4585,17 @@ "titleZh": "配置飞书、Telegram、微信等 Bot 并单独停止 Bot", "titleEn": "Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently", "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“配置飞书、Telegram、微信等 Bot 并单独停止 Bot”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user." + "kind": "direct", + "operations": [ + "configure-bot", + "weixin-login-start", + "weixin-login-poll", + "set-bot-verbose", + "start", + "stop", + "status" + ], + "options": [] }, "evidence": [ "command:remote_connect_configure_bot", @@ -4666,18 +4676,74 @@ "agentExamplesZh": [ "打开 Remote Connect", "我想配置手机远程控制", - "带我管理已连接设备" + "带我管理已连接设备", + "启动微信机器人并持续监听消息", + "关闭 Telegram 机器人", + "开启手机网页远控" ], "agentExamplesEn": [ "Open Remote Connect", "I want to configure mobile remote control", - "Take me to connected-device management" + "Take me to connected-device management", + "Start the WeChat bot and keep listening", + "Stop the Telegram bot", + "Enable Mobile Web remote control" ], "destination": { "kind": "event", "eventName": "openbitfun:open-remote-connect" }, - "operations": [] + "operations": [ + { + "id": "status", + "titleZh": "查看远控状态", + "titleEn": "Inspect Remote Connect status", + "descriptionZh": "读取当前执行主机的监听、配对、停用与恢复错误;不返回凭据,监听任务存活不等于消息已完成往返。", + "descriptionEn": "Read listener, pairing, disabled and restore-error state on the executing host without credentials. A live listener task does not prove a message round trip." + }, + { + "id": "start", + "titleZh": "启动远控渠道", + "titleEn": "Start a Remote Connect channel", + "descriptionZh": "启动指定机器人或手机网页远控。CLI 自动启动 daemon,退出当前聊天后继续监听。新机器人需将返回的配对码发给机器人;CLI 不支持局域网 Relay。", + "descriptionEn": "Start the selected bot or Mobile Web. CLI starts its daemon and keeps listening after this chat exits. Send the returned pairing code to a new bot. CLI does not host a LAN Relay." + }, + { + "id": "stop", + "titleZh": "停用远控渠道", + "titleEn": "Stop a Remote Connect channel", + "descriptionZh": "停用选定渠道并保留配置和会话。机器人停用状态跨重启保留。关闭手机网页会同时断开该主机的 Peer 设备路由,机器人保持运行。", + "descriptionEn": "Stop the selected channel while retaining configuration and sessions. Bot disablement survives restart. Stopping Mobile Web also disconnects Peer routing on this host; bots keep running." + }, + { + "id": "configure-bot", + "titleZh": "从主机凭据文件配置机器人", + "titleEn": "Configure a bot from a private host credential file", + "descriptionZh": "读取执行主机上用户提供的私有 JSON 凭据文件并保存配置;不会自动启动。文件包含 bot_type 和对应凭据字段,需绝对路径和仅所有者可读权限;不要把凭据贴到聊天中。远程工作区路径不能用作主机凭据路径。", + "descriptionEn": "Load a user-supplied private JSON BotConfig file on the executing host, with bot_type and provider credential fields; save without starting. Requires an absolute host path and owner-only permissions. Do not paste credentials into chat or use a remote-workspace path." + }, + { + "id": "weixin-login-start", + "titleZh": "开始微信扫码登录", + "titleEn": "Begin WeChat QR login", + "descriptionZh": "生成微信登录二维码。CLI TUI 在工具卡片中直接显示 qrTerminal,无需模型重写;其他终端逐字显示,图形界面显示 qrImageUrl,再用 sessionKey 轮询。扫码本身尚未完成机器人监听和配对。", + "descriptionEn": "Create a WeChat login QR. CLI TUI renders qrTerminal in the tool card without model transcription; other terminals show it verbatim and graphical surfaces show qrImageUrl. Poll using sessionKey; scanning alone does not complete listening and pairing." + }, + { + "id": "weixin-login-poll", + "titleZh": "完成微信登录并启动监听", + "titleEn": "Complete WeChat login and start listening", + "descriptionZh": "轮询同一登录会话。确认后在主机保存凭据并启动监听,向用户展示返回的机器人配对码。凭据不会返回给模型。", + "descriptionEn": "Poll the same login session. Confirmation saves credentials on the host and starts listening; show the returned bot pairing code. Credentials are never returned to the model." + }, + { + "id": "set-bot-verbose", + "titleZh": "设置机器人详细输出", + "titleEn": "Set bot verbose output", + "descriptionZh": "切换所有机器人的详细输出模式并保存。", + "descriptionEn": "Persist verbose output mode for all bot channels." + } + ] }, { "id": "feature.detached-dispatch", diff --git a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json index fd1ca70369..8ba33cd4e6 100644 --- a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json +++ b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json @@ -4,8 +4,8 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "516e1cab17ad7c33ff1be2777de1c52bb8a47ef0292bed32928843b8d1ee72ae", - "ownerDigest": "f27c231da2e536e4f2123910f34f862b55d21feb0528bc915d4d13edbd528af9", + "digest": "2eb272d6820970e0c8ac677714ca03495729fa4a9cd458f1b89a4de726971107", + "ownerDigest": "df28e5eed6e3190741899ebf236bc5fb426d2469187e437839a349a7136c7c34", "searchAcceptance": [ { "id": "native-image-generation", @@ -177,9 +177,9 @@ "userFacing": 44, "documentedItems": 336, "controlCoverage": { - "direct": 56, + "direct": 58, "delegated": 72, - "interactive": 208, + "interactive": 206, "unsupported": 0 } }, @@ -9128,102 +9128,417 @@ } }, { - "id": "feature.remote-connect:open:connection-methods", + "id": "feature.remote-connect:operation:status", "capabilityId": "feature.remote-connect", "itemIds": [ - "connection-methods" + "start-stop-status", + "bots" ], - "kind": "open", - "risk": "ui", - "executionHost": "presentationSurface", + "kind": "operation", + "risk": "read", + "executionHost": "productHost", "availability": { "desktop": { "available": true }, "cli": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true }, "peer": { "available": true, "requiredCapabilities": [ "product_control_v1", - "product_control_presentation_v1" + "remote_connect_control_v1" ] }, "remoteControl": { "available": true }, "detachedDispatch": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true } }, "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + }, + "outputSchema": { "type": "object", - "additionalProperties": false + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:start", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "start-stop-status", + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "lanIp": { + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" }, "outputSchema": { "type": "object", "additionalProperties": true }, - "openReason": "unstructuredInteraction", + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, "presentationTarget": { "kind": "event", "eventName": "openbitfun:open-remote-connect" } }, { - "id": "feature.remote-connect:open:start-stop-status", + "id": "feature.remote-connect:operation:stop", "capabilityId": "feature.remote-connect", "itemIds": [ - "start-stop-status" + "start-stop-status", + "bots" ], - "kind": "open", - "risk": "ui", - "executionHost": "presentationSurface", + "kind": "operation", + "risk": "write", + "executionHost": "productHost", "availability": { "desktop": { "available": true }, "cli": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true }, "peer": { "available": true, "requiredCapabilities": [ "product_control_v1", - "product_control_presentation_v1" + "remote_connect_control_v1" ] }, "remoteControl": { "available": true }, "detachedDispatch": { - "available": false, - "reason": "This delivery profile has no live presentation surface" + "available": true } }, "inputSchema": { + "additionalProperties": false, + "properties": { + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" + }, + "outputSchema": { "type": "object", - "additionalProperties": false + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:configure-bot", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "credentialsFile": { + "minLength": 1, + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu" + ], + "type": "string" + } + }, + "required": [ + "method", + "credentialsFile" + ], + "type": "object" }, "outputSchema": { "type": "object", "additionalProperties": true }, - "openReason": "unstructuredInteraction", + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, "presentationTarget": { "kind": "event", "eventName": "openbitfun:open-remote-connect" } }, { - "id": "feature.remote-connect:open:network", + "id": "feature.remote-connect:operation:weixin-login-start", "capabilityId": "feature.remote-connect", "itemIds": [ - "network" + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:weixin-login-poll", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "sessionKey": { + "minLength": 1, + "type": "string" + }, + "verifyCode": { + "type": "string" + } + }, + "required": [ + "sessionKey" + ], + "type": "object" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:operation:set-bot-verbose", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "bots" + ], + "kind": "operation", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "remote_connect_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + } + }, + "required": [ + "enabled" + ], + "type": "object" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "provider", + "providerId": "remote-connect" + }, + "presentationTarget": { + "kind": "event", + "eventName": "openbitfun:open-remote-connect" + } + }, + { + "id": "feature.remote-connect:open:connection-methods", + "capabilityId": "feature.remote-connect", + "itemIds": [ + "connection-methods" ], "kind": "open", "risk": "ui", @@ -9266,10 +9581,10 @@ } }, { - "id": "feature.remote-connect:open:bots", + "id": "feature.remote-connect:open:network", "capabilityId": "feature.remote-connect", "itemIds": [ - "bots" + "network" ], "kind": "open", "risk": "ui", @@ -25007,10 +25322,13 @@ "titleZh": "启动、停止 Remote Connect 并查看实时连接状态和设备信息", "titleEn": "Start or stop Remote Connect and inspect live status and device information", "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“启动、停止 Remote Connect 并查看实时连接状态和设备信息”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Start or stop Remote Connect and inspect live status and device information” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user." + "kind": "direct", + "operations": [ + "status", + "start", + "stop" + ], + "options": [] } }, { @@ -25029,10 +25347,17 @@ "titleZh": "配置飞书、Telegram、微信等 Bot 并单独停止 Bot", "titleEn": "Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently", "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "“配置飞书、Telegram、微信等 Bot 并单独停止 Bot”由多个实时状态相关步骤组成,目前没有一个能确定完成整个流程的单一结构化 Command;智能体会打开精确入口,并把后续交互保留在用户可见界面。", - "reasonEn": "“Configure Feishu, Telegram, WeChat, and other bots, and stop a bot independently” spans multiple live-state-dependent steps and currently has no single structured Command that can deterministically complete the whole workflow; the Agent opens the exact entry and keeps the remaining interaction visible to the user." + "kind": "direct", + "operations": [ + "configure-bot", + "weixin-login-start", + "weixin-login-poll", + "set-bot-verbose", + "start", + "stop", + "status" + ], + "options": [] } }, { @@ -25082,18 +25407,187 @@ "agentExamplesZh": [ "打开 Remote Connect", "我想配置手机远程控制", - "带我管理已连接设备" + "带我管理已连接设备", + "启动微信机器人并持续监听消息", + "关闭 Telegram 机器人", + "开启手机网页远控" ], "agentExamplesEn": [ "Open Remote Connect", "I want to configure mobile remote control", - "Take me to connected-device management" + "Take me to connected-device management", + "Start the WeChat bot and keep listening", + "Stop the Telegram bot", + "Enable Mobile Web remote control" ], "destination": { "kind": "event", "eventName": "openbitfun:open-remote-connect" }, - "operations": [], + "operations": [ + { + "id": "status", + "titleZh": "查看远控状态", + "titleEn": "Inspect Remote Connect status", + "descriptionZh": "读取当前执行主机的监听、配对、停用与恢复错误;不返回凭据,监听任务存活不等于消息已完成往返。", + "descriptionEn": "Read listener, pairing, disabled and restore-error state on the executing host without credentials. A live listener task does not prove a message round trip.", + "risk": "read", + "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + } + }, + { + "id": "start", + "titleZh": "启动远控渠道", + "titleEn": "Start a Remote Connect channel", + "descriptionZh": "启动指定机器人或手机网页远控。CLI 自动启动 daemon,退出当前聊天后继续监听。新机器人需将返回的配对码发给机器人;CLI 不支持局域网 Relay。", + "descriptionEn": "Start the selected bot or Mobile Web. CLI starts its daemon and keeps listening after this chat exits. Send the returned pairing code to a new bot. CLI does not host a LAN Relay.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "lanIp": { + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" + } + }, + { + "id": "stop", + "titleZh": "停用远控渠道", + "titleEn": "Stop a Remote Connect channel", + "descriptionZh": "停用选定渠道并保留配置和会话。机器人停用状态跨重启保留。关闭手机网页会同时断开该主机的 Peer 设备路由,机器人保持运行。", + "descriptionEn": "Stop the selected channel while retaining configuration and sessions. Bot disablement survives restart. Stopping Mobile Web also disconnects Peer routing on this host; bots keep running.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "method": { + "enum": [ + "weixin", + "telegram", + "feishu", + "mobile_web", + "lan" + ], + "type": "string" + } + }, + "required": [ + "method" + ], + "type": "object" + } + }, + { + "id": "configure-bot", + "titleZh": "从主机凭据文件配置机器人", + "titleEn": "Configure a bot from a private host credential file", + "descriptionZh": "读取执行主机上用户提供的私有 JSON 凭据文件并保存配置;不会自动启动。文件包含 bot_type 和对应凭据字段,需绝对路径和仅所有者可读权限;不要把凭据贴到聊天中。远程工作区路径不能用作主机凭据路径。", + "descriptionEn": "Load a user-supplied private JSON BotConfig file on the executing host, with bot_type and provider credential fields; save without starting. Requires an absolute host path and owner-only permissions. Do not paste credentials into chat or use a remote-workspace path.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "credentialsFile": { + "minLength": 1, + "type": "string" + }, + "method": { + "enum": [ + "weixin", + "telegram", + "feishu" + ], + "type": "string" + } + }, + "required": [ + "method", + "credentialsFile" + ], + "type": "object" + }, + "argumentScopes": { + "credentialsFile": "productHostLocal" + } + }, + { + "id": "weixin-login-start", + "titleZh": "开始微信扫码登录", + "titleEn": "Begin WeChat QR login", + "descriptionZh": "生成微信登录二维码。CLI TUI 在工具卡片中直接显示 qrTerminal,无需模型重写;其他终端逐字显示,图形界面显示 qrImageUrl,再用 sessionKey 轮询。扫码本身尚未完成机器人监听和配对。", + "descriptionEn": "Create a WeChat login QR. CLI TUI renders qrTerminal in the tool card without model transcription; other terminals show it verbatim and graphical surfaces show qrImageUrl. Poll using sessionKey; scanning alone does not complete listening and pairing.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + } + }, + { + "id": "weixin-login-poll", + "titleZh": "完成微信登录并启动监听", + "titleEn": "Complete WeChat login and start listening", + "descriptionZh": "轮询同一登录会话。确认后在主机保存凭据并启动监听,向用户展示返回的机器人配对码。凭据不会返回给模型。", + "descriptionEn": "Poll the same login session. Confirmation saves credentials on the host and starts listening; show the returned bot pairing code. Credentials are never returned to the model.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "sessionKey": { + "minLength": 1, + "type": "string" + }, + "verifyCode": { + "type": "string" + } + }, + "required": [ + "sessionKey" + ], + "type": "object" + } + }, + { + "id": "set-bot-verbose", + "titleZh": "设置机器人详细输出", + "titleEn": "Set bot verbose output", + "descriptionZh": "切换所有机器人的详细输出模式并保存。", + "descriptionEn": "Persist verbose output mode for all bot channels.", + "risk": "write", + "inputSchema": { + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + } + }, + "required": [ + "enabled" + ], + "type": "object" + } + } + ], "options": [], "searchTerms": [ "feature.remote-connect", @@ -25140,9 +25634,15 @@ "打开 Remote Connect", "我想配置手机远程控制", "带我管理已连接设备", + "启动微信机器人并持续监听消息", + "关闭 Telegram 机器人", + "开启手机网页远控", "Open Remote Connect", "I want to configure mobile remote control", - "Take me to connected-device management" + "Take me to connected-device management", + "Start the WeChat bot and keep listening", + "Stop the Telegram bot", + "Enable Mobile Web remote control" ], "docsUrl": "https://playbook.openbitfun.com/capabilities/feature.remote-connect/" }, diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts index 39cda1c70a..0f6290ce2c 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts @@ -730,6 +730,17 @@ describe('PeerDeviceTransportAdapter queue', () => { expect(deviceRpc).toHaveBeenCalledTimes(1); }); + it('requires the Remote Connect capability before executing a management operation', async () => { + const deviceRpc = vi.fn().mockResolvedValue(JSON.stringify({ resp: 'host_invoke_result', ok: true, value: { started: true } })); + const adapter = new PeerDeviceTransportAdapter('peer-1', deviceRpc, { supportsProductControlV1: true }); + const request = { request: { action: 'execute', capabilityId: 'feature.remote-connect', operationId: 'start', arguments: { method: 'weixin' } } }; + await expect(adapter.request('product_control_invoke', request)).rejects.toThrow('remote_connect_control_v1_unsupported'); + expect(deviceRpc).not.toHaveBeenCalled(); + const capable = new PeerDeviceTransportAdapter('peer-1', deviceRpc, { supportsProductControlV1: true, supportsRemoteConnectControlV1: true }); + await expect(capable.request('product_control_invoke', request)).resolves.toEqual({ started: true }); + expect(deviceRpc).toHaveBeenCalledTimes(1); + }); + it('preserves a session conflict returned by the Peer Host without replaying it', async () => { const deviceRpc = vi.fn().mockResolvedValue(JSON.stringify({ resp: 'host_invoke_result', diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts index 52103dd085..2a4b0e37fd 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts @@ -309,6 +309,7 @@ export interface PeerDeviceTransportHooks { supportsComputerUseSharingV1?: boolean; /** Enables the versioned typed ProductControl HostInvoke contract. */ supportsProductControlV1?: boolean; + supportsRemoteConnectControlV1?: boolean; } interface HostInvokeResultEnvelope { @@ -449,6 +450,7 @@ export class PeerDeviceTransportAdapter implements ITransportAdapter { | 'supportsBtwModelPoolSelectionV1' | 'supportsComputerUseSharingV1' | 'supportsProductControlV1' + | 'supportsRemoteConnectControlV1' >, ): void { this.hooks = { ...this.hooks, ...capabilities }; @@ -596,6 +598,17 @@ export class PeerDeviceTransportAdapter implements ITransportAdapter { ); } + if ( + action === 'product_control_invoke' + && params?.request?.action === 'execute' + && params?.request?.capabilityId === 'feature.remote-connect' + && this.hooks.supportsRemoteConnectControlV1 !== true + ) { + throw new PeerProductCommandError( + 'remote_connect_control_v1_unsupported: Update the executing Peer host to manage Remote Connect bots and Mobile Web', + ); + } + const issuedBindingEpoch = this.surfaceBindingEpoch; const priority = peerInvokePriorityFor(action); return this.enqueue( diff --git a/src/web-ui/src/infrastructure/api/generated/productControl.ts b/src/web-ui/src/infrastructure/api/generated/productControl.ts index c7eb316db5..194486b12d 100644 --- a/src/web-ui/src/infrastructure/api/generated/productControl.ts +++ b/src/web-ui/src/infrastructure/api/generated/productControl.ts @@ -1,5 +1,5 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. -export const PRODUCT_CONTROL_GRAPH_DIGEST = "516e1cab17ad7c33ff1be2777de1c52bb8a47ef0292bed32928843b8d1ee72ae" as const; +export const PRODUCT_CONTROL_GRAPH_DIGEST = "2eb272d6820970e0c8ac677714ca03495729fa4a9cd458f1b89a4de726971107" as const; export type ProductControlCapabilityId = "feature.ai-assistant" | "feature.agents" | "feature.personal-assistants" | "feature.projects" | "feature.files-editor" | "feature.terminal" | "feature.git" | "feature.code-review" | "feature.browser" | "feature.computer-use" | "feature.skills" | "feature.miniapps" | "feature.canvas" | "feature.tasks-automation" | "feature.insights" | "feature.ecosystem-compatibility" | "feature.remote-workspaces" | "feature.remote-connect" | "feature.detached-dispatch" | "feature.pages" | "feature.voice-input" | "feature.desktop-pet" | "feature.desktop-cards" | "setting.application.general" | "setting.application.appearance" | "setting.application.pet" | "setting.application.input" | "setting.application.shortcuts" | "setting.application.development" | "setting.ai.models" | "setting.ai.memory" | "setting.workspace.session" | "setting.workspace.worktrees" | "setting.tools.execution" | "setting.application.terminal" | "setting.tools.desktop-control" | "setting.tools.browser-control" | "setting.tools.automation" | "setting.tools.web-search" | "setting.tools.mcp" | "setting.tools.acp" | "setting.data.usage" | "setting.data.archived" | "setting.data.diagnostics"; @@ -68,7 +68,7 @@ export interface ProductControlOperationIdsByCapability { "feature.insights": never; "feature.ecosystem-compatibility": never; "feature.remote-workspaces": never; - "feature.remote-connect": never; + "feature.remote-connect": "status" | "start" | "stop" | "configure-bot" | "weixin-login-start" | "weixin-login-poll" | "set-bot-verbose"; "feature.detached-dispatch": never; "feature.pages": never; "feature.voice-input": never; diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index c5b6d118e9..2b533287f9 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:96fc351cf4dd6568" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:0e26746186f2b4ad" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -196,6 +196,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "wsl_workspaces_v1", "computer_use_sharing_v1", "product_control_v1", + "remote_connect_control_v1", "product_control_native_v1", "product_control_presentation_v1", "cancel_tool", @@ -243,6 +244,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "wsl_workspaces_v1", "computer_use_sharing_v1", "product_control_v1", + "remote_connect_control_v1", "product_control_native_v1", "product_control_presentation_v1", "cancel_tool", @@ -269,6 +271,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "token_usage_statistics", "model_channel_routing_v1", "product_control_v1", + "remote_connect_control_v1", "cancel_tool", "tool_catalog", "session_trajectory_v1", diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 0b0bd916f2..7a6f0050cf 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -68,6 +68,7 @@ export interface PeerHostCapabilities { readonly computerUseSharingV1?: boolean; /** Typed ProductControl HostInvoke, including shared config read-back. */ readonly productControlV1?: boolean; + readonly remoteConnectControlV1?: boolean; /** * ProductControl definitions that need a host-native provider or a live * presentation surface. The controller does not pre-check these: the peer @@ -206,6 +207,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = { modelPoolSelectionV1: false, computerUseSharingV1: false, productControlV1: false, + remoteConnectControlV1: false, productControlNativeV1: false, productControlPresentationV1: false, // Unknown (not yet probed) — not the same as `false` (probed, unsupported). @@ -466,6 +468,7 @@ export class PeerConnectionManager { supportsBtwModelPoolSelectionV1: entry.capabilities.btwModelPoolSelectionV1, supportsComputerUseSharingV1: entry.capabilities.computerUseSharingV1, supportsProductControlV1: entry.capabilities.productControlV1, + supportsRemoteConnectControlV1: entry.capabilities.remoteConnectControlV1, }); entry.health = 'ready'; this.scheduleKeepalive(entry); @@ -564,6 +567,7 @@ export class PeerConnectionManager { modelPoolSelectionV1: caps?.model_pool_selection_v1 === true, computerUseSharingV1: caps?.computer_use_sharing_v1 === true, productControlV1: caps?.product_control_v1 === true, + remoteConnectControlV1: caps?.remote_connect_control_v1 === true, productControlNativeV1: caps?.product_control_native_v1 === true, productControlPresentationV1: caps?.product_control_presentation_v1 === true, @@ -666,6 +670,7 @@ export class PeerConnectionManager { supportsBtwModelPoolSelectionV1: capabilities.btwModelPoolSelectionV1, supportsComputerUseSharingV1: capabilities.computerUseSharingV1, supportsProductControlV1: capabilities.productControlV1, + supportsRemoteConnectControlV1: capabilities.remoteConnectControlV1, }); entry.consecutiveFailures = 0; const recovered = entry.health !== 'ready'; diff --git a/src/web-ui/src/infrastructure/peer-device/README.md b/src/web-ui/src/infrastructure/peer-device/README.md index be028e26fa..8b2834c19a 100644 --- a/src/web-ui/src/infrastructure/peer-device/README.md +++ b/src/web-ui/src/infrastructure/peer-device/README.md @@ -221,7 +221,12 @@ listener alone recovers an interaction emitted before attachment. to the controller. Definitions that need a native provider or a live UI additionally declare `product_control_native_v1` or `product_control_presentation_v1`; the CLI host advertises neither and - returns a typed unsupported result. `mark_openbitfun_control_surface_ready`, + returns a typed unsupported result. Remote Connect management instead uses the + narrow `remote_connect_control_v1` capability, advertised by both Desktop and + CLI; its operations execute on the selected host and fail before RPC on older + peers. Direct Peer RPC refuses Relay start/stop because it holds that route's + response lease; submit these operations through a Claw turn instead. + `mark_openbitfun_control_surface_ready`, `mark_openbitfun_control_surface_unready`, and `report_openbitfun_control_result` describe or acknowledge the controller window's live Web UI and therefore remain `LOCAL_ONLY` in the frontend, Desktop host, and CLI host lists. A