Feature: Add window info RPC for foreground checks and window activation

Add a capability-gated main-connection RPC (COMMAND_MCP_WINDOW_INFO=179 /
TOKEN_MCP_WINDOW_INFO=180) that returns visible top-level windows with UTF-8
titles, screen rectangles, foreground flag and z-order, so MCP can verify
focus before injecting input. New tool get_foreground_window; host_list_windows
switches to the richer fields; host_control_window and operate_window gain
action=activate; remote_keyboard and remote_mouse gain expect_hwnd,
require_foreground and report_foreground. Old clients keep the previous
behavior: the RPC is refused up front via CLIENT_CAP_WINDOW_INFO.

The client caps a response at 96 windows (about 101 KB, under MAX_SEND_BUFFER).
Signal the cut-off in the mode byte (0x80) instead of silently dropping windows:
host_list_windows now reports truncated=true and says the list is incomplete,
and activate verification reports state=unknown with reason=list_truncated
rather than claiming the window is gone. expect_hwnd is checked only after the
session is validated, so an invalid session_id no longer burns a window RPC and
no longer reports a window error for a session that does not exist. Nullable
output fields (foreground, window) are declared as ["object","null"] so strict
clients do not reject responses.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-10 15:09:24 +01:00
1 parent c7e23f750d
commit b2c0d81396
18 files changed
+1298 -68

No files matched your search

+539 -12
View File
@@ -320,6 +320,7 @@ const char* kServerInstructions =
u8"进程排查:host_list_processes 或 list_processes 定位,kill_process 结束。这类动作没有真实回执,"
u8"拿到 ok 后应再列一次复核,不要凭 ok 断言已生效。\n"
u8"GUI 自动化:remote_open 取得 session_id 与分辨率(screen_w/screen_h)→ get_screenshot 看画面 → "
u8"get_foreground_window 确认前台窗口(或用 remote_mouse / remote_keyboard 的 expect_hwnd 做前置校验)→ "
u8"remote_mouse / remote_keyboard 用归一化坐标(0..1)操作 → 必须 remote_close 释放会话,闲置会话会被回收。"
u8"要防止真人操作打断自动化时用 remote_block_input 锁定对端键鼠(必须带 max_block_ms,到期自动解除;"
u8"客户端无管理员权限时 Windows 会让 BlockInput 静默失败,成功只代表命令已送达)。\n"
@@ -331,13 +332,14 @@ const char* kServerInstructions =
u8"支持面从宽到窄依次是 win > lnx > mac ≈ apk:Windows 是唯一全量支持的平台,Linux 次之,"
u8"macOS 与 Android 只覆盖一部分。拿不准时按这个顺序假设。\n"
u8"win(EXE / DLL / MEXE / SC / MDLL):全部工具可用。\n"
u8"lnx(LNX):不支持服务、注册表、键日志、活动历史、文件搜索/删除/移动/建目录、"
u8"窗口列表(list_windows)、网络连接列表与断开"
u8"lnx(LNX):不支持服务、注册表、键日志、文件搜索/删除/移动/建目录、"
u8"窗口列表(list_windows)与窗口信息(get_foreground_window)、网络连接列表与断开"
u8"(list_network_connections / kill_network_connection)、"
u8"块输入、host_* 全族、chat_* 全族、operate_window、power_action。远程控制与截屏要求目标机"
u8"有 X11/Xorg(或 XWayland)桌面,纯 Wayland 或无桌面的服务器不行。\n"
u8"mac(MAC):在 lnx 的基础上,还不支持远程控制全族(remote_open / remote_close / "
u8"remote_mouse / remote_keyboard / remote_clipboard)、get_screenshot、"
u8"活动历史(get_activity_history)、"
u8"exec_command、terminal_open / terminal_exec / terminal_close"
u8"(客户端有 PTY 实现,但服务端本轮未开放)、kill_process;"
u8"文件传输、进程列表、日志可用。\n"
@@ -1034,6 +1036,9 @@ Json::Value BuildHostDetailOutputSchema() {
capProps["fileTransferV2"] = boolProp(u8"是否支持 V2 文件传输(download_file / upload_file 的前提)");
capProps["c2cPaths"] = boolProp(u8"能否按路径清单接收另一台主机的文件(copy_files_c2c 源端的前提)");
capProps["registry"] = boolProp(u8"是否有 Windows 注册表可查(list_registry);仅 Windows 客户端为 true");
capProps["windowInfo"] = boolProp(
u8"是否支持窗口信息(get_foreground_window、host_list_windows 的坐标/前后台字段、"
u8"operate_window/host_control_window 的 activate);仅声明 CLIENT_CAP_WINDOW_INFO 的新客户端为 true");
Json::Value caps(Json::objectValue);
caps["type"] = "object";
caps["properties"] = capProps;
@@ -1362,7 +1367,7 @@ Json::Value BuildOperateWindowInputSchema() {
Json::Value actionProp(Json::objectValue);
actionProp["type"] = "string";
actionProp["description"] = u8"操作:close(关闭) | show(显示) | hide(隐藏) | minimize(最小化) | maximize(最大化) | restore(还原)";
actionProp["description"] = u8"操作:close(关闭) | show(显示) | hide(隐藏) | minimize(最小化) | maximize(最大化) | restore(还原) | activate(激活到前台,需新客户端)";
props["action"] = actionProp;
Json::Value dryRunProp(Json::objectValue);
@@ -1377,7 +1382,7 @@ Json::Value BuildOperateWindowOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value ok(Json::objectValue);
ok["type"] = "boolean";
ok["description"] = u8"命令已下发(不代表窗口已按预期变化)";
ok["description"] = u8"命令已下发(不代表窗口已按预期变化);action=activate 时为前台复核结果";
props["ok"] = ok;
Json::Value dryProp(Json::objectValue);
@@ -1390,10 +1395,30 @@ Json::Value BuildOperateWindowOutputSchema() {
props["action"] = actionProp;
Json::Value windowProp(Json::objectValue);
windowProp["type"] = "object";
windowProp["description"] = u8"dry_run 时的目标窗口(hwnd/title/status/pid)";
// action=activate 复核时若没找到目标窗口,window 为 null(字段存在但值为空)。
Json::Value windowTypes(Json::arrayValue);
windowTypes.append("object");
windowTypes.append("null");
windowProp["type"] = windowTypes;
windowProp["description"] = u8"dry_run 时的目标窗口;action=activate 时为复核到的窗口快照(hwnd/title/pid/rect/flags 等),复核未找到为 null";
props["window"] = windowProp;
Json::Value stateProp(Json::objectValue);
stateProp["type"] = "string";
stateProp["description"] = u8"action=activate 时的复核状态:foreground / background / missing / unknown";
props["state"] = stateProp;
Json::Value verifyErrProp(Json::objectValue);
verifyErrProp["type"] = "string";
verifyErrProp["description"] = u8"action=activate 且前台复核请求失败时的错误说明";
props["verifyError"] = verifyErrProp;
Json::Value truncProp(Json::objectValue);
truncProp["type"] = "boolean";
truncProp["description"] = u8"为 true 时表示复核用的可见窗口列表被 96 条单次上限截断,"
u8"未找到目标不代表窗口不存在(此时 state=unknown)";
props["truncated"] = truncProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
@@ -1751,6 +1776,56 @@ Json::Value BuildScreenshotOutputSchema() {
return schema;
}
// 窗口对象 schema(get_foreground_window 的 window 字段,与 WindowEntryToJson 同口径)
Json::Value BuildWindowObjectSchema() {
Json::Value obj(Json::objectValue);
obj["type"] = "object";
Json::Value p(Json::objectValue);
const char* ints[] = { "hwnd", "pid", "left", "top", "right", "bottom",
"width", "height", "zOrder" };
for (const char* f : ints) {
Json::Value s(Json::objectValue);
s["type"] = "integer";
p[f] = s;
}
Json::Value title(Json::objectValue);
title["type"] = "string";
p["title"] = title;
const char* bools[] = { "visible", "minimized", "maximized", "isForeground" };
for (const char* f : bools) {
Json::Value s(Json::objectValue);
s["type"] = "boolean";
p[f] = s;
}
obj["properties"] = p;
return obj;
}
// get_foreground_window 的 outputSchema(window 为 null 表示当前没有可枚举的前台窗口)
Json::Value BuildGetForegroundWindowOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value winProp = BuildWindowObjectSchema();
Json::Value winTypes(Json::arrayValue);
winTypes.append("object");
winTypes.append("null");
winProp["type"] = winTypes;
props["window"] = winProp;
Json::Value cntProp(Json::objectValue);
cntProp["type"] = "integer";
props["windowCount"] = cntProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("window");
required.append("windowCount");
schema["required"] = required;
return schema;
}
// get_screenshot 的 inputSchema(id 必填,max_width 可选)
Json::Value BuildGetScreenshotInputSchema() {
Json::Value props(Json::objectValue);
@@ -1774,6 +1849,24 @@ Json::Value BuildGetScreenshotInputSchema() {
return schema;
}
// get_foreground_window 的 inputSchema(id 必填)
Json::Value BuildGetForegroundWindowInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
schema["required"] = required;
return schema;
}
// list_files 的 inputSchema(id 必填,path 可选;path 缺省/空 = 列盘)
Json::Value BuildListFilesInputSchema() {
Json::Value props(Json::objectValue);
@@ -2046,6 +2139,18 @@ std::string BuildToolsListResult(const Json::Value& id) {
tools.append(tool);
}
// 7b) get_foreground_window(窗口信息 RPC,CLIENT_CAP_WINDOW_INFO,仅 Windows)
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_foreground_window";
tool["description"] = u8"获取指定在线 Windows 主机当前的前台窗口(GetForegroundWindow):标题、hwnd、pid、虚拟桌面坐标矩形、是否最小化/最大化、z 序与可见窗口总数。注入键鼠前先用它确认焦点在目标窗口上(remote_keyboard / remote_mouse 的 expect_hwnd 也可做同样的前置校验)。主连接 RPC、一次性返回;要求客户端能力位 CLIENT_CAP_WINDOW_INFO(新客户端),老客户端返回 -32005。只读。";
tool["inputSchema"] = BuildGetForegroundWindowInputSchema();
tool["outputSchema"] = BuildGetForegroundWindowOutputSchema();
tools.append(tool);
}
// 8) list_files(P2c:文件链路,列盘/列目录)
{
Json::Value tool(Json::objectValue);
@@ -2359,7 +2464,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "remote_keyboard";
tool["description"] = u8"向已建立的远程控制会话注入键盘事件。action 可选 key_down / key_up / key_press / type:前三种需 key(虚拟键名,如 ENTER/TAB/F5/LEFT/CTRL/ALT/SHIFT/WIN,Linux 侧映射为 X11 keysym),type 需 text(仅 ASCII 文本;非 ASCII 请用 remote_clipboard + Ctrl+V)。modifiers 可选(CTRL/ALT/SHIFT/WIN)。";
tool["description"] = u8"向已建立的远程控制会话注入键盘事件。action 可选 key_down / key_up / key_press / type:前三种需 key(虚拟键名,如 ENTER/TAB/F5/LEFT/CTRL/ALT/SHIFT/WIN,Linux 侧映射为 X11 keysym),type 需 text(仅 ASCII 文本;非 ASCII 请用 remote_clipboard + Ctrl+V)。modifiers 可选(CTRL/ALT/SHIFT/WIN)。可选 expect_hwnd:注入前先确认目标窗口仍在可见列表里(整数或 0x 字符串);配合 require_foreground=true 还要求它已是前台,否则不发注入返回 -32000;同时默认在结果里回报注入后的前台窗口(structuredContent.foreground),用于确认按键真的进了目标窗口。窗口校验仅新 Windows 客户端支持,其他客户端返回 -32005。";
tool["inputSchema"] = BuildRemoteKeyboardInputSchema();
tool["outputSchema"] = BuildRemoteKeyboardOutputSchema();
tools.append(tool);
@@ -2367,7 +2472,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 正=向下滚、负=向上滚。";
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["inputSchema"] = BuildRemoteMouseInputSchema();
tool["outputSchema"] = BuildRemoteMouseOutputSchema();
tools.append(tool);
@@ -2438,7 +2543,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "operate_window";
tool["description"] = u8"对指定在线 Windows 主机的窗口执行操作:close(关闭)/show(显示)/hide(隐藏)/minimize(最小化)/maximize(最大化)/restore(还原)。hwnd 取 list_windows 或 host_list_windows 返回的 hwnd。ok 仅表示已下发(窗口句柄可能已失效)。关闭窗口只有本工具能做,host_control_window 不提供 close,且它会重新枚举可见窗口复核结果。dry_run=true 只校验 hwnd 是否还在可见窗口列表里并返回该窗口信息,不发送任何命令。";
tool["description"] = u8"对指定在线 Windows 主机的窗口执行操作:close(关闭)/show(显示)/hide(隐藏)/minimize(最小化)/maximize(最大化)/restore(还原)/activate(激活到前台)。hwnd 取 list_windows 或 host_list_windows 返回的 hwnd。ok 仅表示已下发(窗口句柄可能已失效);action=activate 例外:工具会在动作后用窗口信息 RPC 复核 GetForegroundWindow,返回 ok/state(foreground|background|missing)/window,旧客户端不支持时返回 -32005(可退回 show)。关闭窗口只有本工具能做,host_control_window 不提供 close,且它会重新枚举可见窗口复核结果。dry_run=true 只校验 hwnd 是否还在可见窗口列表里并返回该窗口信息,不发送任何命令。";
tool["inputSchema"] = BuildOperateWindowInputSchema();
tool["outputSchema"] = BuildOperateWindowOutputSchema();
tools.append(tool);
@@ -2758,6 +2863,8 @@ void AppendHostTechnicalDetail(CMy2015RemoteDlg* parent, uint64_t devId, Json::V
caps["fileTransferV2"] = ctx->SupportsFileV2();
caps["c2cPaths"] = ctx->SupportsC2CPaths();
caps["registry"] = IsWindowsClient(ctx);
// windowInfo → get_foreground_window / host_list_windows 的矩形与 activate(SupportsWindowInfo)
caps["windowInfo"] = ctx->SupportsWindowInfo();
host["capabilities"] = caps;
}
@@ -3173,6 +3280,59 @@ std::string BuildGetScreenshot(const Json::Value& id, const Json::Value& args, C
return BuildResult(id, result);
}
// tools/call:get_foreground_window(窗口信息 RPC,主连接,不建子链接、不弹框)
std::string BuildGetForegroundWindow(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));
std::vector<WindowEntry> wins;
std::string ferr;
int rc = FetchWindowInfo(ctx, devId, "get_foreground_window", 0, wins, ferr);
if (rc == 1)
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
if (rc == 4)
return BuildError(id, -32005, "Host does not support window info (old client)");
if (rc != 0)
return BuildError(id, rc == 2 ? -32001 : -32000, "Failed to get window info: " + ferr);
const WindowEntry* fg = nullptr;
for (const WindowEntry& e : wins) {
if (e.flags & WINDOWINFO_FOREGROUND) { fg = &e; break; }
}
Json::Value structuredContent(Json::objectValue);
structuredContent["windowCount"] = (Json::UInt)wins.size();
structuredContent["window"] = fg ? WindowEntryToJson(*fg) : Json::Value(Json::nullValue);
Json::Value result(Json::objectValue);
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
if (fg) {
item["text"] = std::string(u8"前台窗口:") + fg->title +
" (hwnd=" + std::to_string(fg->hwnd) +
", pid=" + std::to_string(fg->pid) +
", rect=" + std::to_string(fg->left) + "," + std::to_string(fg->top) + "," +
std::to_string(fg->right) + "," + std::to_string(fg->bottom) + ")";
} else {
item["text"] = std::string(u8"未找到前台窗口(可能被 UAC/安全桌面遮挡,或客户端为老版本)");
}
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// 新客户端的结构化失败回报布局:[token:1][win32/status:4 LE]。读取其中 4 字节错误码。
static DWORD ReadWin32Payload(const std::vector<BYTE>& data) {
DWORD v = 0;
@@ -5043,6 +5203,25 @@ Json::Value BuildRemoteKeyboardInputSchema() {
mods["description"] = u8"修饰键(可选):CTRL/ALT/SHIFT/WIN";
props["modifiers"] = mods;
Json::Value expect(Json::objectValue);
Json::Value expectTypes(Json::arrayValue);
expectTypes.append("integer");
expectTypes.append("string");
expect["type"] = expectTypes;
expect["description"] = u8"可选:注入前先确认目标窗口仍在当前可见窗口列表中(整数或 0x 前缀字符串)。"
u8"顺带默认回报前台窗口;仅新 Windows 客户端支持(否则 -32005)。";
props["expect_hwnd"] = expect;
Json::Value requireFg(Json::objectValue);
requireFg["type"] = "boolean";
requireFg["description"] = u8"可选:配合 expect_hwnd,要求该窗口已是前台,否则不发注入并返回 -32000。默认 false";
props["require_foreground"] = requireFg;
Json::Value reportFg(Json::objectValue);
reportFg["type"] = "boolean";
reportFg["description"] = u8"可选:注入后回报前台窗口(structuredContent.foreground)。给了 expect_hwnd 时默认 true";
props["report_foreground"] = reportFg;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
@@ -5056,6 +5235,26 @@ Json::Value BuildRemoteKeyboardInputSchema() {
Json::Value BuildRemoteKeyboardOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value windowProp(Json::objectValue);
windowProp["type"] = "object";
windowProp["description"] = u8"expect_hwnd 时注入前的目标窗口快照";
props["expectedWindow"] = windowProp;
Json::Value fgProp(Json::objectValue);
// report_foreground 时若系统没有可枚举的前台窗口,foreground 为 null。
Json::Value fgTypes(Json::arrayValue);
fgTypes.append("object");
fgTypes.append("null");
fgProp["type"] = fgTypes;
fgProp["description"] = u8"注入后的前台窗口(report_foreground 时返回;无前台窗口为 null)";
props["foreground"] = fgProp;
Json::Value fgErr(Json::objectValue);
fgErr["type"] = "string";
fgErr["description"] = u8"前台回报失败的原因(注入本身已成功)";
props["foregroundError"] = fgErr;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
@@ -5078,6 +5277,142 @@ static bool SendScreenCtrlEvents(context* subCtx, const std::vector<MSG64>& batc
return true;
}
// ===== 输入注入的窗口校验(expect_hwnd / require_foreground / report_foreground)=====
//
// 键鼠注入走屏幕子连接,窗口信息走主连接 RPC,两条链路互不占用,可安全地一前一后。
// 这些辅助只在调用方显式要求时才发 RPC:注入本身不能因为「查不到前台窗口」而失败。
// 解析可选 hwnd(非零整数,或 "0x..." / 十进制字符串)。
static bool GetOptionalWindowArg(const Json::Value& args, const char* key, uint32_t& out,
bool& present, std::string& err) {
present = false;
out = 0;
if (!args.isMember(key) || args[key].isNull()) return true;
const Json::Value& v = args[key];
uint64_t val = 0;
if (v.isNumeric()) {
if (v.isDouble()) {
double d = v.asDouble();
if (d < 1.0 || d > 4294967295.0 || d != (double)(uint64_t)d) {
err = std::string("Invalid ") + key + ": expected a non-zero integer window handle";
return false;
}
val = (uint64_t)d;
} else {
Json::Int64 n = v.asInt64();
if (n <= 0) {
err = std::string("Invalid ") + key + ": expected a non-zero window handle";
return false;
}
val = (uint64_t)n;
}
} else if (v.isString()) {
const std::string s = Trim(v.asString());
char* end = nullptr;
if (s.size() > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
val = strtoull(s.c_str() + 2, &end, 16);
else
val = strtoull(s.c_str(), &end, 10);
if (end == s.c_str() || *end != '\0') {
err = std::string("Invalid ") + key + ": expected a decimal integer or 0x-prefixed hex";
return false;
}
} else {
err = std::string("Invalid ") + key + ": expected an integer or string window handle";
return false;
}
if (val == 0 || val > 0xFFFFFFFFull) {
err = std::string("Invalid ") + key + ": window handle out of range";
return false;
}
out = (uint32_t)val;
present = true;
return true;
}
static bool GetOptionalBoolArg(const Json::Value& args, const char* key, bool& out,
std::string& err) {
out = false;
if (!args.isMember(key) || args[key].isNull()) return true;
if (!args[key].isBool()) {
err = std::string("Invalid ") + key + ": expected a boolean";
return false;
}
out = args[key].asBool();
return true;
}
struct WindowLookup {
int rc = 0; // FetchWindowInfo 返回码
std::string err;
bool found = false;
bool foreground = false;
bool truncated = false; // 客户端可见窗口多于单包上限,列表不完整
Json::Value json; // 目标窗口快照;未找到时为 null
};
// 按 hwnd 在最新可见窗口列表里查找(只发一次窗口信息 RPC)。
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);
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.json = WindowEntryToJson(e);
break;
}
}
return w;
}
// 窗口信息 RPC 失败 → 序列化的 JSON-RPC 错误(与 get_foreground_window 同一错误口径)。
static std::string WindowRpcErrorJson(const Json::Value& id, uint64_t devId, int rc,
const std::string& err) {
if (rc == 1)
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
if (rc == 4)
return BuildError(id, -32005, "Host does not support window info (old client)");
return BuildError(id, rc == 2 ? -32001 : -32000, "Window check failed: " + err);
}
// expect_hwnd 在窗口列表里没命中:列表被单包上限截断时不能说"窗口不存在",
// 只能说明它没出现在返回的这一批里。
static std::string WindowNotFoundErrorJson(const Json::Value& id, uint32_t hwnd, bool truncated) {
const std::string win = "Window hwnd=" + std::to_string(hwnd);
if (truncated)
return BuildError(id, -32009, win + " is not in the returned window list, and that list was "
"truncated at 96 windows (the host has more visible windows), "
"so the window may still exist; verify with host_list_windows "
"or use the foreground window");
return BuildError(id, -32009, win + " is not in the current visible window list "
"(hidden, closed, or not a visible top-level window)");
}
// 注入后回报前台窗口。失败只写 foregroundError:注入已经发生,不能因此把工具判失败。
static void AppendForegroundReport(Json::Value& structuredContent, context* ctx, uint64_t devId,
const char* tool) {
Sleep(150);
std::vector<WindowEntry> wins;
std::string ferr;
int rc = FetchWindowInfo(ctx, devId, tool, 0, wins, ferr);
if (rc != 0) {
structuredContent["foregroundError"] = ferr;
return;
}
for (const WindowEntry& e : wins) {
if (e.flags & WINDOWINFO_FOREGROUND) {
structuredContent["foreground"] = WindowEntryToJson(e);
return;
}
}
structuredContent["foreground"] = Json::Value(Json::nullValue);
}
// tools/call:remote_keyboard(键盘注入;成功返回空对象)
std::string BuildRemoteKeyboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
@@ -5140,6 +5475,28 @@ std::string BuildRemoteKeyboard(const Json::Value& id, const Json::Value& args,
if (batch.empty())
return BuildError(id, -32602, "No key events generated");
// ---- expect_hwnd / require_foreground:注入前核对目标窗口(可选,走窗口信息 RPC)----
uint32_t expectHwnd = 0;
bool hasExpect = false, requireForeground = false, reportForeground = false;
{
std::string oerr;
if (!GetOptionalWindowArg(args, "expect_hwnd", expectHwnd, hasExpect, 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())
return BuildError(id, -32005,
"expect_hwnd/report_foreground require window info capability, "
"which this host does not support (newer Windows clients only)");
// 未显式指定 report_foreground 时,只要给了 expect_hwnd 就默认回报前台窗口。
if (!args.isMember("report_foreground") || args["report_foreground"].isNull())
reportForeground = hasExpect;
}
// 校验 session_id/busy 并置 busy(注入期间 close/sweep/断线不擦会话,镜像终端 busy 模式)。
context* subCtx = nullptr;
int screenW = 0, screenH = 0;
@@ -5147,6 +5504,26 @@ std::string BuildRemoteKeyboard(const Json::Value& id, const Json::Value& args,
if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session");
if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId);
// 窗口核对放在会话校验之后:session_id 无效时应当先报会话错误,不白跑一次 RPC;
// busy 已置上,窗口不满足时必须先释放再返回。
WindowLookup expectWin;
if (hasExpect) {
expectWin = LookupWindow(ctx, devId, "remote_keyboard", expectHwnd);
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);
else if (requireForeground && !expectWin.foreground)
winErr = BuildError(id, -32000, "Window hwnd=" + std::to_string(expectHwnd) +
" is not the foreground window; activate it first "
"(host_control_window / operate_window action=activate)");
if (!winErr.empty()) {
mcp.EndScreenCtrlAction(devId, sessionId);
return winErr;
}
}
bool ok = SendScreenCtrlEvents(subCtx, batch);
mcp.EndScreenCtrlAction(devId, sessionId);
@@ -5166,7 +5543,10 @@ std::string BuildRemoteKeyboard(const Json::Value& id, const Json::Value& args,
}
Json::Value result(Json::objectValue);
result["structuredContent"] = Json::Value(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
if (hasExpect) structuredContent["expectedWindow"] = expectWin.json;
if (reportForeground) AppendForegroundReport(structuredContent, ctx, devId, "remote_keyboard");
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
@@ -5280,6 +5660,25 @@ Json::Value BuildRemoteMouseInputSchema() {
del["description"] = u8"滚动量(仅 scroll;正=向下滚,负=向上滚,与 Web 控制台一致;仅垂直滚轮,忽略 button)";
props["delta"] = del;
Json::Value expect(Json::objectValue);
Json::Value expectTypes(Json::arrayValue);
expectTypes.append("integer");
expectTypes.append("string");
expect["type"] = expectTypes;
expect["description"] = u8"可选:注入前先确认目标窗口仍在当前可见窗口列表中(整数或 0x 前缀字符串)。"
u8"顺带默认回报前台窗口;仅新 Windows 客户端支持(否则 -32005)。";
props["expect_hwnd"] = expect;
Json::Value requireFg(Json::objectValue);
requireFg["type"] = "boolean";
requireFg["description"] = u8"可选:配合 expect_hwnd,要求该窗口已是前台,否则不发注入并返回 -32000。默认 false";
props["require_foreground"] = requireFg;
Json::Value reportFg(Json::objectValue);
reportFg["type"] = "boolean";
reportFg["description"] = u8"可选:注入后回报前台窗口(structuredContent.foreground)。给了 expect_hwnd 时默认 true";
props["report_foreground"] = reportFg;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
@@ -5295,6 +5694,26 @@ Json::Value BuildRemoteMouseInputSchema() {
Json::Value BuildRemoteMouseOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value windowProp(Json::objectValue);
windowProp["type"] = "object";
windowProp["description"] = u8"expect_hwnd 时注入前的目标窗口快照";
props["expectedWindow"] = windowProp;
Json::Value fgProp(Json::objectValue);
// report_foreground 时若系统没有可枚举的前台窗口,foreground 为 null。
Json::Value fgTypes(Json::arrayValue);
fgTypes.append("object");
fgTypes.append("null");
fgProp["type"] = fgTypes;
fgProp["description"] = u8"注入后的前台窗口(report_foreground 时返回;无前台窗口为 null)";
props["foreground"] = fgProp;
Json::Value fgErr(Json::objectValue);
fgErr["type"] = "string";
fgErr["description"] = u8"前台回报失败的原因(注入本身已成功)";
props["foregroundError"] = fgErr;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
@@ -5355,6 +5774,28 @@ 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)----
uint32_t expectHwnd = 0;
bool hasExpect = false, requireForeground = false, reportForeground = false;
{
std::string oerr;
if (!GetOptionalWindowArg(args, "expect_hwnd", expectHwnd, hasExpect, 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())
return BuildError(id, -32005,
"expect_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;
}
WindowLookup expectWin;
// 校验 session_id/busy 并置 busy,同时取抓屏帧尺寸(screenW/H>0 由会话就绪保证)。
context* subCtx = nullptr;
int screenW = 0, screenH = 0;
@@ -5362,6 +5803,25 @@ std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy
if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session");
if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId);
// 窗口核对放在会话校验之后:session_id 无效时应当先报会话错误,不白跑一次 RPC;
// busy 已置上,窗口不满足时必须先释放再返回。
if (hasExpect) {
expectWin = LookupWindow(ctx, devId, "remote_mouse", expectHwnd);
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);
else if (requireForeground && !expectWin.foreground)
winErr = BuildError(id, -32000, "Window hwnd=" + std::to_string(expectHwnd) +
" is not the foreground window; activate it first "
"(host_control_window / operate_window action=activate)");
if (!winErr.empty()) {
mcp.EndScreenCtrlAction(devId, sessionId);
return winErr;
}
}
// 归一化坐标 → 发送帧像素(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); };
@@ -5430,7 +5890,10 @@ std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy
}
Json::Value result(Json::objectValue);
result["structuredContent"] = Json::Value(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
if (hasExpect) structuredContent["expectedWindow"] = expectWin.json;
if (reportForeground) AppendForegroundReport(structuredContent, ctx, devId, "remote_mouse");
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
@@ -7066,8 +7529,15 @@ std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, C
else if (action == "restore") dHow = SW_NORMAL; // 1
else if (action == "maximize") dHow = SW_MAXIMIZE; // 3
else if (action == "minimize") dHow = SW_MINIMIZE; // 6
else if (action == "activate") {
// 后台窗口仅 ShowWindow 不会升到前台:依赖新客户端的激活实现。
if (!ctx->SupportsWindowInfo())
return BuildError(id, -32005,
"activate requires a newer client (window info capability); use show instead");
dHow = CMD_WINDOW_ACTIVATE_FLAG;
}
else return BuildError(id, -32602,
"Invalid action: " + action + " (expect close|show|hide|minimize|maximize|restore)");
"Invalid action: " + action + " (expect close|show|hide|minimize|maximize|restore|activate)");
lpMsgBuf[0] = CMD_WINDOW_TEST;
memcpy(lpMsgBuf + 1, &h, sizeof(DWORD));
memcpy(lpMsgBuf + 1 + sizeof(DWORD), &dHow, sizeof(DWORD));
@@ -7145,6 +7615,60 @@ std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, C
AuditManageAction(parent, devId, "operate_window",
"action=" + action + " hwnd=" + std::to_string(hwnd));
if (action == "activate") {
Sleep(300); // 给客户端激活线程 / 系统前台切换留出时间
std::vector<WindowEntry> wins;
std::string ferr;
bool winTruncated = false;
int rc = FetchWindowInfo(ctx, devId, "operate_window", 0, wins, ferr, &winTruncated);
if (rc == 1)
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
const WindowEntry* target = nullptr;
if (rc == 0) {
for (const WindowEntry& e : wins) {
if (e.hwnd == (uint32_t)hwnd) { target = &e; break; }
}
}
bool isForeground = target && (target->flags & WINDOWINFO_FOREGROUND) != 0;
// 列表被 96 条上限截断时,没找到目标只是"没看到",不能断言窗口不存在。
const bool listIncomplete = (rc == 0 && winTruncated);
std::string state = (rc != 0) ? "unknown"
: (!target ? (listIncomplete ? "unknown" : "missing")
: (isForeground ? "foreground" : "background"));
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["ok"] = isForeground;
structuredContent["action"] = action;
structuredContent["state"] = state;
structuredContent["window"] = target ? WindowEntryToJson(*target) : Json::Value(Json::nullValue);
if (rc != 0)
structuredContent["verifyError"] = ferr;
else if (listIncomplete)
structuredContent["truncated"] = true;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
if (isForeground)
item["text"] = u8"窗口已激活并成为前台窗口(复核 GetForegroundWindow 一致)";
else if (rc != 0)
item["text"] = u8"窗口操作已下发,但前台复核失败:" + ferr;
else if (!target && listIncomplete)
item["text"] = u8"窗口操作已下发,但复核用的窗口列表被单次上限截断(可见窗口超过 96 个),"
u8"目标不在返回的这一批里,无法确认是否已到前台";
else if (!target)
item["text"] = u8"窗口操作已下发,但复核时目标窗口不在可见窗口列表中(可能已关闭或已隐藏)";
else
item["text"] = u8"窗口操作已下发,但目标窗口仍未成为前台窗口(可能被系统前台锁定策略拦下,可重试)";
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["ok"] = true;
@@ -8838,6 +9362,8 @@ const ToolPlatform kToolPlatforms[] = {
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac },
// ---- win+lnx ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项
{ "get_screenshot", kPlatWin|kPlatLnx },
// 窗口信息 RPC 只在 Windows 客户端实现(CLIENT_CAP_WINDOW_INFO)
{ "get_foreground_window", kPlatWin },
{ "remote_open", kPlatWin|kPlatLnx },
{ "remote_close", kPlatWin|kPlatLnx },
{ "remote_keyboard", kPlatWin|kPlatLnx },
@@ -9192,6 +9718,7 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
if (toolName == "list_windows") return BuildListWindows(id, args, parent);
if (toolName == "get_activity_history") return BuildGetActivityHistory(id, args, parent);
if (toolName == "get_screenshot") return BuildGetScreenshot(id, args, parent);
if (toolName == "get_foreground_window") return BuildGetForegroundWindow(id, args, parent);
if (toolName == "list_files") return BuildListFiles(id, args, parent);
if (toolName == "list_services") return BuildListServices(id, args, parent);
if (toolName == "get_client_log") return BuildGetClientLog(id, args, parent);