Feature: Report activity history on Linux clients
Implement COMMAND_QUERY_ACTIVITY -> TOKEN_REPORT_ACTIVITY with two backends picked at startup. With a desktop, a sampler thread reads the foreground window every second and books dwell time like the Windows client: under five seconds is dropped, five idle minutes close the window, the last 500 records stay newest first, each line being "[YYYY-MM-DD HH:MM:SS] [title] duration". It uses its own ActivityChecker because an Xlib connection cannot be shared with the heartbeat thread, and it is stopped before main's locals go away. A reachable X server is not enough: the window backend is only chosen when the root window carries _NET_SUPPORTING_WM_CHECK, so Xvfb or a bare X without an EWMH window manager falls back to the headless backend instead of sampling a window id that never appears. Without a desktop the answer is computed on demand: logins from "last -n 100 -F" plus bash/zsh history of root and /home/*, tagged [登录] or [命令] after a [来源] header. Both halves are merged and sorted by timestamp; three fifths of the budget goes to logins and reboot records are capped at ten, since a WSL or container writes one reboot per start. activity_commands=0 drops the command half. A single detached thread builds and sends it, only while the main link is up. The MCP gate now admits Linux for get_activity_history and documents both shapes. test/unit/linux covers the parsers, ordering and UTF-8 truncation; 15 cases pass. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
5f40f3726c
commit
d8048979e3
6 files changed
+940
-14
No files matched your search
+121
-11
@@ -45,6 +45,7 @@
|
||||
#include "common/host_transfer.h"
|
||||
#include "common/host_share.h"
|
||||
#include "LinuxConfig.h"
|
||||
#include "LinuxActivityHistory.h"
|
||||
#include <openssl/evp.h>
|
||||
#include <cctype>
|
||||
#include <vector>
|
||||
@@ -250,6 +251,32 @@ public:
|
||||
return "Inactive: " + FormatMilliseconds(idle);
|
||||
}
|
||||
|
||||
// 历史活动采样用:有桌面、用户未空闲且存在活动窗口时返回 id+标题,否则 id=0。
|
||||
// 与 Check 的区别是不把「空闲」包装成 Inactive 文本 —— 采样端只关心"有没有活动"。
|
||||
LinuxActivity::ProbeResult Probe(unsigned long idle_threshold_ms = 6000)
|
||||
{
|
||||
LinuxActivity::ProbeResult r;
|
||||
if (!m_available) return r;
|
||||
if (GetIdleTime() >= idle_threshold_ms) return r;
|
||||
r.winId = GetActiveWindowId();
|
||||
if (r.winId == 0) return r;
|
||||
r.title = GetWindowTitle(r.winId); // 用刚取到的 id,别再读一次活动窗口(可能已换)
|
||||
return r;
|
||||
}
|
||||
|
||||
bool Available() const { return m_available; }
|
||||
|
||||
// 有桌面且真能跟踪前台窗口:X 连上了还不够,根窗口上得有 _NET_SUPPORTING_WM_CHECK
|
||||
// (EWMH 窗口管理器)。Xvfb、裸 X 这类「有 DISPLAY 没有 WM」的环境里
|
||||
// _NET_ACTIVE_WINDOW 永远读不到,采样只会一直空转,应该按无头后端处理。
|
||||
bool Usable()
|
||||
{
|
||||
if (!m_available) return false;
|
||||
Atom atom = pXInternAtom(m_display, "_NET_SUPPORTING_WM_CHECK", 0);
|
||||
if (!atom) return false;
|
||||
return !GetWindowProperty(m_root, atom, (Atom)0).empty();
|
||||
}
|
||||
|
||||
private:
|
||||
// X11 函数指针类型
|
||||
typedef Display* (*fn_XOpenDisplay)(const char*);
|
||||
@@ -315,10 +342,9 @@ private:
|
||||
return idle;
|
||||
}
|
||||
|
||||
// 获取当前活动窗口标题(通过 EWMH _NET_ACTIVE_WINDOW + _NET_WM_NAME)
|
||||
std::string GetActiveWindowTitle()
|
||||
// 从根窗口读取 _NET_ACTIVE_WINDOW 得到活动窗口 ID;无窗口/WM 不支持时返回 0
|
||||
Window GetActiveWindowId()
|
||||
{
|
||||
// 第一步:从根窗口读取 _NET_ACTIVE_WINDOW 得到活动窗口 ID
|
||||
Atom actualType = 0;
|
||||
int actualFormat = 0;
|
||||
unsigned long nItems = 0, bytesAfter = 0;
|
||||
@@ -329,20 +355,27 @@ private:
|
||||
&actualType, &actualFormat, &nItems, &bytesAfter, &prop);
|
||||
if (ret != 0 || !prop || nItems == 0) {
|
||||
if (prop) pXFree(prop);
|
||||
return "";
|
||||
return 0;
|
||||
}
|
||||
|
||||
Window activeWin = *(Window*)prop;
|
||||
Window w = *(Window*)prop;
|
||||
pXFree(prop);
|
||||
prop = nullptr;
|
||||
return w;
|
||||
}
|
||||
|
||||
if (activeWin == 0) return "";
|
||||
// 获取当前活动窗口标题(通过 EWMH _NET_ACTIVE_WINDOW + _NET_WM_NAME)
|
||||
std::string GetActiveWindowTitle()
|
||||
{
|
||||
return GetWindowTitle(GetActiveWindowId());
|
||||
}
|
||||
|
||||
// 第二步:读取 _NET_WM_NAME (UTF-8),失败则回退 WM_NAME
|
||||
std::string title = GetWindowProperty(activeWin, m_atomWmName, m_atomUtf8String);
|
||||
// 指定窗口的标题:_NET_WM_NAME (UTF-8),失败回退 WM_NAME
|
||||
std::string GetWindowTitle(Window win)
|
||||
{
|
||||
if (win == 0) return "";
|
||||
std::string title = GetWindowProperty(win, m_atomWmName, m_atomUtf8String);
|
||||
if (title.empty())
|
||||
title = GetWindowProperty(activeWin, m_atomWmNameLegacy, (Atom)0);
|
||||
|
||||
title = GetWindowProperty(win, m_atomWmNameLegacy, (Atom)0);
|
||||
return title;
|
||||
}
|
||||
|
||||
@@ -576,6 +609,44 @@ static void CheckTransferExpiry()
|
||||
StopChildren(KIND_TRANSFER);
|
||||
}
|
||||
|
||||
// ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ==============
|
||||
// true=桌面窗口采样(启动时 X11 可用),false=无头后端(登录记录 + shell 命令历史)
|
||||
static std::atomic<bool> g_activityWindowBackend(false);
|
||||
|
||||
// 与 Windows 端一致:主连接一次性快照,不开子连接(服务端 TOKEN_REPORT_ACTIVITY 分支
|
||||
// 不 CancelIO)。无头后端要跑 last、读历史文件,所以放线程里,别堵接收线程。
|
||||
// 同时在飞的报表最多一份:连点/多个 MCP 调用会把 popen(last) 和读历史文件叠起来,
|
||||
// 一次几十毫秒的活堆成几百个子进程没有任何意义。
|
||||
static std::atomic<int> g_activityReportsInFlight(0);
|
||||
|
||||
static void ActivityReportThread()
|
||||
{
|
||||
const bool windowBackend = g_activityWindowBackend.load(std::memory_order_relaxed);
|
||||
std::string text;
|
||||
if (windowBackend) {
|
||||
text = LinuxActivity::ActivityHistory::Instance().Dump();
|
||||
if (text.empty())
|
||||
text = LinuxActivity::WindowBackendEmptyText(); // 桌面空闲/刚启动,还没有够 5 秒的窗口
|
||||
} else {
|
||||
LinuxConfig cfg; // 每次现读:activity_commands 改了立刻生效
|
||||
const bool includeCommands = cfg.GetInt("activity_commands", 1) != 0;
|
||||
text = LinuxActivity::BuildHeadlessDump(includeCommands, 200);
|
||||
}
|
||||
|
||||
std::vector<BYTE> pkt(1 + text.size());
|
||||
pkt[0] = TOKEN_REPORT_ACTIVITY;
|
||||
if (!text.empty())
|
||||
memcpy(pkt.data() + 1, text.data(), text.size());
|
||||
// 取快照可能跑上几十毫秒(last/读历史文件),期间主连接可能已经断了或是进程在退出;
|
||||
// 与截屏回包一样:Send2Server 内部持锁,但先确认还连着
|
||||
bool sent = false;
|
||||
if (g_pMainClient && g_pMainClient->IsConnected() && g_bExit == S_CLIENT_NORMAL)
|
||||
sent = g_pMainClient->Send2Server((char*)pkt.data(), (ULONG)pkt.size()) != FALSE;
|
||||
Mprintf("[Activity] report %zu bytes (%s backend)%s\n", text.size(),
|
||||
windowBackend ? "window" : "headless", sent ? "" : " FAILED");
|
||||
g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (szBuffer == nullptr || ulLength == 0)
|
||||
@@ -607,6 +678,21 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
// 子连接;若回在主连接上,被关掉的就是主连接本身。
|
||||
std::thread(ClientLogThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
|
||||
} else if (szBuffer[0] == COMMAND_QUERY_ACTIVITY) {
|
||||
// 历史活动:主连接一次性快照(无子连接),有桌面走窗口采样,无桌面走登录+命令记录。
|
||||
// 已经有报表在飞就丢掉这一次(服务端每主机单飞行,连点也只是重复请求)
|
||||
if (g_activityReportsInFlight.fetch_add(1) >= 1) {
|
||||
g_activityReportsInFlight.fetch_sub(1);
|
||||
return TRUE;
|
||||
}
|
||||
Mprintf("** [%p] Received 'QUERY_ACTIVITY' command ***\n", user);
|
||||
try {
|
||||
std::thread(ActivityReportThread).detach();
|
||||
} catch (const std::exception& e) {
|
||||
// 线程起不来要把在途计数还回去,否则之后的历史活动请求全被当成「忙」丢掉
|
||||
g_activityReportsInFlight.fetch_sub(1);
|
||||
Mprintf("** Activity report thread failed: %s ***\n", e.what());
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_SCREEN_PREVIEW_REQ) {
|
||||
if (ulLength < sizeof(ScreenPreviewReq)) return TRUE;
|
||||
ScreenPreviewReq req;
|
||||
@@ -1894,6 +1980,22 @@ int main(int argc, char* argv[])
|
||||
// 初始化用户活动检测器(用于心跳包中的 ActiveWnd 字段)
|
||||
ActivityChecker activityChecker;
|
||||
|
||||
// 历史活动采样器必须用独立实例:Xlib 连接不能跨线程共用,心跳线程一直在用
|
||||
// activityChecker。没有桌面 / 有 X 但没有 EWMH 窗口管理器时不启动采样线程,
|
||||
// 查询时走无头后端。
|
||||
ActivityChecker historyChecker;
|
||||
const bool windowBackend = historyChecker.Usable();
|
||||
g_activityWindowBackend.store(windowBackend, std::memory_order_relaxed);
|
||||
if (windowBackend) {
|
||||
LinuxActivity::ActivityHistory::Instance().Start([&historyChecker]() {
|
||||
return historyChecker.Probe((unsigned long)ACTIVITY_IDLE_BREAK_SEC * 1000UL);
|
||||
});
|
||||
}
|
||||
Mprintf("[Activity] 历史活动后端: %s\n",
|
||||
windowBackend ? "桌面窗口(X11)"
|
||||
: (historyChecker.Available() ? "无头(登录+命令,X 上没有 EWMH 窗口管理器)"
|
||||
: "无头(登录+命令)"));
|
||||
|
||||
std::unique_ptr<IOCPClient> ClientObject(new IOCPClient(g_bExit, false));
|
||||
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
|
||||
// 不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议只能显式喂进去:否则哪怕
|
||||
@@ -2047,6 +2149,14 @@ int main(int argc, char* argv[])
|
||||
StopChildren(KIND_ALL);
|
||||
}
|
||||
|
||||
// 采样线程要在 main 的局部对象(historyChecker)析构前停掉
|
||||
LinuxActivity::ActivityHistory::Instance().Stop();
|
||||
|
||||
// 历史活动的报表线程是 detached 的,可能还在跑 last / 读历史文件;它最后要写一行日志,
|
||||
// 等它收尾再关日志。最多等 2 秒,等不到就算了(进程要退出,不能因此卡住)。
|
||||
for (int i = 0; i < 20 && g_activityReportsInFlight.load(std::memory_order_relaxed) > 0; ++i)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
|
||||
Logger::getInstance().stop();
|
||||
if (!g_bShareInstance)
|
||||
removePidFile();
|
||||
|
||||
Reference in new issue
Block a user