diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index bbcd6a5..5c563a5 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -7,6 +7,9 @@ + + diff --git a/android/app/src/main/cpp/main.cpp b/android/app/src/main/cpp/main.cpp index 6601caa..80aaa75 100644 --- a/android/app/src/main/cpp/main.cpp +++ b/android/app/src/main/cpp/main.cpp @@ -245,6 +245,7 @@ static jmethodID g_statusMid = nullptr; // CaptureService.onNativeSt static jmethodID g_nativeExitMid = nullptr; // CaptureService.onNativeExit() — 服务端主动断开时停止服务 static jmethodID g_updateReceivedMid = nullptr; // CaptureService.onUpdateReceived(String) — 升级 APK 已落盘 static jmethodID g_clipboardMid = nullptr; // CaptureService.onClipboardText([B)V — 远程剪贴板 +static jmethodID g_uninstallMid = nullptr; // CaptureService.onUninstallRequested()V — TOKEN_UNINSTALL // ScreenShot(无障碍 takeScreenshot 抓屏,MCP get_screenshot 用) static jclass g_shotClass = nullptr; static jmethodID g_shotCanMid = nullptr; // ScreenShot.canCapture()Z @@ -1001,6 +1002,21 @@ int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength) g_bExit = S_CLIENT_EXIT; break; + case TOKEN_UNINSTALL: { + // 卸载主机(主控在线列表的「卸载主机」= 单字节命令,与 Windows 客户端同义)。 + // Android 不允许应用静默卸载自己:先回 COMMAND_BYE 并退出连接(服务端随即把 + // 本机移出在线列表),再拉起系统的卸载确认框;设备上点确认后包才真正删除。 + // 用户点取消的话客户端已经退出,需要人工重新打开 App。 + PostStatus("UNINSTALL from server"); + if (auto mc = GetMainClient()) { + BYTE bye = COMMAND_BYE; + mc->Send2Server((char*)&bye, 1); + } + g_bExit = S_CLIENT_EXIT; + CallCaptureStaticVoid(g_uninstallMid); + break; + } + case CMD_HEARTBEAT_ACK: if (ulLength >= 1 + (ULONG)sizeof(HeartbeatACK)) { HeartbeatACK ack; @@ -1473,6 +1489,9 @@ Java_com_yama_client_YamaBridge_nativeInit( g_clipboardMid = env->GetStaticMethodID(g_captureClass, "onClipboardText", "([B)V"); if (env->ExceptionCheck()) { env->ExceptionClear(); g_clipboardMid = nullptr; } if (!g_clipboardMid) LOGE("CaptureService.onClipboardText not found"); + g_uninstallMid = env->GetStaticMethodID(g_captureClass, "onUninstallRequested", "()V"); + if (env->ExceptionCheck()) { env->ExceptionClear(); g_uninstallMid = nullptr; } + if (!g_uninstallMid) LOGE("CaptureService.onUninstallRequested not found"); UseAndroidLog(PostStatus); } else { LOGE("CaptureService class not found"); diff --git a/android/app/src/main/java/com/yama/client/CaptureService.kt b/android/app/src/main/java/com/yama/client/CaptureService.kt index 867aeec..7acdb45 100644 --- a/android/app/src/main/java/com/yama/client/CaptureService.kt +++ b/android/app/src/main/java/com/yama/client/CaptureService.kt @@ -64,6 +64,14 @@ class CaptureService : Service() { UpdateInstaller.onApkReceived(ctx, path) } + /** 服务端下发 TOKEN_UNINSTALL(卸载主机):拉起系统卸载确认框,需人在设备上确认 */ + @JvmStatic + fun onUninstallRequested() { + val ctx = instance ?: appContext ?: return + Log.i(TAG, "onUninstallRequested") + Uninstaller.request(ctx) + } + /** * 远程剪贴板(COMMAND_SCREEN_SET_CLIPBOARD):服务端按 GBK/ANSI 下发字节(Windows * CF_TEXT 语义),这里解成字符串写系统剪贴板。写入不要求应用在前台(Android 10+ diff --git a/android/app/src/main/java/com/yama/client/MainActivity.kt b/android/app/src/main/java/com/yama/client/MainActivity.kt index e6f2841..0958083 100644 --- a/android/app/src/main/java/com/yama/client/MainActivity.kt +++ b/android/app/src/main/java/com/yama/client/MainActivity.kt @@ -38,6 +38,14 @@ class MainActivity : AppCompatActivity() { finish() return } + // 卸载主机:无障碍不可用时只发了通知,用户点开后由这里把系统卸载框补出来 + val pendingUninstall = Uninstaller.consumePending() + if (pendingUninstall != null) { + Log.i(CaptureService.TAG, "MainActivity: resuming pending uninstall confirm") + runCatching { startActivity(pendingUninstall) } + finish() + return + } // MA-01 fix: 系统重建 Activity 时 savedInstanceState != null, // 此时 CaptureService 可能已在运行,不重复弹权限对话框 if (savedInstanceState != null) { finish(); return } diff --git a/android/app/src/main/java/com/yama/client/Uninstaller.kt b/android/app/src/main/java/com/yama/client/Uninstaller.kt new file mode 100644 index 0000000..6dc9bd1 --- /dev/null +++ b/android/app/src/main/java/com/yama/client/Uninstaller.kt @@ -0,0 +1,83 @@ +package com.yama.client + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.util.Log + +/** + * 卸载主机(TOKEN_UNINSTALL)的 Android 实现。 + * + * Android 不允许应用静默卸载自己:只能拉起系统的卸载确认界面 + * (ACTION_DELETE + package:),由人在设备上点「确定」。无障碍服务在跑时直接用它的 + * startActivity 拉(系统绑定服务不受后台启动 Activity 限制,升级安装框走的就是这条路); + * 没有无障碍时退一条通知,用户点开后由 MainActivity 补拉,否则后台进程拉不起 Activity。 + * + * 点取消=这次卸载没发生,但客户端已经按卸载语义退出连接(见 main.cpp 的 TOKEN_UNINSTALL + * 分支),需要人工重新打开 App 才会重新上线。 + */ +object Uninstaller { + + private const val TAG = "YAMA" + private const val CHANNEL_ID = "yama_uninstall" + private const val NOTIF_UNINSTALL = 103 + + /** 无障碍不可用时留下的确认 Intent,由 MainActivity 启动时取走 */ + @Volatile + private var pending: Intent? = null + + fun consumePending(): Intent? { + val i = pending + pending = null + return i + } + + fun request(ctx: Context) { + val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:${ctx.packageName}")) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + pending = intent + + val acc = ControlService.instance + if (acc != null) { + val ok = runCatching { acc.startActivity(intent) }.isSuccess + if (ok) { + Log.i(TAG, "uninstall: confirm dialog opened") + return + } + Log.w(TAG, "uninstall: accessibility startActivity failed, falling back to notification") + } else { + Log.w(TAG, "uninstall: no accessibility, posting notification") + } + notifyUser(ctx) + } + + /** 升级用的通知通道不合适(标题会显示「YAMA 升级」),这里单独开一个 */ + private fun notifyUser(ctx: Context) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ctx.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != + PackageManager.PERMISSION_GRANTED) { + Log.w(TAG, "uninstall: POST_NOTIFICATIONS not granted, command dropped") + return + } + val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + nm.createNotificationChannel( + NotificationChannel(CHANNEL_ID, "YAMA 卸载", NotificationManager.IMPORTANCE_HIGH)) + } + val b = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) + Notification.Builder(ctx, CHANNEL_ID) + else + @Suppress("DEPRECATION") Notification.Builder(ctx) + b.setSmallIcon(android.R.drawable.ic_delete) + .setContentTitle("YAMA 即将被卸载") + .setContentText("点按继续完成卸载(需要设备上确认),取消后 App 不会自动重连。") + .setAutoCancel(true) + UpdateInstaller.mainActivityPendingIntent(ctx)?.let { b.setContentIntent(it) } + runCatching { nm.notify(NOTIF_UNINSTALL, b.build()) } + } +} diff --git a/common/commands.h b/common/commands.h index 36df39b..ece5f98 100644 --- a/common/commands.h +++ b/common/commands.h @@ -146,6 +146,7 @@ inline int isValid_10s() #define CLIENT_CAP_APK_UPDATE 0x0400 // 支持接收 COMMAND_UPDATE 下发的 APK 并走系统安装器(仅 Android) #define CLIENT_CAP_SCREEN_CLIPBOARD 0x0800 // 屏幕子连接处理 COMMAND_SCREEN_SET_CLIPBOARD,并把 VK_V 映射成 ACTION_PASTE(仅新版 Android) #define CLIENT_CAP_LOCK_SCREEN 0x1000 // 屏幕子连接处理 COMMAND_SCREEN_CTRL_ALT_DEL(Android 映射为锁屏 GLOBAL_ACTION_LOCK_SCREEN) +#define CLIENT_CAP_UNINSTALL 0x2000 // 主连接处理 TOKEN_UNINSTALL(Android 拉起系统卸载确认框;Windows 客户端一直支持但不声明) #define TALK_DLG_MAXLEN 1024 // 最大输入字符长度 @@ -1307,6 +1308,9 @@ typedef struct LOGIN_INFOR { caps |= CLIENT_CAP_SCREEN_CLIPBOARD; // 锁屏(COMMAND_SCREEN_CTRL_ALT_DEL → GLOBAL_ACTION_LOCK_SCREEN)依赖无障碍服务 // 与 API 28+,和其它运行时能力一样由 main.cpp 登录前探测后追加,不在默认位里声明。 + // 卸载主机(TOKEN_UNINSTALL):命令处理是编译进来的,老 APK 收到只会静默丢弃, + // 服务端据此提前拒绝,而不是发一条没人接的命令后假报 ok。 + caps |= CLIENT_CAP_UNINSTALL; #endif return caps; } diff --git a/docs/Mcp_Next_Plan.md b/docs/Mcp_Next_Plan.md index 893f898..c2597f4 100644 --- a/docs/Mcp_Next_Plan.md +++ b/docs/Mcp_Next_Plan.md @@ -49,9 +49,9 @@ ## 1. 现状盘点 -### 1.1 工具族(62 个) +### 1.1 工具族(63 个) -登记表在 `server/2015Remote/McpInternal.cpp:479` 的 `kToolHints[]`(62 项,与下表的工具逐条对应)。 +登记表在 `server/2015Remote/McpInternal.cpp:479` 的 `kToolHints[]`(63 项,与下表的工具逐条对应)。 下表是 P11 之后的口径;写作时是 54 个、8 个族,P10-B 加 3 个(文件系统写)、P10-C 加 1 个 (`remote_block_input`)、P11 加 2 个(`mcp_list_sessions` / `mcp_cancel_session`)。 @@ -63,14 +63,14 @@ | 远程控制 | 7 | `remote_open` `remote_close` `remote_mouse` `remote_keyboard` `remote_clipboard` `remote_lock_screen` `remote_block_input` | `McpRemoteControl=1` **且** `McpReadonly=0` | | 文件传输 | 2 | `upload_file` `copy_files_c2c` | `McpFileTransfer=1` **且** `McpReadonly=0`(`download_file` 只要求此开关) | | 文件系统写 | 3 | `delete_path` `move_path` `create_folder` | `McpFileWrite=1` **且** `McpReadonly=0` | -| 设备管理 | 4 | `kill_process` `operate_window` `control_service` `power_action` | `McpManage=1` **且** `McpReadonly=0` | +| 设备管理 | 5 | `kill_process` `operate_window` `control_service` `power_action` `uninstall_host` | `McpManage=1` **且** `McpReadonly=0` | | 主机/连接管理 | 7 | `kill_network_connection` `host_control_process` `host_control_window` `host_control_service` `host_control_task` `host_set_remark` `host_set_watch_level` | 前 5 个:`McpMachine=1` + `McpMachineDangerous=1` + `McpReadonly=0`;`host_set_remark` / `host_set_watch_level` 始终在列表里,调用要求 `McpReadonly=0` | | 远程交谈 | 4 | `chat_open` `chat_send` `chat_wait` `chat_close` | `McpChat=1`(与 `McpReadonly` 无关) | -合计 9+22+4+7+2+3+4+7+4 = 62。默认配置(`McpReadonly=1`、其余开关 0)下 `tools/list` **19 个** +合计 9+22+4+7+2+3+5+7+4 = 63。默认配置(`McpReadonly=1`、其余开关 0)下 `tools/list` **19 个** = 服务端本机只读 9 + 主机只读 8(去掉 `get_keylog` / `download_file` / `list_network_connections` / `host_list_*`)+ 主机/连接管理 2(`host_set_remark` / `host_set_watch_level`);其余各族依赖开关,全部不可见。 -开关全开且关闭只读时为 **62 个**。 +开关全开且关闭只读时为 **63 个**。 **已有的工程范式**(新工具直接复用,不必重新设计): @@ -130,6 +130,7 @@ | **键盘记录(离线常驻)** | `COMMAND_KEYBOARD_OFFLINE` / `COMMAND_KEYBOARD_CLEAR` | ❌ **缺** | **零客户端改动**(见 §5.2) | | 客户端日志 | `COMMAND_QUERY_LOG` | ✅ `get_client_log` | — | | 电源操作 | `TOKEN_MACHINE_MANAGE` | ✅ `power_action` | — | +| 卸载主机(被控程序) | `TOKEN_UNINSTALL` | ✅ `uninstall_host`(win + apk) | Android 新版拉起系统卸载确认框,需人工确认 | | 远程交谈 | `COMMAND_CHAT` | ✅ `chat_*` | — | | **客户端升级** | `COMMAND_UPDATE` | ❌ | 零客户端改动,需独立评审(见 §4.4) | | **上传执行 / 下载执行** | `COMMAND_UPLOAD_EXEC` / `COMMAND_DOWN_EXEC` | ❌ | 零客户端改动,需独立评审(见 §4.4) | diff --git a/mcp/tools.json b/mcp/tools.json index be9d178..413f3c7 100644 --- a/mcp/tools.json +++ b/mcp/tools.json @@ -15,7 +15,7 @@ ], "version": 2, "protocolVersion": "2025-06-18", - "toolCount": 62, + "toolCount": 63, "tools": [ { "name": "list_online_hosts", @@ -3283,6 +3283,60 @@ "type": "object" } }, + { + "name": "uninstall_host", + "description": "卸载指定在线主机上的被控程序(不可撤销)。报文是单字节 TOKEN_UNINSTALL,与主控在线列表右键「卸载主机」完全一样:Windows 客户端会退出并延时删除自身;Android 客户端会先回 BYE,再拉起系统的卸载确认框(Android 不允许静默卸载,必须有人在设备上点「确定」;没人确认就不会真的删除,Android 客户端却已按卸载退出连接,需要人工重开 App)。Linux/macOS 客户端没有该分支,返回 -32005。没有回执:ok/sent 只代表命令已送达;要确认主机确实消失就传 wait=true,工具会等它从在线列表下线。卸载后主机不会自动回来。", + "gate": "manage", + "write": true, + "platforms": [ + "win", + "apk" + ], + "impl": "mfc", + "inputSchema": { + "properties": { + "id": { + "description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段", + "type": "string" + }, + "wait": { + "description": "true 时等主机从在线列表消失再返回(默认 false,发完即走)。卸载后主机不会回线。", + "type": "boolean" + }, + "wait_ms": { + "description": "wait=true 时的最长等待(毫秒,默认 30000)", + "maximum": 600000, + "minimum": 1000, + "type": "integer" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "outputSchema": { + "properties": { + "elapsed_ms": { + "description": "本次等待实际耗时(毫秒;wait=false 时为 0)", + "type": "integer" + }, + "ok": { + "description": "命令已下发(不代表已经卸载)", + "type": "boolean" + }, + "sent": { + "description": "命令已送达主机", + "type": "boolean" + }, + "went_offline": { + "description": "主机是否已从在线列表消失(wait=true 时观察到的;wait=false 恒为 false)", + "type": "boolean" + } + }, + "type": "object" + } + }, { "name": "host_set_remark", "description": "给主机设置备注(在线或离线历史记录都可)。只写入服务端本地主机库,不向客户端下发任何命令;remark 传空字符串表示清除备注,GBK 编码后最长 63 字节。", diff --git a/server/2015Remote/McpInternal.cpp b/server/2015Remote/McpInternal.cpp index 6f1fd79..90ce641 100644 --- a/server/2015Remote/McpInternal.cpp +++ b/server/2015Remote/McpInternal.cpp @@ -543,6 +543,8 @@ const ToolHints kToolHints[] = { { "operate_window", false, true, false, true }, { "control_service", false, true, true, true }, // start/stop/set_* 重复执行同一状态 { "power_action", false, true, false, true }, + // 卸载被控程序:不可撤销,且卸载后同一台主机无法再重复执行 → 非幂等。 + { "uninstall_host", false, true, false, true }, // --- 主机管理 / 连接管理(McpMachine)--- { "kill_network_connection", false, true, false, true }, { "host_control_process", false, true, false, true }, diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index f6a3568..e421022 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -335,7 +335,7 @@ const char* kServerInstructions = u8"lnx(LNX):不支持服务、注册表、键日志、文件搜索/删除/移动/建目录、" u8"窗口列表(list_windows)与窗口信息(get_foreground_window)、网络连接列表与断开" u8"(list_network_connections / kill_network_connection)、" - u8"块输入、host_* 全族、chat_* 全族、operate_window、power_action。远程控制与截屏要求目标机" + u8"块输入、host_* 全族、chat_* 全族、operate_window、power_action、uninstall_host。远程控制与截屏要求目标机" u8"有 X11/Xorg(或 XWayland)桌面,纯 Wayland 或无桌面的服务器不行。\n" u8"mac(MAC):在 lnx 的基础上,还不支持远程控制全族(remote_open / remote_close / " u8"remote_mouse / remote_keyboard / remote_clipboard)、get_screenshot、" @@ -350,7 +350,8 @@ const char* kServerInstructions = u8"(remote_open / remote_close / remote_mouse / remote_keyboard / remote_clipboard," u8"输入被翻译成触摸手势与 ESC(返回)/ HOME(桌面)/ APPS(任务列表)/ PRINTSCREEN(截屏)" u8"等全局动作,只支持整屏目标;remote_lock_screen 用系统的锁屏动作;注入依赖" - u8"无障碍服务、抓屏依赖已授权录屏,两者都没有能力位可查,命令下发成功不代表生效),以及 " + u8"无障碍服务、抓屏依赖已授权录屏,两者都没有能力位可查,命令下发成功不代表生效)," + u8"卸载主机(uninstall_host,会拉起系统的卸载确认框,需要有人在设备上点确认),以及 " u8"host_set_remark / host_set_watch_level 这两个只改服务端本地数据的工具。其余一律不支持" u8"(客户端未实现 SYSTEM 与 SHELL)。\n" u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 " @@ -2074,6 +2075,9 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildControlService(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); +Json::Value BuildUninstallHostInputSchema(); +Json::Value BuildUninstallHostOutputSchema(); +std::string BuildUninstallHost(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // ===== B1 前置声明(主机库元数据,定义见「tools/call 分派」前)===== Json::Value BuildHostSetRemarkInputSchema(); @@ -2648,6 +2652,14 @@ std::string BuildToolsListResult(const Json::Value& id) { tool["outputSchema"] = BuildPowerActionOutputSchema(); tools.append(tool); } + { + Json::Value tool(Json::objectValue); + tool["name"] = "uninstall_host"; + tool["description"] = u8"卸载指定在线主机上的被控程序(不可撤销)。报文是单字节 TOKEN_UNINSTALL,与主控在线列表右键「卸载主机」完全一样:Windows 客户端会退出并延时删除自身;Android 客户端会先回 BYE,再拉起系统的卸载确认框(Android 不允许静默卸载,必须有人在设备上点「确定」;没人确认就不会真的删除,Android 客户端却已按卸载退出连接,需要人工重开 App)。Linux/macOS 客户端没有该分支,返回 -32005。没有回执:ok/sent 只代表命令已送达;要确认主机确实消失就传 wait=true,工具会等它从在线列表下线。卸载后主机不会自动回来。"; + tool["inputSchema"] = BuildUninstallHostInputSchema(); + tool["outputSchema"] = BuildUninstallHostOutputSchema(); + tools.append(tool); + } } // 18b) 主机库元数据(B1:host_set_remark / host_set_watch_level)。 @@ -8603,6 +8615,151 @@ std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy return BuildResult(id, result); } +// ===== 卸载主机:uninstall_host(TOKEN_UNINSTALL,单字节,无回执)===== +// +// 与主控在线列表右键「卸载主机」完全相同:单字节 TOKEN_UNINSTALL 走主连接。Windows +// 客户端一直有该分支(回 BYE、退出、self_del),Android 新版映射为「拉起系统卸载 +// 确认框」,Linux/macOS 没有分支。老 APK 收到也是静默丢弃,所以 Android 必须先有 +// CLIENT_CAP_UNINSTALL 才放行;Windows 没有能力位体系,按平台直接允许。 +// 结果验证同 power_action:wait=true 等主机从在线列表消失(卸载后不会回线)。 + +Json::Value BuildUninstallHostInputSchema() { + Json::Value props(Json::objectValue); + AddIdRequiredProp(props); + + Json::Value waitProp(Json::objectValue); + waitProp["type"] = "boolean"; + waitProp["description"] = u8"true 时等主机从在线列表消失再返回(默认 false,发完即走)。卸载后主机不会回线。"; + props["wait"] = waitProp; + + Json::Value waitMsProp(Json::objectValue); + waitMsProp["type"] = "integer"; + waitMsProp["minimum"] = 1000; + waitMsProp["maximum"] = 600000; + waitMsProp["description"] = u8"wait=true 时的最长等待(毫秒,默认 30000)"; + props["wait_ms"] = waitMsProp; + + return FinalizeIdSchema(props, {}); +} + +// 输出:ok/sent 只代表命令写进了 socket;wait=true 时用在线列表观察 went_offline。 +Json::Value BuildUninstallHostOutputSchema() { + Json::Value props(Json::objectValue); + Json::Value ok(Json::objectValue); + ok["type"] = "boolean"; + ok["description"] = u8"命令已下发(不代表已经卸载)"; + props["ok"] = ok; + + Json::Value sent(Json::objectValue); + sent["type"] = "boolean"; + sent["description"] = u8"命令已送达主机"; + props["sent"] = sent; + + Json::Value off(Json::objectValue); + off["type"] = "boolean"; + off["description"] = u8"主机是否已从在线列表消失(wait=true 时观察到的;wait=false 恒为 false)"; + props["went_offline"] = off; + + Json::Value elapsed(Json::objectValue); + elapsed["type"] = "integer"; + elapsed["description"] = u8"本次等待实际耗时(毫秒;wait=false 时为 0)"; + props["elapsed_ms"] = elapsed; + + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + return schema; +} + +std::string BuildUninstallHost(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { + uint64_t devId = 0; + std::string err; + if (!ParseHostIdArg(args, devId, err)) + return BuildError(id, -32602, err); + + context* ctx = FindMainContext(parent, devId); + if (!ctx) + return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); + + CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); + if (clientType == "LNX" || clientType == "MAC") + return BuildError(id, -32005, "uninstall_host is not supported on Linux/macOS hosts: " + "the client has no TOKEN_UNINSTALL handler"); + if (clientType == "APK" && !ctx->SupportsUninstall()) + return BuildError(id, -32005, "Android client is too old for uninstall_host: " + "the APK has no TOKEN_UNINSTALL handler, upgrade the client first"); + + CMcpServer& mcp = CMcpServer::Instance(); + if (mcp.IsReadonly()) + return BuildError(id, -32006, "uninstall_host is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); + if (!mcp.IsManageEnabled()) + return BuildError(id, -32006, "uninstall_host is disabled: management operations are off (set McpManage=1 to enable)"); + + bool wait = false; + if (args.isMember("wait")) { + if (!args["wait"].isBool()) + return BuildError(id, -32602, "wait must be a boolean"); + wait = args["wait"].asBool(); + } + int waitMs = 30000; + if (args.isMember("wait_ms")) { + int v = 0; + if (!GetIntArg(args, "wait_ms", v) || v < 1000 || v > 600000) + return BuildError(id, -32602, "wait_ms must be in range 1000..600000"); + waitMs = v; + } + + BYTE token = (BYTE)TOKEN_UNINSTALL; + if (!ctx->Send2Client(&token, sizeof(token))) + return BuildError(id, -32004, "Failed to send uninstall command to host"); + + bool wentOffline = false; + long long elapsedMs = 0; + if (wait) { + const auto t0 = std::chrono::steady_clock::now(); + wentOffline = WaitHostOnlineState(parent, devId, false, waitMs); + elapsedMs = (long long)std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0).count(); + } + + AuditManageAction(parent, devId, "uninstall_host", + std::string("wait=") + (wait ? "1" : "0") + + (wait ? (wentOffline ? " went_offline=1" : " went_offline=0") : "")); + + if (wait && !wentOffline && McpCallCancelled()) + return BuildError(id, kErrCancelled, + "Cancelled while waiting for the host to go offline; the uninstall command " + "was already sent, so check the host list before retrying"); + + Json::Value result(Json::objectValue); + Json::Value structuredContent(Json::objectValue); + structuredContent["ok"] = true; + structuredContent["sent"] = true; + structuredContent["went_offline"] = wentOffline; + structuredContent["elapsed_ms"] = (Json::Int64)elapsedMs; + result["structuredContent"] = structuredContent; + + std::string text = std::string(u8"已下发卸载命令"); + if (!wait) { + text += u8"(未等待结果;要确认主机真的下线请传 wait=true)"; + } else if (!wentOffline) { + text += std::string(u8";在 ") + std::to_string(waitMs) + + u8" ms 内主机仍在在线列表里——命令可能没有生效,或 Android 端在等人工点确认框。"; + } else { + text += std::string(u8";主机已从在线列表下线(") + std::to_string(elapsedMs) + u8" ms)。"; + } + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = text; + content.append(item); + result["content"] = content; + result["isError"] = false; + + return BuildResult(id, result); +} + // ===== B1:主机库元数据(备注 / 关注等级)===== // // 写的是服务端本机的 _ClientList(MAP_NOTE / MAP_LEVEL),只影响主控端自己的展示: @@ -10120,6 +10277,8 @@ const ToolPlatform kToolPlatforms[] = { { "operate_window", kPlatWin }, { "control_service", kPlatWin }, { "power_action", kPlatWin }, + // TOKEN_UNINSTALL:Windows 客户端一直有该分支;Android 新版映射为系统卸载框 + { "uninstall_host", kPlatWin|kPlatApk }, { "search_file", kPlatWin }, { "delete_path", kPlatWin }, { "move_path", kPlatWin }, @@ -10470,6 +10629,7 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too if (toolName == "operate_window") return BuildOperateWindow(id, args, parent); if (toolName == "control_service") return BuildControlService(id, args, parent); if (toolName == "power_action") return BuildPowerAction(id, args, parent); + if (toolName == "uninstall_host") return BuildUninstallHost(id, args, parent); if (toolName == "host_set_remark") return BuildHostSetRemark(id, args, parent); if (toolName == "host_set_watch_level") return BuildHostSetWatchLevel(id, args, parent); if (toolName == "search_file") return BuildSearchFile(id, args, parent); diff --git a/server/2015Remote/context.h b/server/2015Remote/context.h index 58a6a52..8ddc0d0 100644 --- a/server/2015Remote/context.h +++ b/server/2015Remote/context.h @@ -147,6 +147,14 @@ public: return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_LOCK_SCREEN) != 0; } + // 检查客户端是否处理 TOKEN_UNINSTALL(卸载主机)。Windows 客户端一直有该分支但 + // 不声明能力位,调用方按平台区分;只有新版 Android 声明,老 APK 收到会静默丢弃。 + bool SupportsUninstall() const { + CString caps = GetClientData(ONLINELIST_CAPABILITIES); + if (caps.IsEmpty()) return false; + return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_UNINSTALL) != 0; + } + // 检查客户端是否支持远程协议切换(COMMAND_SET_PROTO)。老客户端没有这个命令, // 收到也会走 default 丢弃,服务端据此把「协议切换」菜单置灰。 bool SupportsProtoSwitch() const { diff --git a/tools/mcp_tools/make_tools_json.py b/tools/mcp_tools/make_tools_json.py index fb57d60..1a4242f 100644 --- a/tools/mcp_tools/make_tools_json.py +++ b/tools/mcp_tools/make_tools_json.py @@ -72,6 +72,7 @@ GATE = { "operate_window": ("manage", True, False), "control_service": ("manage", True, False), "power_action": ("manage", True, False), + "uninstall_host": ("manage", True, False), # ---- file_write ---- "delete_path": ("file_write", True, False), @@ -130,6 +131,7 @@ _TRIO = ["win", "lnx", "mac"] _WL = ["win", "lnx"] _WLA = ["win", "lnx", "apk"] _WIN = ["win"] +_WINAPK = ["win", "apk"] _APKONLY = ["apk"] PLATFORMS = { @@ -199,6 +201,8 @@ PLATFORMS = { "remote_block_input": _WIN, "operate_window": _WIN, # WSLIST 能列窗口,但窗口操作仅 Windows 实现 "power_action": _WIN, # 实际走 TOKEN_MACHINE_MANAGE + # TOKEN_UNINSTALL:Windows 客户端一直有该分支;Android 新版映射为系统卸载确认框 + "uninstall_host": _WINAPK, # McpMachine 族(COMMAND_MACHINE_MANAGE 仅 Windows 实现) "list_network_connections": _WIN,