diff --git a/client/KernelManager.cpp b/client/KernelManager.cpp index ae63c41..f8fb27c 100644 --- a/client/KernelManager.cpp +++ b/client/KernelManager.cpp @@ -911,7 +911,7 @@ static void ReplyMcpWindowInfo(IOCPClient* client, uint8_t mode) // 字节最高位置 1,服务端据此报告"列表不完整",而不是把第 97 个以后的窗口当成不存在。 size_t count = windows.size() > 96 ? 96 : windows.size(); const bool truncated = windows.size() > count; - std::vector pkt(4 + count * sizeof(WINDOWINFO_MCP), 0); + std::vector pkt(4 + count * sizeof(WINDOWINFO_MCP) + sizeof(WINDOWINFO_MCP_DESKTOP), 0); pkt[0] = TOKEN_MCP_WINDOW_INFO; pkt[1] = (BYTE)(mode | (truncated ? 0x80 : 0)); pkt[2] = (BYTE)(count & 0xFF); @@ -919,6 +919,16 @@ static void ReplyMcpWindowInfo(IOCPClient* client, uint8_t mode) if (count) memcpy(pkt.data() + 4, windows.data(), count * sizeof(WINDOWINFO_MCP)); + // 尾块:虚拟桌面矩形,供服务端把窗口相对坐标换算成抓屏帧归一化坐标。 + // 老服务端只读前 count 条记录,尾部字节被忽略(非破坏性扩展)。 + WINDOWINFO_MCP_DESKTOP desk = {}; + desk.magic = WINDOWINFO_DESKTOP_MAGIC; + desk.left = ::GetSystemMetrics(SM_XVIRTUALSCREEN); + desk.top = ::GetSystemMetrics(SM_YVIRTUALSCREEN); + desk.width = ::GetSystemMetrics(SM_CXVIRTUALSCREEN); + desk.height = ::GetSystemMetrics(SM_CYVIRTUALSCREEN); + memcpy(pkt.data() + 4 + count * sizeof(WINDOWINFO_MCP), &desk, sizeof(desk)); + if (client && client->IsConnected()) client->Send2Server((char*)pkt.data(), (int)pkt.size()); } diff --git a/common/commands.h b/common/commands.h index 0c207f1..847e090 100644 --- a/common/commands.h +++ b/common/commands.h @@ -768,6 +768,21 @@ struct WINDOWINFO_MCP { static_assert(sizeof(WINDOWINFO_MCP) == 1056, "WINDOWINFO_MCP must be exactly 1056 bytes"); +// COMMAND_MCP_WINDOW_INFO 响应尾块(可选):虚拟桌面矩形(虚拟桌面坐标)。 +// 新客户端在窗口记录之后追加,服务端按包长判定是否存在;老服务端只读 count 条记录、 +// 自动忽略尾部。remote_mouse 的 window_hwnd 相对坐标靠它把窗口矩形换算成发送帧归一化坐标。 +#define WINDOWINFO_DESKTOP_MAGIC 0x56444350u // 'VDCP' +#pragma pack(push, 1) +struct WINDOWINFO_MCP_DESKTOP { + uint32_t magic; + int32_t left; + int32_t top; + int32_t width; + int32_t height; +}; +#pragma pack(pop) +static_assert(sizeof(WINDOWINFO_MCP_DESKTOP) == 20, "WINDOWINFO_MCP_DESKTOP must be exactly 20 bytes"); + // 远程交谈 enum ChatManager { COMMAND_NEXT_CHAT, diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index 26a9d01..6878092 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -685,7 +685,7 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机 | `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 | | `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 | | `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 | -| `-32012` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符。**`-32008` 是同一语义的历史别名**(早期实现用它,已发布的客户端/文档可能仍在匹配),新代码一律用 `-32012` | 按 `message` 修正参数后重试 | +| `-32012` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含控制字符(含换行),或**老非 PTY 会话**里含 `&`/`\|`,或 POSIX 会话里含裸后台 `&`;路径/参数含非法字符。**`-32008` 是同一语义的历史别名**(早期实现用它,已发布的客户端/文档可能仍在匹配),新代码一律用 `-32012` | 按 `message` 修正参数后重试 | | `-32009` | Target not found | 远端路径/注册表键不存在(win32 `2`/`3`,由新客户端主动回报);`kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `list_files`/`list_registry`(或 `host_list_network_state`)确认目标存在 | | `-32010` | Access denied | 目标存在但权限不足(win32 `5`):非提权客户端的服务枚举(`OpenSCManager`)、受保护目录(如 `System Volume Information`)、受保护注册表键(如 `HKLM\SAM`) | **不要重试**:需客户端提权(管理员运行)或换目标 | | `-32011` | Destination write failed | 文件传输的**目标端**已收到数据但写盘失败:`copy_files_c2c` / `upload_file` 的目标主机回了回执且 `status != 0`(`message` 带 status、首个 errno、实收文件数) | **不要原样重试**:按文案判断(errno 13/1→权限、2→路径不存在、28→磁盘满),先修目标端目录/权限 | @@ -726,6 +726,13 @@ POSIX 形态与 Windows 的差别: **已知边界**:屏幕渲染流里「光标下移空行」会被剥成紧邻行(例如 `ping` 的统计块会贴在最后一条回复后面),不影响语义。 +**PTY 会话允许管道与串联**(2026-11-10):哨兵独立成行后,命令行里的 `|`、`&&`、`||`(POSIX 还允许 `;`)都由 shell 正常解析,不会再吞掉哨兵,因此 `is_pty=true` 的会话不再拒绝这些字符,退出码取整条管道/串联的结果。被拒绝的只剩两类: + +- **老非 PTY 客户端**(单行 ` 2>&1 && echo 哨兵 || echo 哨兵`):`&`/`|` 仍会破坏单行哨兵语义,维持 `-32012` 并提示「拆成多条调用或升级客户端」。 +- **POSIX 会话里的裸后台 `&`**:`cmd & echo 哨兵` 会让哨兵在命令真正完成前执行,stdout 与退出码都不可信;`&&`、`&>`、`>&`/`2>&1` 不受影响(判别器 `HasPosixBackgroundAmpersand` 跳过引号与转义,只拦裸后台符;`$((...))`、`${...}` 展开里的 `&` 会被保守拒绝,误报只会让调用方改写命令)。 + +判定发生在 `BeginTermCommand` 之前:`PeekTermSession` 只读查询会话是否存在、是否 PTY,不置 `busy`、不改状态,因此不支持的语法在碰会话之前就被拒绝。 + ## 13. 增补(2026-10-26:MCP HTTPS / native TLS) ### 13.1 目标与取舍 @@ -1020,6 +1027,7 @@ GUI 自动化的失败大多不是「事件没发出去」,而是「事件进 ``` 请求 [COMMAND_MCP_WINDOW_INFO(179)][mode:1] // mode 0 = 可见顶层窗口 响应 [TOKEN_MCP_WINDOW_INFO(180)][mode:1][count:u16 LE][WINDOWINFO_MCP × count] + [WINDOWINFO_MCP_DESKTOP?] // 新客户端可选尾块,20 字节(§22.2) ``` `WINDOWINFO_MCP` 为 1056 字节 packed:`hwnd/pid/left/top/right/bottom/flags/zorder/title[1024]`, @@ -1030,6 +1038,10 @@ GUI 自动化的失败大多不是「事件没发出去」,而是「事件进 `BeginPending` / `WaitPending`,由 `2015RemoteDlg::MessageHandle` 的 `TOKEN_MCP_WINDOW_INFO` 分支调用 `TakeMainResponse`,不建子连接、不弹框。 +新客户端在 `count` 条记录后追加可选的 `WINDOWINFO_MCP_DESKTOP` 尾块(20 字节,magic +`'VDCP'`,报告虚拟桌面矩形);服务端按包长判定是否存在,老服务端只读 `count` 条记录、 +忽略尾部。布局与用途见 §22.2。 + 老客户端不认识 179,服务端按能力位提前拒绝(`-32005`),不会白等超时。 ### 20.3 新工具与参数 @@ -1135,3 +1147,64 @@ u32 hwnd mode=WINDOW 的窗口句柄 并发请求直接丢弃,表现为服务端超时。 - 原生分辨率意味着更大的 JPEG 与 base64 体积:区域越大、越多窗口细节,单次响应越贵。 只截需要的 ROI,比整屏 1920 更省也更快。 + + +## 22. 增补(2026-11-10:窗口相对坐标 —— 看屏即点) + +### 22.1 问题 + +`get_screenshot mode=window` 能拿到窗口原始像素,但 `remote_mouse` 只接受**屏幕**归一化坐标 +(0..1 相对整个虚拟桌面)。模型想点窗口截图里 (0.5, 0.4) 的按钮,得自己把像素换算回 +虚拟桌面坐标,还要处理多显示器导致的负原点;换算错一位,点击就落到别的窗口或别的屏幕上。 + +### 22.2 协议:窗口信息响应的桌面尾块 + +窗口信息响应在 `count` 条记录之后追加一个**可选**尾块(布局见 §20.2): + +``` +响应 [TOKEN_MCP_WINDOW_INFO][mode:1][count:u16 LE][WINDOWINFO_MCP × count] + [WINDOWINFO_MCP_DESKTOP?] // 20 字节,magic 'VDCP'(0x56444350) +``` + +`WINDOWINFO_MCP_DESKTOP` 为 packed 的 `magic/left/top/width/height`,取 +`SM_*VIRTUALSCREEN`,即抓屏与注入共用的虚拟桌面矩形。服务端按**包长**判定尾块是否存在: +老客户端不发尾块,服务端按旧布局解析、`window_hwnd` 返回 `-32005`;老服务端只读 +`count` 条记录,尾部字节被忽略。不新增能力位——尾块本身就是新客户端的标志。 + +### 22.3 `remote_mouse` 的 `window_hwnd` 基准 + +`remote_mouse` 新增可选 `window_hwnd`(整数或 `0x` 字符串)。给定后 `x/y`(以及 `drag` 的 +`x2/y2`)改为**相对该窗口的归一化坐标**,服务端换算成发送帧坐标: + +``` +clip_left = max(window.left, desktop.left) +clip_right = min(window.right, desktop.left + desktop.width) +physical_x = clip_left + n × (clip_right - clip_left) +frame_x = (physical_x - desktop.left) / desktop.width +``` + +(Y 方向同理;窗口完全移出虚拟桌面时交集为空,直接 `-32009`。) + +基准矩形取**窗口矩形与虚拟桌面的交集**:`get_screenshot mode=window` 的源矩形也是这个 +交集(§21.3),因此窗口截图上的比例点可直接映射为 `window_hwnd` 坐标;窗口部分移出 +虚拟桌面时,被裁掉的那部分不会让点击整体偏移。`frame_x/frame_y` 钳制到 0..1 后交给 +既有的发送帧 → 客户端 `PointConversion`(ROI 偏移、缩放、DPI、虚拟桌面原点)。 + +安全默认值: + +- **默认要求目标窗口是前台**(`require_foreground=true` 隐式生效):非前台窗口的坐标 + 点击会落到遮挡它的窗口上。显式传 `require_foreground=false` 可关闭。 +- `window_hwnd` 与 `expect_hwnd` 同时给出时必须指向同一窗口,否则 `-32602`。 +- 窗口不存在 / 不可见 / 最小化 / 矩形为空 / 完全移出虚拟桌面 → `-32009`;窗口不是前台 → `-32000`; + 客户端窗口信息响应没有桌面尾块(老客户端)→ `-32005`。 +- 返回 `structuredContent.coordinateWindow`(**未裁剪**的窗口原始快照)与 `resolved` 里的 + `frame_x/frame_y`(drag 另有 `frame_x2/frame_y2`)和 `basis`(实际坐标基准矩形,即 + 窗口 ∩ 虚拟桌面,与 `get_screenshot mode=window` 的 `capture` 源矩形一致)。 + 窗口部分移出虚拟桌面时 `coordinateWindow` 与 `basis` 不同,核对换算请以 `basis` 为准。 + +### 22.4 代价 + +- 每次带 `window_hwnd` 的调用多一次窗口信息 RPC(一次主连接往返);不带时行为与 + 字节流完全不变。 +- 窗口在前台且未被缩放时,比例点与窗口截图 1:1 对应;窗口被其他窗口部分遮挡时, + 截图本身也是遮挡内容(GDI 语义,见 §21.3),需要无遮挡内容时先 `activate`。 diff --git a/docs/Mcp_Next_Plan.md b/docs/Mcp_Next_Plan.md index 281bfe7..bd2b9db 100644 --- a/docs/Mcp_Next_Plan.md +++ b/docs/Mcp_Next_Plan.md @@ -512,6 +512,8 @@ P10-C(`3d388f8`)加工具时索性去掉数字——避免每加一个工具 | `search_file` 无深度/大小上限参数 | `McpServer.cpp:8050` | 客户端固定深度 32 / 10000 条,服务端可加 `max_depth` 但需客户端支持;暂不做(P12) | | ~~`search_file` 的描述仍写着「会栈溢出」~~ | — | **已完成**(P10-A,`bb55f52`):描述改为「超过 260 字节的路径会被静默跳过(既不记录也不继续向下递归)」,`tools/mcp_smoke.ps1` 的两处注释改为「MAX_PATH 的条目会被客户端静默跳过(8f718d9 起不再栈溢出)」 | | ~~`get_screenshot` 无区域裁剪~~ | — | **已完成**(2026-11-10):新增 `mode=region/window/monitor`,默认原生分辨率并返回 `capture` 源矩形元数据;见 `Mcp_Design.md §21` | +| ~~窗口截图坐标要手工换算成屏幕坐标~~ | — | **已完成**(2026-11-10):`remote_mouse` 新增 `window_hwnd` 基准,窗口信息响应追加虚拟桌面矩形尾块;见 `Mcp_Design.md §22` | +| ~~`terminal_exec` 不能用管道~~ | — | **已完成**(2026-11-10):PTY 会话放开 `\|` / `&&` / `\|\|`(POSIX 还允许 `;`),仅老非 PTY 客户端与 POSIX 裸后台 `&` 仍拒绝;见 `Mcp_Design.md §12.1` | | 审计不含调用参数 | `Mcp_Design.md §10.8` | 有意设计(防泄漏),维持 | | `chat_wait` 会取走 inbox | `McpInternal.cpp:431` | 已正确标注非幂等,无需改 | diff --git a/docs/Mcp_Terminal_Design.md b/docs/Mcp_Terminal_Design.md index e47d7ce..a5445dc 100644 --- a/docs/Mcp_Terminal_Design.md +++ b/docs/Mcp_Terminal_Design.md @@ -237,15 +237,20 @@ SweepIdleTerminals(300) ResolveTerminalSessionHost session_id 为空 → -32602 command 为空 → -32602 -command 含 & 或 | → -32012(正确性门,见 §4.6) +PeekTermSession(devId, sid, isPty) + → 非 0 则按 -32002/-32003 返回(不存在/不匹配/未就绪/忙碌/已关) +command 含 <0x20 控制字符 → -32012(换行会拆行,见 §4.6) +!isPty && command 含 & 或 | → -32012(老非 PTY 单行哨兵,见 §4.6) +posix && HasPosixBackgroundAmpersand(command) + → -32012(POSIX 裸后台 &,见 §4.6) nonce = 随机 8 hex BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty) - → false 则 -32002(不存在/不匹配/未就绪/忙碌/已关) -sentLine = SendTerminalCommandLine(subCtx, isPty, command, nonce) + → 非 0 则 -32002/-32003(Peek 后被并发抢占:忙碌/已关等) +sentLine = SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, ...) WaitTermCommand(devId, raw, exitCode, closed, timeoutMs) → 超时:subCtx->CancelIO() + -32001 → closed:subCtx->CancelIO()(会话已被清理,仅对称无害) -stdoutStr = CleanTerminalOutput(raw, cp, sentLine) +stdoutStr = CleanTerminalOutput(raw, cp, isPty, cmdLine, sentLine) 审计 "term-exec [sessionId]: command" 返回 { stdout, exit_code } ``` @@ -271,15 +276,29 @@ CloseTermSession(devId, sessionId) `CloseTermSession` 返回值语义:**0**=已关闭;**1**=会话不存在(幂等,仍返回 `{closed:true}`);**2**=sessionId 不匹配(报错)。 -### 4.6 正确性门 `&|`(非安全门) +### 4.6 正确性门:`&` / `|` / 控制字符(非安全门) -`terminal_exec` **拒绝含 `&` 或 `|` 的命令**(`find_first_of("&|")`,含 `&&`/`||`/`|`),报 `-32012`(历史别名 `-32008`)。原因:哨兵包装 `cmd 2>&1 && echo ... || echo ...` 假定命令是「扁平」的,命令内含 `&`/`|` 会与包装的控制操作符合流、导致退出码失真/输出归属不清。 +门按**会话形态**分档,判定发生在 `BeginTermCommand` 之前:`PeekTermSession` 只读查询 +(不置 `busy`、不改状态),不支持的语法在碰会话之前就被拒绝;Peek 与 Begin 之间被并发 +抢占时 `BeginTermCommand` 返回忙碌,无竞态。全部报 `-32012`(历史别名 `-32008`)。 + +- **控制字符(`<0x20`,含 `\r`/`\n`)一律拒绝**:换行会把命令拆成多行、只有末行被哨兵 + 包装,退出码与输出归属失真。 +- **老非 PTY 会话**(`is_pty=false`,单行哨兵 `cmd 2>&1 && echo ... || echo ...`):`&`/`|` + 会与包装的控制操作符合流,维持拒绝(`find_first_of("&|")`,含 `&&`/`||`/`|`)。 +- **PTY 会话**(`is_pty=true`:Windows ConPTY / Linux POSIX PTY):哨兵独立成行执行, + `|`、`&&`、`||`(POSIX 还允许 `;`)由 shell 正常解析,退出码取整条管道/串联的结果,放行。 +- **POSIX 会话的裸后台 `&`**:`cmd & echo 哨兵` 会让哨兵在命令真正完成前执行,stdout 与 + 退出码都不可信,拒绝。`&&`、`&>`/`&>>`、`>&`/`2>&1` 里的 `&` 放行;引号与反斜杠转义内的 + `&` 不算。判别器 `HasPosixBackgroundAmpersand` 对 `$((...))`、`${...}` 展开里的 `&` 会 + 保守拒绝(误报,改写命令即可)。 - 这是**正确性限制,不是白名单**——持久终端本就不设白名单。 -- 同样拒绝 `<0x20` 的控制字符(`\r`/`\n`):换行会把命令拆成多行、只有末行被哨兵包装,导致退出码与输出归属失真。 -- `> < ^`(重定向 / 转义)**允许**:不破坏哨兵链。AI 把链式/管道命令拆成多条 `terminal_exec` 调用即可(cwd/env 保持,等价)。 +- `> < ^`(重定向 / 转义)**允许**:不破坏哨兵链。老非 PTY 会话请把链式/管道命令拆成 + 多条 `terminal_exec` 调用(cwd/env 保持,等价)。 -对比:一次性 `exec_command` 因有白名单,其元字符门更严(`&|<>^` 五元字符全拒,§3.1)。 +对比:一次性 `exec_command` 因有白名单,其元字符门更严(`&|<>^` 五元字符全拒,§3.1), +且不因 PTY 放宽。 --- diff --git a/mcp/tools.json b/mcp/tools.json index 6ab6e5e..591724e 100644 --- a/mcp/tools.json +++ b/mcp/tools.json @@ -2230,7 +2230,7 @@ }, { "name": "terminal_exec", - "description": "在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束,但不能含 & 或 |(会破坏输出哨兵捕获),请拆成多条调用;Windows 下重定向 > < 与转义 ^ 允许,Linux 下可用 ; 串联(退出码取最后一条)。", + "description": "在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。", "gate": "terminal", "write": true, "platforms": [ @@ -2241,7 +2241,7 @@ "inputSchema": { "properties": { "command": { - "description": "要执行的命令(完整 shell,不受白名单约束;但不能含 & 或 |,请拆成多条调用)。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令", + "description": "要执行的命令(完整 shell,不受白名单约束)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令", "type": "string" }, "id": { @@ -2496,7 +2496,7 @@ }, { "name": "remote_mouse", - "description": "向已建立的远程控制会话注入鼠标事件。action 可选 move / down / up / click / right_click / middle_click / drag / scroll;坐标 x/y(及 drag 的 x2/y2)为归一化 0..1 浮点。button 可选 left/middle/right(默认 left);click 的 clicks 可选 1/2/3(默认 1);scroll 的 delta 正=向下滚、负=向上滚。可选 expect_hwnd / require_foreground / report_foreground 与 remote_keyboard 同义(新 Windows 客户端),可用它确认点击确实落在目标窗口。", + "description": "向已建立的远程控制会话注入鼠标事件。action 可选 move / down / up / click / right_click / middle_click / drag / scroll;坐标 x/y(及 drag 的 x2/y2)为归一化 0..1 浮点,默认相对整屏/整虚拟桌面。给 window_hwnd 时改为相对「该窗口与虚拟桌面的交集」(窗口完整可见时即窗口本身;0=左/上边缘,1=右/下边缘),可直接照 get_screenshot mode=window 的图量比例:服务端用该交集与虚拟桌面矩形换算成屏幕坐标,并默认要求该窗口在前台(require_foreground=false 可显式关闭;与 expect_hwnd 同时给出时须指向同一窗口)。button 可选 left/middle/right(默认 left);click 的 clicks 可选 1/2/3(默认 1);scroll 的 delta 正=向下滚、负=向上滚。可选 expect_hwnd / require_foreground / report_foreground 与 remote_keyboard 同义(新 Windows 客户端),可用它确认点击确实落在目标窗口。", "gate": "remote_control", "write": true, "platforms": [ @@ -2546,19 +2546,19 @@ "type": "string" }, "x": { - "description": "归一化 X 坐标(0=屏幕最左,1=最右)", + "description": "归一化 X 坐标(0=屏幕最左,1=最右);给了 window_hwnd 时改为相对「窗口与虚拟桌面的交集」(窗口完整可见时即窗口),0=左边缘,1=右边缘", "type": "number" }, "x2": { - "description": "拖拽终点 X(仅 drag)", + "description": "拖拽终点 X(仅 drag;坐标基准与 x 相同)", "type": "number" }, "y": { - "description": "归一化 Y 坐标(0=屏幕最上,1=最下)", + "description": "归一化 Y 坐标(0=屏幕最上,1=最下);给了 window_hwnd 时改为相对「窗口与虚拟桌面的交集」(窗口完整可见时即窗口),0=上边缘,1=下边缘", "type": "number" }, "y2": { - "description": "拖拽终点 Y(仅 drag)", + "description": "拖拽终点 Y(仅 drag;坐标基准与 y 相同)", "type": "number" }, "expect_hwnd": { @@ -2575,6 +2575,13 @@ "report_foreground": { "type": "boolean", "description": "可选:注入后回报前台窗口(structuredContent.foreground)。给了 expect_hwnd 时默认 true" + }, + "window_hwnd": { + "type": [ + "integer", + "string" + ], + "description": "可选:以该窗口为坐标基准(整数或 0x 前缀字符串)。给定后 x/y(及 drag 的 x2/y2)变为相对「窗口与虚拟桌面的交集」的归一化坐标(窗口完整可见时即窗口本身),服务端用该交集与虚拟桌面矩形换算成屏幕坐标,可直接用 get_screenshot mode=window 图上的比例点。默认要求该窗口是前台(可用 require_foreground=false 显式关闭;与 expect_hwnd 同时给出时须指向同一窗口);窗口不存在/最小化/完全移出虚拟桌面时报错。仅新 Windows 客户端支持(窗口信息 RPC 需带虚拟桌面矩形),否则 -32005。" } }, "required": [ @@ -2603,6 +2610,14 @@ "foregroundError": { "type": "string", "description": "前台回报失败的原因(注入本身已成功)" + }, + "coordinateWindow": { + "type": "object", + "description": "window_hwnd 时命中的窗口原始快照(left/top/right/bottom/width/height,未裁剪);实际归一化基准是 resolved.basis(窗口与虚拟桌面的交集)" + }, + "resolved": { + "type": "object", + "description": "window_hwnd 时换算后的发送帧归一化坐标(frame_x/frame_y,drag 另有 frame_x2/frame_y2);basis 为实际坐标基准矩形 left/top/right/bottom(窗口与虚拟桌面的交集,与 get_screenshot mode=window 的源矩形一致)" } } } diff --git a/server/2015Remote/McpInternal.cpp b/server/2015Remote/McpInternal.cpp index a34b116..13e3903 100644 --- a/server/2015Remote/McpInternal.cpp +++ b/server/2015Remote/McpInternal.cpp @@ -202,10 +202,12 @@ Json::Value WindowEntryToJson(const WindowEntry& e) { } int FetchWindowInfo(context* ctx, uint64_t devId, const char* tool, int timeoutMs, - std::vector& out, std::string& errMsg, bool* truncated) { + std::vector& out, std::string& errMsg, bool* truncated, + WindowDesktopRect* desktop) { out.clear(); errMsg.clear(); if (truncated) *truncated = false; + if (desktop) *desktop = WindowDesktopRect(); if (!ctx) { errMsg = "host context unavailable"; return 2; @@ -265,6 +267,19 @@ int FetchWindowInfo(context* ctx, uint64_t devId, const char* tool, int timeoutM e.title = title; out.push_back(std::move(e)); } + + // 可选尾块:虚拟桌面矩形(新客户端才回;老客户端包长正好到 count 条记录为止)。 + if (desktop && data.size() >= 4 + count * sizeof(WINDOWINFO_MCP) + sizeof(WINDOWINFO_MCP_DESKTOP)) { + WINDOWINFO_MCP_DESKTOP d; + memcpy(&d, data.data() + 4 + count * sizeof(WINDOWINFO_MCP), sizeof(d)); + if (d.magic == WINDOWINFO_DESKTOP_MAGIC && d.width > 0 && d.height > 0) { + desktop->left = d.left; + desktop->top = d.top; + desktop->width = d.width; + desktop->height = d.height; + desktop->valid = true; + } + } return 0; } diff --git a/server/2015Remote/McpInternal.h b/server/2015Remote/McpInternal.h index a9d9a8b..28e6548 100644 --- a/server/2015Remote/McpInternal.h +++ b/server/2015Remote/McpInternal.h @@ -99,13 +99,24 @@ struct WindowEntry { // minimized/maximized/isForeground/zOrder)。机器管理与远程控制共用同一字段口径。 Json::Value WindowEntryToJson(const WindowEntry& e); +// 窗口信息响应尾块里的虚拟桌面矩形(WINDOWINFO_MCP_DESKTOP 的解码结果)。 +// valid=false 表示客户端是老版本、没带这个尾块。 +struct WindowDesktopRect { + int32_t left = 0; + int32_t top = 0; + int32_t width = 0; + int32_t height = 0; + bool valid = false; +}; + // 下发 COMMAND_MCP_WINDOW_INFO(主连接 RPC,不建子连接、不弹框),解析 TOKEN_MCP_WINDOW_INFO。 // timeoutMs <= 0 时取 McpServer().ToolTimeoutMs()。out 按客户端的 z 序返回。 +// desktop(可选):新客户端的虚拟桌面矩形;老客户端保持 valid=false。 // 返回:0=ok;1=设备忙;2=发送失败/超时;3=响应畸形;4=客户端未声明 CLIENT_CAP_WINDOW_INFO。 // truncated(可选):true 表示客户端还有更多可见窗口没装进这个包(单包上限 96 条)。 int FetchWindowInfo(context* ctx, uint64_t devId, const char* tool, int timeoutMs, std::vector& out, std::string& errMsg, - bool* truncated = nullptr); + bool* truncated = nullptr, WindowDesktopRect* desktop = nullptr); // 客户端是否为 Windows 形态(EXE/DLL/MEXE/SC/MDLL);LNX / MAC / APK 返回 false。 // 用于「只有 Windows 客户端实现了这个能力」的判断(注册表、窗口、服务等)。 diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 367a483..e5c9ef0 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -2491,7 +2491,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "terminal_exec"; - tool["description"] = u8"在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束,但不能含 & 或 |(会破坏输出哨兵捕获),请拆成多条调用;Windows 下重定向 > < 与转义 ^ 允许,Linux 下可用 ; 串联(退出码取最后一条)。"; + tool["description"] = u8"在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。"; tool["inputSchema"] = BuildTerminalExecInputSchema(); tool["outputSchema"] = BuildTerminalExecOutputSchema(); tools.append(tool); @@ -2537,7 +2537,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "remote_mouse"; - tool["description"] = u8"向已建立的远程控制会话注入鼠标事件。action 可选 move / down / up / click / right_click / middle_click / drag / scroll;坐标 x/y(及 drag 的 x2/y2)为归一化 0..1 浮点。button 可选 left/middle/right(默认 left);click 的 clicks 可选 1/2/3(默认 1);scroll 的 delta 正=向下滚、负=向上滚。可选 expect_hwnd / require_foreground / report_foreground 与 remote_keyboard 同义(新 Windows 客户端),可用它确认点击确实落在目标窗口。"; + tool["description"] = u8"向已建立的远程控制会话注入鼠标事件。action 可选 move / down / up / click / right_click / middle_click / drag / scroll;坐标 x/y(及 drag 的 x2/y2)为归一化 0..1 浮点,默认相对整屏/整虚拟桌面。给 window_hwnd 时改为相对「该窗口与虚拟桌面的交集」(窗口完整可见时即窗口本身;0=左/上边缘,1=右/下边缘),可直接照 get_screenshot mode=window 的图量比例:服务端用该交集与虚拟桌面矩形换算成屏幕坐标,并默认要求该窗口在前台(require_foreground=false 可显式关闭;与 expect_hwnd 同时给出时须指向同一窗口)。button 可选 left/middle/right(默认 left);click 的 clicks 可选 1/2/3(默认 1);scroll 的 delta 正=向下滚、负=向上滚。可选 expect_hwnd / require_foreground / report_foreground 与 remote_keyboard 同义(新 Windows 客户端),可用它确认点击确实落在目标窗口。"; tool["inputSchema"] = BuildRemoteMouseInputSchema(); tool["outputSchema"] = BuildRemoteMouseOutputSchema(); tools.append(tool); @@ -3998,6 +3998,27 @@ static bool ContainsControlChar(const std::string& s) { return false; } +// POSIX 命令里是否有「后台执行」用的 &:哨兵在下一行立即执行,后台命令的输出与退出码 +// 都不可信。&&(串联)、&> / &>>(重定向)以及 2>&1 里的 & 都放行;引号与反斜杠转义内 +// 的 & 不算。仅 PTY 会话会用到(老非 PTY 仍整体拒绝 & 与 |)。 +static bool HasPosixBackgroundAmpersand(const std::string& s) { + bool inSingle = false, inDouble = false, esc = false; + for (size_t i = 0; i < s.size(); ++i) { + const char c = s[i]; + if (esc) { esc = false; continue; } + if (c == '\\' && !inSingle) { esc = true; continue; } + if (inSingle) { if (c == '\'') inSingle = false; continue; } + if (inDouble) { if (c == '"') inDouble = false; continue; } + if (c == '\'') { inSingle = true; continue; } + if (c == '"') { inDouble = true; continue; } + if (c != '&') continue; + if (i + 1 < s.size() && (s[i + 1] == '&' || s[i + 1] == '>')) { ++i; continue; } + if (i > 0 && s[i - 1] == '>') continue; // 2>&1 / >&2 + return true; + } + return false; +} + // tools/call:exec_command(Windows/Linux 一次性远程命令:主连接 COMMAND_SHELL → 子连接终端 → // 哨兵命令行 → 收集 stdout + exit_code → 关子链接)。安全门:只读默认 + 白名单 + 审计。 std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { @@ -4705,7 +4726,7 @@ Json::Value BuildTerminalExecInputSchema() { props["session_id"] = sid; Json::Value cmdProp(Json::objectValue); cmdProp["type"] = "string"; - cmdProp["description"] = u8"要执行的命令(完整 shell,不受白名单约束;但不能含 & 或 |,请拆成多条调用)。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令"; + cmdProp["description"] = u8"要执行的命令(完整 shell,不受白名单约束)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令"; props["command"] = cmdProp; Json::Value timeoutProp(Json::objectValue); timeoutProp["type"] = "integer"; @@ -4832,7 +4853,7 @@ std::string BuildTerminalOpen(const Json::Value& id, const Json::Value& args, CM return BuildResult(id, result); } -// tools/call:terminal_exec(在已打开的持久会话中执行一条命令;无白名单,但禁 & |) +// tools/call:terminal_exec(在已打开的持久会话中执行一条命令;无白名单;PTY 下允许管道/串联) std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleTerminals(kTermIdleTimeoutSec); @@ -4852,11 +4873,42 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM if (command.empty()) return BuildError(id, -32602, "Missing required parameter: command"); - // 正确性门(非安全门):& 与 | 会破坏哨兵控制操作符链、导致退出码失真;拆成多条调用即可。 - // \r\n 会把命令拆成多行、只有末行被哨兵包装,同样破坏退出码捕获,一并拒绝。 - if (command.find_first_of("&|") != std::string::npos || ContainsControlChar(command)) + auto sessionError = [&](int code) -> std::string { + // 区分「会话被超时/退出/关闭销毁」与「session_id 写错」「另一条命令在飞」(评审 P1)。 + std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId); + if (!destroyed.empty()) + return BuildError(id, -32002, destroyed); + if (code == 4) + return BuildError(id, -32003, "Device busy: another terminal_exec is already running for this session"); + if (code == 2) + return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId); + if (code == 3) + return BuildError(id, -32002, "Terminal session is not ready yet: " + sessionId); + if (code == 5) + return BuildError(id, -32002, "Terminal session is already closing: " + sessionId); + return BuildError(id, -32002, "Terminal session not found: " + sessionId + " (call terminal_open first)"); + }; + + // 先只读查会话形态:PTY 会话才允许管道/串联;失败时状态不变。 + bool isPty = false; + int peek = mcp.PeekTermSession(devId, sessionId, isPty); + if (peek != 0) + return sessionError(peek); + + // 正确性门(非安全门):换行会拆成多行、只有末行被哨兵包装,一律拒绝。 + // 管道 | 与 && 串联在 PTY 会话(ConPTY / POSIX PTY)下是安全的:哨兵独立成行执行, + // 拿到的是整条管道/串联的退出码。老非 PTY 客户端仍是单行哨兵,继续拒绝 & 与 |。 + if (ContainsControlChar(command)) return BuildError(id, kErrValidation, - "Command contains & or | or a newline (breaks output capture); run chained/piped commands as separate terminal_exec calls"); + "Command contains a control character (newline/tab); send one line per call"); + if (!isPty && command.find_first_of("&|") != std::string::npos) + return BuildError(id, kErrValidation, + "Pipes and & require a PTY session (newer client); this session uses the legacy " + "non-PTY shell. Run the commands as separate terminal_exec calls"); + if (posix && HasPosixBackgroundAmpersand(command)) + return BuildError(id, kErrValidation, + "Background execution (&) breaks output capture; use && to chain commands " + "or run it in a separate session"); int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); int v = 0; @@ -4865,23 +4917,9 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM std::string nonce = GenerateRandomToken().substr(0, 8); context* subCtx = nullptr; - bool isPty = false; int begin = mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty); - if (begin != 0) { - // 区分「会话被超时/退出/关闭销毁」与「session_id 写错」「另一条命令在飞」(评审 P1)。 - std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId); - if (!destroyed.empty()) - return BuildError(id, -32002, destroyed); - if (begin == 4) - return BuildError(id, -32003, "Device busy: another terminal_exec is already running for this session"); - if (begin == 2) - return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId); - if (begin == 3) - return BuildError(id, -32002, "Terminal session is not ready yet: " + sessionId); - if (begin == 5) - return BuildError(id, -32002, "Terminal session is already closing: " + sessionId); - return BuildError(id, -32002, "Terminal session not found: " + sessionId + " (call terminal_open first)"); - } + if (begin != 0) + return sessionError(begin); std::string cmdLine, sentLine; SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, cmdLine, sentLine); @@ -5543,6 +5581,8 @@ struct WindowLookup { bool found = false; bool foreground = false; bool truncated = false; // 客户端可见窗口多于单包上限,列表不完整 + WindowDesktopRect desktop; // 新客户端才有的虚拟桌面矩形(window_hwnd 相对坐标用) + WindowEntry entry; // 命中的窗口记录(未命中时字段无意义) Json::Value json; // 目标窗口快照;未找到时为 null }; @@ -5550,12 +5590,13 @@ struct WindowLookup { static WindowLookup LookupWindow(context* ctx, uint64_t devId, const char* tool, uint32_t hwnd) { WindowLookup w; std::vector wins; - w.rc = FetchWindowInfo(ctx, devId, tool, 0, wins, w.err, &w.truncated); + w.rc = FetchWindowInfo(ctx, devId, tool, 0, wins, w.err, &w.truncated, &w.desktop); if (w.rc != 0) { w.truncated = false; return w; } for (const WindowEntry& e : wins) { if (e.hwnd == hwnd) { w.found = true; w.foreground = (e.flags & WINDOWINFO_FOREGROUND) != 0; + w.entry = e; w.json = WindowEntryToJson(e); break; } @@ -5817,22 +5858,22 @@ Json::Value BuildRemoteMouseInputSchema() { Json::Value xProp(Json::objectValue); xProp["type"] = "number"; - xProp["description"] = u8"归一化 X 坐标(0=屏幕最左,1=最右)"; + xProp["description"] = u8"归一化 X 坐标(0=屏幕最左,1=最右);给了 window_hwnd 时改为相对「窗口与虚拟桌面的交集」(窗口完整可见时即窗口),0=左边缘,1=右边缘"; props["x"] = xProp; Json::Value yProp(Json::objectValue); yProp["type"] = "number"; - yProp["description"] = u8"归一化 Y 坐标(0=屏幕最上,1=最下)"; + yProp["description"] = u8"归一化 Y 坐标(0=屏幕最上,1=最下);给了 window_hwnd 时改为相对「窗口与虚拟桌面的交集」(窗口完整可见时即窗口),0=上边缘,1=下边缘"; props["y"] = yProp; Json::Value x2Prop(Json::objectValue); x2Prop["type"] = "number"; - x2Prop["description"] = u8"拖拽终点 X(仅 drag)"; + x2Prop["description"] = u8"拖拽终点 X(仅 drag;坐标基准与 x 相同)"; props["x2"] = x2Prop; Json::Value y2Prop(Json::objectValue); y2Prop["type"] = "number"; - y2Prop["description"] = u8"拖拽终点 Y(仅 drag)"; + y2Prop["description"] = u8"拖拽终点 Y(仅 drag;坐标基准与 y 相同)"; props["y2"] = y2Prop; Json::Value btn(Json::objectValue); @@ -5872,6 +5913,19 @@ Json::Value BuildRemoteMouseInputSchema() { reportFg["description"] = u8"可选:注入后回报前台窗口(structuredContent.foreground)。给了 expect_hwnd 时默认 true"; props["report_foreground"] = reportFg; + Json::Value winHwnd(Json::objectValue); + Json::Value winHwndTypes(Json::arrayValue); + winHwndTypes.append("integer"); + winHwndTypes.append("string"); + winHwnd["type"] = winHwndTypes; + winHwnd["description"] = u8"可选:以该窗口为坐标基准(整数或 0x 前缀字符串)。给定后 x/y(及 drag 的 x2/y2)" + u8"变为相对「窗口与虚拟桌面的交集」的归一化坐标(窗口完整可见时即窗口本身)," + u8"服务端用该交集与虚拟桌面矩形换算成屏幕坐标,可直接用 get_screenshot mode=window 图上的比例点。" + u8"默认要求该窗口是前台(可用 require_foreground=false 显式关闭;与 expect_hwnd 同时给出时" + u8"须指向同一窗口);窗口不存在/最小化/完全移出虚拟桌面时报错。" + u8"仅新 Windows 客户端支持(窗口信息 RPC 需带虚拟桌面矩形),否则 -32005。"; + props["window_hwnd"] = winHwnd; + Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; @@ -5907,6 +5961,16 @@ Json::Value BuildRemoteMouseOutputSchema() { fgErr["description"] = u8"前台回报失败的原因(注入本身已成功)"; props["foregroundError"] = fgErr; + Json::Value coordWin(Json::objectValue); + coordWin["type"] = "object"; + coordWin["description"] = u8"window_hwnd 时命中的窗口原始快照(left/top/right/bottom/width/height,未裁剪);实际归一化基准是 resolved.basis(窗口与虚拟桌面的交集)"; + props["coordinateWindow"] = coordWin; + + Json::Value resolved(Json::objectValue); + resolved["type"] = "object"; + resolved["description"] = u8"window_hwnd 时换算后的发送帧归一化坐标(frame_x/frame_y,drag 另有 frame_x2/frame_y2);basis 为实际坐标基准矩形 left/top/right/bottom(窗口与虚拟桌面的交集,与 get_screenshot mode=window 的源矩形一致)"; + props["resolved"] = resolved; + Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; @@ -5967,26 +6031,38 @@ std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy if (!GetNormCoord(args, "y2", ny2, coordErr)) return BuildError(id, -32602, coordErr); } - // ---- expect_hwnd / require_foreground:注入前核对目标窗口(可选,走窗口信息 RPC)---- + // ---- expect_hwnd / window_hwnd / require_foreground:注入前核对目标窗口(可选,走窗口信息 RPC)---- uint32_t expectHwnd = 0; bool hasExpect = false, requireForeground = false, reportForeground = false; + uint32_t windowHwnd = 0; + bool hasWindowFrame = false; { std::string oerr; if (!GetOptionalWindowArg(args, "expect_hwnd", expectHwnd, hasExpect, oerr)) return BuildError(id, -32602, oerr); + if (!GetOptionalWindowArg(args, "window_hwnd", windowHwnd, hasWindowFrame, oerr)) + return BuildError(id, -32602, oerr); if (!GetOptionalBoolArg(args, "require_foreground", requireForeground, oerr)) return BuildError(id, -32602, oerr); if (!GetOptionalBoolArg(args, "report_foreground", reportForeground, oerr)) return BuildError(id, -32602, oerr); - if (requireForeground && !hasExpect) - return BuildError(id, -32602, "require_foreground requires expect_hwnd"); - if ((hasExpect || reportForeground) && !ctx->SupportsWindowInfo()) + if (hasWindowFrame && hasExpect && windowHwnd != expectHwnd) + return BuildError(id, -32602, "window_hwnd and expect_hwnd must refer to the same window"); + // window_hwnd 的点击只有落在该窗口上才有意义(否则会点到它上面的窗口): + // 调用方未显式关闭时默认要求前台。 + if (hasWindowFrame && (!args.isMember("require_foreground") || args["require_foreground"].isNull())) + requireForeground = true; + if (requireForeground && !hasExpect && !hasWindowFrame) + return BuildError(id, -32602, "require_foreground requires expect_hwnd or window_hwnd"); + if ((hasExpect || hasWindowFrame || reportForeground) && !ctx->SupportsWindowInfo()) return BuildError(id, -32005, - "expect_hwnd/report_foreground require window info capability, " + "expect_hwnd/window_hwnd/report_foreground require window info capability, " "which this host does not support (newer Windows clients only)"); if (!args.isMember("report_foreground") || args["report_foreground"].isNull()) reportForeground = hasExpect; } + const bool needWindowLookup = hasExpect || hasWindowFrame; + const uint32_t targetHwnd = hasWindowFrame ? windowHwnd : expectHwnd; WindowLookup expectWin; // 校验 session_id/busy 并置 busy,同时取抓屏帧尺寸(screenW/H>0 由会话就绪保证)。 @@ -5998,15 +6074,42 @@ std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy // 窗口核对放在会话校验之后:session_id 无效时应当先报会话错误,不白跑一次 RPC; // busy 已置上,窗口不满足时必须先释放再返回。 - if (hasExpect) { - expectWin = LookupWindow(ctx, devId, "remote_mouse", expectHwnd); + // 窗口与虚拟桌面的交集:get_screenshot mode=window 的源矩形也是这个交集, + // window_hwnd 比例点按同一交集换算,截图被裁掉的部分不会让点击整体偏移。 + int clipL = 0, clipT = 0, clipR = 0, clipB = 0; + bool clipEmpty = false; + if (needWindowLookup) { + expectWin = LookupWindow(ctx, devId, "remote_mouse", targetHwnd); + if (expectWin.rc == 0 && expectWin.found && hasWindowFrame && expectWin.desktop.valid) { + const WindowEntry& we = expectWin.entry; + const WindowDesktopRect& de = expectWin.desktop; + clipL = we.left > de.left ? we.left : de.left; + clipT = we.top > de.top ? we.top : de.top; + clipR = we.right < de.left + de.width ? we.right : de.left + de.width; + clipB = we.bottom < de.top + de.height ? we.bottom : de.top + de.height; + clipEmpty = (clipR <= clipL || clipB <= clipT); + } std::string winErr; if (expectWin.rc != 0) winErr = WindowRpcErrorJson(id, devId, expectWin.rc, expectWin.err); else if (!expectWin.found) - winErr = WindowNotFoundErrorJson(id, expectHwnd, expectWin.truncated); + winErr = WindowNotFoundErrorJson(id, targetHwnd, expectWin.truncated); + else if (hasWindowFrame && (expectWin.entry.flags & WINDOWINFO_MINIMIZED)) + winErr = BuildError(id, -32009, "Window hwnd=" + std::to_string(targetHwnd) + + " is minimized; restore it before using window-relative coordinates"); + else if (hasWindowFrame && (expectWin.entry.right <= expectWin.entry.left || + expectWin.entry.bottom <= expectWin.entry.top)) + winErr = BuildError(id, -32009, "Window hwnd=" + std::to_string(targetHwnd) + + " has an empty rect; window-relative coordinates are not usable"); + else if (hasWindowFrame && !expectWin.desktop.valid) + winErr = BuildError(id, -32005, + "window_hwnd requires a newer Windows client: its window info response " + "does not carry the virtual desktop rect"); + else if (hasWindowFrame && clipEmpty) + winErr = BuildError(id, -32009, "Window hwnd=" + std::to_string(targetHwnd) + + " lies outside the virtual desktop; window-relative coordinates are not usable"); else if (requireForeground && !expectWin.foreground) - winErr = BuildError(id, -32000, "Window hwnd=" + std::to_string(expectHwnd) + + winErr = BuildError(id, -32000, "Window hwnd=" + std::to_string(targetHwnd) + " is not the foreground window; activate it first " "(host_control_window / operate_window action=activate)"); if (!winErr.empty()) { @@ -6015,10 +6118,30 @@ std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy } } + // 坐标基准:默认整屏/整虚拟桌面;给了 window_hwnd 时是窗口内归一化坐标,先换算成 + // 虚拟桌面物理点,再按虚拟桌面矩形归一化到抓屏帧。基准矩形取「窗口矩形 ∩ 虚拟桌面」, + // 与 get_screenshot mode=window 的源矩形完全一致,截图上的比例点可直接对应。 + double fx = nx, fy = ny, fx2 = nx2, fy2 = ny2; + if (hasWindowFrame) { + const WindowDesktopRect& d = expectWin.desktop; + auto toFrameNorm = [](double n, int lo, int hi, int dlo, int dlen) -> double { + if (hi <= lo || dlen <= 0) return 0.0; + double p = (double)lo + n * (double)(hi - lo); + double f = (p - (double)dlo) / (double)dlen; + return f < 0.0 ? 0.0 : (f > 1.0 ? 1.0 : f); + }; + fx = toFrameNorm(nx, clipL, clipR, d.left, d.width); + fy = toFrameNorm(ny, clipT, clipB, d.top, d.height); + if (action == "drag") { + fx2 = toFrameNorm(nx2, clipL, clipR, d.left, d.width); + fy2 = toFrameNorm(ny2, clipT, clipB, d.top, d.height); + } + } + // 归一化坐标 → 发送帧像素(round + clamp 到 [0, screen-1];客户端 PointConversion 再换算为物理坐标) auto toPxX = [&](double n) -> int { int p = (int)(n * screenW + 0.5); return p < 0 ? 0 : (p > screenW - 1 ? screenW - 1 : p); }; auto toPxY = [&](double n) -> int { int p = (int)(n * screenH + 0.5); return p < 0 ? 0 : (p > screenH - 1 ? screenH - 1 : p); }; - int px = toPxX(nx), py = toPxY(ny); + int px = toPxX(fx), py = toPxY(fy); int px2 = 0, py2 = 0; UINT downMsg, upMsg; uint64_t downWParam; @@ -6041,7 +6164,7 @@ std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy batch.push_back(BuildMouseMsg64(px, py, uMsg, 0)); } } else if (action == "drag") { - px2 = toPxX(nx2); py2 = toPxY(ny2); + px2 = toPxX(fx2); py2 = toPxY(fy2); batch.push_back(BuildMouseMsg64(px, py, downMsg, downWParam)); batch.push_back(BuildMouseMsg64(px2, py2, WM_MOUSEMOVE, 0)); batch.push_back(BuildMouseMsg64(px2, py2, upMsg, 0)); @@ -6069,6 +6192,10 @@ std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy char cbuf[96]; sprintf(cbuf, " norm=(%.3f,%.3f) px=(%d,%d)", nx, ny, px, py); audit += cbuf; + if (hasWindowFrame) { + sprintf(cbuf, " window=%u frame=(%.4f,%.4f)", windowHwnd, fx, fy); + audit += cbuf; + } if (action == "drag") { sprintf(cbuf, " -> norm2=(%.3f,%.3f) px2=(%d,%d)", nx2, ny2, px2, py2); audit += cbuf; @@ -6085,6 +6212,25 @@ std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); if (hasExpect) structuredContent["expectedWindow"] = expectWin.json; + if (hasWindowFrame) { + structuredContent["coordinateWindow"] = expectWin.json; + Json::Value resolved(Json::objectValue); + resolved["frame_x"] = fx; + resolved["frame_y"] = fy; + if (action == "drag") { + resolved["frame_x2"] = fx2; + resolved["frame_y2"] = fy2; + } + // 实际坐标基准(窗口 ∩ 虚拟桌面);coordinateWindow 是未裁剪的窗口矩形, + // 窗口部分移出虚拟桌面时两者不同,调用方核对换算用它。 + Json::Value basis(Json::objectValue); + basis["left"] = clipL; + basis["top"] = clipT; + basis["right"] = clipR; + basis["bottom"] = clipB; + resolved["basis"] = basis; + structuredContent["resolved"] = resolved; + } if (reportForeground) AppendForegroundReport(structuredContent, ctx, devId, "remote_mouse"); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); @@ -10189,6 +10335,19 @@ int CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& sessionI return 0; } +int CMcpServer::PeekTermSession(uint64_t device_id, const std::string& sessionId, bool& isPty) { + std::lock_guard lk(m_TermMutex); + auto it = m_TermSessions.find(device_id); + if (it == m_TermSessions.end()) return 1; + TermSession& s = it->second; + if (!s.persistent || s.sessionId != sessionId) return 2; + if (!s.started) return 3; + if (s.busy) return 4; + if (s.closed) return 5; + isPty = s.isPty; + return 0; +} + bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector& out, int& exitCode, bool& closed, int timeoutMs) { std::unique_lock lk(m_TermMutex); diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index 4c025a7..721f8d9 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -260,6 +260,10 @@ public: const std::string& command, const std::string& nonce, context*& subCtx, bool& isPty); + // 只读查询持久会话状态与 PTY 形态(不置 busy、不改会话)。 + // 返回码与 BeginTermCommand 相同,供调用方在执行前判断命令语法是否被支持。 + int PeekTermSession(uint64_t device_id, const std::string& sessionId, bool& isPty); + // 若该设备上的持久终端最近被销毁(超时/退出/关闭),返回可读原因(英文,含时间); // 否则返回空串。sessionId 不匹配时也返回空串(那是「id 写错」而不是「已销毁」)。 std::string DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId);