Feature: Add window-relative remote_mouse coords and PTY pipes in terminal_exec

New Windows clients append an optional 20-byte WINDOWINFO_MCP_DESKTOP block
(virtual desktop rect, magic 'VDCP') after the window list, so the server can
map window-relative coordinates into the capture frame. remote_mouse accepts
an optional window_hwnd; x/y and drag x2/y2 are then normalized against the
intersection of the window and the virtual desktop, which is exactly the
source rect of get_screenshot mode=window. The target window must be foreground
by default, and window_hwnd/expect_hwnd must agree when both are given.
structuredContent gains coordinateWindow and resolved (frame coords plus the
basis rect), so callers can verify the mapping.

terminal_exec now allows pipes, && and || in PTY sessions (ConPTY on Windows,
POSIX PTY on Linux) because the sentinel runs on its own line; legacy non-PTY
sessions still reject & and |. A read-only PeekTermSession lets the server
reject unsupported syntax before BeginTermCommand. POSIX still rejects bare
background & (&&, &>, 2>&1 stay allowed).

Docs: Mcp_Design.md sections 12.1/20.2/22 and Mcp_Terminal_Design.md 4.4/4.6
are synchronized with the protocol, the new validation order, and the basis
rect semantics.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-10 18:03:25 +01:00
1 parent 235a8a622c
commit 5501889d33
10 files changed
+383 -60

No files matched your search

+16 -1
View File
@@ -202,10 +202,12 @@ Json::Value WindowEntryToJson(const WindowEntry& e) {
}
int FetchWindowInfo(context* ctx, uint64_t devId, const char* tool, int timeoutMs,
std::vector<WindowEntry>& out, std::string& errMsg, bool* truncated) {
std::vector<WindowEntry>& 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;
}
+12 -1
View File
@@ -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<WindowEntry>& out, std::string& errMsg,
bool* truncated = nullptr);
bool* truncated = nullptr, WindowDesktopRect* desktop = nullptr);
// 客户端是否为 Windows 形态(EXE/DLL/MEXE/SC/MDLL);LNX / MAC / APK 返回 false。
// 用于「只有 Windows 客户端实现了这个能力」的判断(注册表、窗口、服务等)。
+199 -40
View File
@@ -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<WindowEntry> 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<std::mutex> 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<BYTE>& out,
int& exitCode, bool& closed, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_TermMutex);
+4
View File
@@ -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);