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:
yuanyuanxianganddeepseek-flash committed 2026-11-08 15:22:09 +01:00
1 parent 5f40f3726c
commit d8048979e3
6 files changed
+940 -14

No files matched your search

+562
View File
@@ -0,0 +1,562 @@
#pragma once
// Linux 客户端的「历史活动」(服务端 COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY)。
//
// 双后端:
// 窗口后端:有可用桌面(X11 + EWMH)时,后台每秒采样前台窗口,输出格式与 Windows
// 端 client/ActivityHistory.cpp 完全一致:[时间] [窗口标题] 时长
// 无头后端:没有桌面时(服务器/容器/daemon 启动时 DISPLAY 不可用),查询时现算
// 「登录记录 + shell 命令历史」,每行带 [登录] / [命令] 标签,首行标明来源
//
// 服务端 CActivityDialog 与 MCP get_activity_history 都只按行切分纯文本,不需要改。
// 纯解析函数放在这里(不依赖 X11),单元测试见 test/unit/linux/ActivityHistoryTest.cpp。
#include <string>
#include <vector>
#include <deque>
#include <mutex>
#include <thread>
#include <atomic>
#include <chrono>
#include <functional>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#ifndef _WIN32
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
// 与 Windows 端 client/ActivityHistory.h 保持一致
#ifndef ACTIVITY_MIN_DWELL_SEC
#define ACTIVITY_MIN_DWELL_SEC 5 // 一闪而过阈值(秒):驻留低于此值不记录
#endif
#ifndef ACTIVITY_IDLE_BREAK_SEC
#define ACTIVITY_IDLE_BREAK_SEC 300 // 空闲打断阈值(秒):与 Windows 端一致
#endif
#ifndef ACTIVITY_HISTORY_MAX
#define ACTIVITY_HISTORY_MAX 500 // 内存保留的最大记录条数
#endif
namespace LinuxActivity {
// 采样线程从 X11 拿到的一条观测:id==0 表示空闲/无窗口/取不到标题
struct ProbeResult
{
unsigned long winId = 0;
std::string title;
};
inline std::tm LocalTimeOf(std::time_t t)
{
std::tm tm{};
#ifdef _WIN32
localtime_s(&tm, &t);
#else
localtime_r(&t, &tm);
#endif
return tm;
}
inline std::string FormatTimeStamp(std::time_t t)
{
std::tm tm = LocalTimeOf(t);
char buf[80]; // 64 够放下极限值,多留一点让 -Wformat-truncation 闭嘴
snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
return buf;
}
inline std::string NowStr()
{
return FormatTimeStamp(std::time(nullptr));
}
// 时长格式化:Ns / Nm / NmNs / NhNm(与 Windows 端一致)
inline std::string FormatDuration(int sec)
{
if (sec < 0) sec = 0;
if (sec < 60)
return std::to_string(sec) + "s";
if (sec < 3600) {
int m = sec / 60, s = sec % 60;
return s ? std::to_string(m) + "m" + std::to_string(s) + "s"
: std::to_string(m) + "m";
}
int h = sec / 3600, m = (sec % 3600) / 60;
return std::to_string(h) + "h" + std::to_string(m) + "m";
}
// UTF-8 尾字节修正:按字节截断可能切在多字节字符中间,而服务端要按 UTF-8
// 转 GBK(对话框)或塞进 JSON(MCP),半截字符会变成乱码/非法 JSON。
// 返回可以安全截断的位置。
inline size_t Utf8Boundary(const std::string& s)
{
const size_t n = s.size();
size_t i = n;
while (i > 0 && n - i < 3 && ((unsigned char)s[i - 1] & 0xC0) == 0x80) --i;
if (i == 0) return n;
const unsigned char c = (unsigned char)s[i - 1];
size_t need = 1;
if ((c & 0x80) == 0) need = 1;
else if ((c & 0xE0) == 0xC0) need = 2;
else if ((c & 0xF0) == 0xE0) need = 3;
else if ((c & 0xF8) == 0xF0) need = 4;
return (n - (i - 1) >= need) ? n : i - 1;
}
// 控制字符换成空格(换行会破坏「每行一条」),可选截断
inline std::string CleanLine(const std::string& s, size_t maxLen = 512)
{
std::string out;
out.reserve(std::min(s.size(), maxLen));
bool cut = false;
for (char c : s) {
unsigned char uc = (unsigned char)c;
out += (uc < 0x20 || uc == 0x7f) ? ' ' : c;
if (out.size() >= maxLen) { cut = true; break; }
}
if (cut) out.resize(Utf8Boundary(out));
return out;
}
inline std::string FormatWindowRecord(const std::string& startTime, const std::string& title, int dwellSec)
{
return "[" + startTime + "] [" + CleanLine(title) + "] " + FormatDuration(dwellSec);
}
inline std::string FormatCommandRecord(std::time_t ts, const std::string& user, const std::string& cmd)
{
std::string t = ts > 0 ? FormatTimeStamp(ts) : std::string("时间未知");
return "[" + t + "] [命令] " + user + ": " + cmd;
}
inline std::vector<std::string> SplitWs(const std::string& s)
{
std::vector<std::string> out;
size_t i = 0;
while (i < s.size()) {
while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\r')) ++i;
size_t start = i;
while (i < s.size() && s[i] != ' ' && s[i] != '\t' && s[i] != '\r') ++i;
if (i > start) out.push_back(s.substr(start, i - start));
}
return out;
}
// bash / zsh 历史文本解析。
// bash 设了 HISTTIMEFORMAT 时按 "#<epoch>" + 命令成对写;
// zsh 开 EXTENDED_HISTORY 时写成 ": <epoch>:<elapsed>;命令"。
// 其余按普通行处理(时间未知)。
inline std::vector<std::string> ParseShellHistoryText(const std::string& text,
const std::string& user,
size_t maxLines)
{
std::vector<std::string> out;
std::time_t pending = 0;
size_t i = 0;
while (i < text.size()) {
size_t nl = text.find('\n', i);
std::string line = text.substr(i, nl == std::string::npos ? std::string::npos : nl - i);
i = (nl == std::string::npos) ? text.size() : nl + 1;
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.empty()) continue;
// "#1699560000" —— 只认纯数字,避免把真实的 "#注释" 当成时间戳
if (line[0] == '#' && line.size() > 1 && line.size() <= 13 &&
std::all_of(line.begin() + 1, line.end(),
[](unsigned char c) { return c >= '0' && c <= '9'; })) {
try { pending = (std::time_t)std::stoll(line.substr(1)); } catch (...) { pending = 0; }
continue;
}
std::time_t ts = pending;
pending = 0;
if (line.size() > 2 && line[0] == ':' && line[1] == ' ') {
size_t semi = line.find(';');
if (semi != std::string::npos) {
std::string meta = line.substr(2, semi - 2);
size_t colon = meta.find(':');
// 只认 ": <epoch>:<elapsed>;" 这一种形状。bash 里 ": ${PATH:=/usr/bin}; ls"
// 这种命令行同样以 ": " 开头、也带 ';',不能当成 zsh 元数据截掉。
const std::string tsPart = meta.substr(0, colon);
const bool zshMeta = colon != std::string::npos && !tsPart.empty() &&
std::all_of(tsPart.begin(), tsPart.end(),
[](unsigned char c) { return c >= '0' && c <= '9'; });
if (zshMeta) {
try { ts = (std::time_t)std::stoll(tsPart); } catch (...) { ts = 0; }
line = line.substr(semi + 1);
if (line.empty()) continue;
}
}
}
out.push_back(FormatCommandRecord(ts, user, CleanLine(line)));
}
if (out.size() > maxLines)
out.erase(out.begin(), out.end() - (long)maxLines);
return out;
}
inline int MonthNumber(const std::string& m)
{
static const char* kMonths[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
for (int i = 0; i < 12; ++i)
if (m == kMonths[i]) return i + 1;
return 0;
}
// `last -F`(LC_ALL=C)的输出解析。样例:
// root pts/0 203.0.113.7 Fri Nov 7 22:10:33 2026 - ... (00:49)
// reboot system boot 6.8.0-45 Fri Nov 7 22:10:20 2026 - ...
// root tty1 Sat Nov 8 09:00:00 2026 still logged in
// 本地登录没有 host 字段,靠「星期」在字段里的位置判断:
// [user][tty][host][Mon..Sun][Mon月][日][HH:MM:SS][年] 远程登录
// [user][tty][Mon..Sun][月][日][HH:MM:SS][年] 本地登录
// [reboot][system][boot][内核][Mon..Sun][月][日][...] 重启
inline int WeekdayIndex(const std::string& s)
{
static const char* kDays[] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
for (int i = 0; i < 7; ++i)
if (s == kDays[i]) return i;
return -1;
}
inline std::vector<std::string> ParseLastOutput(const std::string& text, size_t maxLines)
{
std::vector<std::string> out;
size_t i = 0;
while (i < text.size() && out.size() < maxLines) {
size_t nl = text.find('\n', i);
std::string line = text.substr(i, nl == std::string::npos ? std::string::npos : nl - i);
i = (nl == std::string::npos) ? text.size() : nl + 1;
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.empty()) continue;
// 文件尾部的说明行不是记录
if (line.compare(0, 12, "wtmp begins ") == 0) continue;
std::vector<std::string> f = SplitWs(line);
if (f.size() < 4) continue;
// 定位「星期」,月份紧跟在它后面;找不到星期的行按未知时间原样保留
size_t wi = 0;
for (; wi < f.size(); ++wi) {
if (WeekdayIndex(f[wi]) >= 0) break;
}
int mon = (wi + 1 < f.size()) ? MonthNumber(f[wi + 1]) : 0;
if (wi >= f.size() || !mon || wi + 4 >= f.size()) {
out.push_back("[时间未知] [登录] " + CleanLine(line));
continue;
}
size_t mi = wi + 1; // 月份字段下标
const std::string& user = f[0];
std::string tty, host;
if (user == "reboot") {
host = (wi >= 4) ? f[3] : std::string(); // 内核版本
} else {
tty = f.size() > 1 ? f[1] : std::string();
host = (wi >= 3) ? f[2] : std::string();
}
int day = atoi(f[mi + 1].c_str());
int hour = 0, minute = 0, sec = 0;
int year = atoi(f[mi + 3].c_str());
std::string ts;
if (sscanf(f[mi + 2].c_str(), "%d:%d:%d", &hour, &minute, &sec) == 3 && year > 1970) {
char buf[80];
snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
year, mon, day, hour, minute, sec);
ts = buf;
}
std::string rec = "[" + (ts.empty() ? std::string("时间未知") : ts) + "] [登录] " + user;
if (user == "reboot") rec += " (system boot)";
if (!tty.empty()) rec += " " + tty;
if (!host.empty() && host != "-") rec += " from " + host;
out.push_back(rec);
}
return out;
}
// reboot 记录里除了时间几乎没别的信息,而无头/WSL 机器的 wtmp 常常堆着几十条
// (每次启动一条),会把真正的登录和命令全挤掉。这里只保留最近的几条。
constexpr size_t ACTIVITY_HEADLESS_MAX_REBOOTS = 10;
inline std::vector<std::string> LimitRebootSpam(const std::vector<std::string>& lines,
size_t maxReboots, size_t budget)
{
std::vector<std::string> kept;
kept.reserve(std::min(lines.size(), budget));
size_t reboots = 0;
for (const auto& l : lines) {
if (l.find("[登录] reboot ") != std::string::npos) {
if (++reboots > maxReboots) continue;
}
if (kept.size() >= budget) break;
kept.push_back(l);
}
return kept;
}
// 一条记录的时间戳键:"[2026-11-08 09:00:00] ..." → "2026-11-08 09:00:00",
// 认不出("[时间未知]")返回空串。
inline std::string RecordTimestampKey(const std::string& line)
{
if (line.size() < 21 || line[0] != '[') return std::string();
size_t close = line.find(']');
if (close == std::string::npos) return std::string();
std::string ts = line.substr(1, close - 1);
if (ts.size() != 19) return std::string();
return ts;
}
// 登录记录和命令历史是两批数据、各自新在前;服务端和 MCP 都按「offset=0 就是最近
// limit 条」分页,合并后必须真正按时间戳排一遍,否则最近的命令会被更早的登录挤到后面。
inline void SortNewestFirst(std::vector<std::string>& lines)
{
std::stable_sort(lines.begin(), lines.end(),
[](const std::string& a, const std::string& b) {
const std::string ka = RecordTimestampKey(a);
const std::string kb = RecordTimestampKey(b);
if (ka.empty() != kb.empty()) return !ka.empty(); // 有时间戳的在前
return ka > kb; // 同为空时两者等价,stable_sort 保持原顺序
});
}
// 窗口后端可用但没有记录时的说明(避免对话框全空)
inline std::string WindowBackendEmptyText()
{
return "[来源] 桌面窗口活动:暂无记录(没有停留超过 5 秒的活动窗口)\n";
}
#ifndef _WIN32
inline std::string RunCommandCapture(const std::string& cmd, size_t maxBytes = 256 * 1024)
{
std::string out;
FILE* p = popen(cmd.c_str(), "r");
if (!p) return out;
char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), p)) > 0) {
out.append(buf, n);
if (out.size() >= maxBytes) break;
}
pclose(p);
return out;
}
// 只读文件尾部,避免把巨型历史文件整个读进来;从中间截断时丢掉半行
inline bool ReadFileTail(const std::string& path, size_t maxBytes, std::string& out)
{
out.clear();
FILE* f = fopen(path.c_str(), "rb");
if (!f) return false;
bool ok = false;
do {
if (fseek(f, 0, SEEK_END) != 0) break;
long len = ftell(f);
if (len < 0) break;
long start = ((size_t)len > maxBytes) ? len - (long)maxBytes : 0;
if (fseek(f, start, SEEK_SET) != 0) break;
char buf[8192];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), f)) > 0) out.append(buf, n);
if (start > 0) {
size_t nl = out.find('\n');
if (nl == std::string::npos) out.clear();
else out.erase(0, nl + 1);
}
ok = true;
} while (0);
fclose(f);
return ok;
}
struct HistoryFile
{
std::string user;
std::string path;
std::time_t mtime;
};
// 客户端通常以 root 运行,但日常操作发生在普通用户 shell 里,两边都收
inline void CollectHistoryFiles(std::vector<HistoryFile>& files)
{
auto add = [&](const std::string& user, const std::string& path) {
struct stat st;
if (stat(path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) return;
files.push_back(HistoryFile{ user, path, st.st_mtime });
};
add("root", "/root/.bash_history");
add("root", "/root/.zsh_history");
DIR* d = opendir("/home");
if (!d) return;
while (struct dirent* e = readdir(d)) {
if (e->d_name[0] == '.') continue;
std::string base = std::string("/home/") + e->d_name;
add(e->d_name, base + "/.bash_history");
add(e->d_name, base + "/.zsh_history");
}
closedir(d);
}
// 无头后端:登录记录(last)+ shell 命令历史,每行一条,首行标注来源。
// includeCommands=false 时只返回登录记录(配置项 activity_commands=0)。
// maxLines 是总行数上限:登录记录先占,剩下的额度给命令。
inline std::string BuildHeadlessDump(bool includeCommands, size_t maxLines = 200)
{
// 登录记录最多占 60%(至少 10 行),余量一定留给命令历史:
// reboot 行虽然先算进来,但下面会被 LimitRebootSpam 削掉大半,不预留额度的话
// 无头机上很可能一条命令都看不到。
const size_t loginBudget = includeCommands
? std::min(maxLines, std::max<size_t>(10, maxLines * 3 / 5))
: maxLines;
std::vector<std::string> logins = LimitRebootSpam(
ParseLastOutput(RunCommandCapture("LC_ALL=C last -n 100 -F 2>/dev/null"), loginBudget),
ACTIVITY_HEADLESS_MAX_REBOOTS, loginBudget);
const size_t cmdBudget = includeCommands && maxLines > logins.size()
? maxLines - logins.size() : 0;
std::vector<std::string> cmds;
if (cmdBudget > 0) {
std::vector<HistoryFile> files;
CollectHistoryFiles(files);
// 最近改过的历史文件排在前面(大致对应当前活跃用户)
std::sort(files.begin(), files.end(),
[](const HistoryFile& a, const HistoryFile& b) { return a.mtime > b.mtime; });
for (const auto& f : files) {
std::string text;
if (!ReadFileTail(f.path, 256 * 1024, text)) continue;
std::vector<std::string> lines = ParseShellHistoryText(text, f.user, cmdBudget);
for (auto it = lines.rbegin(); it != lines.rend(); ++it)
cmds.push_back(*it); // 新在前,与 Windows 端一致
if (cmds.size() >= cmdBudget) break;
}
if (cmds.size() > cmdBudget) cmds.resize(cmdBudget);
}
std::vector<std::string> merged;
merged.reserve(logins.size() + cmds.size());
merged.insert(merged.end(), logins.begin(), logins.end());
merged.insert(merged.end(), cmds.begin(), cmds.end());
SortNewestFirst(merged);
std::string out = std::string("[来源] 无桌面环境:") +
(includeCommands ? "登录记录 + 命令历史" : "仅登录记录") + "\n";
if (merged.empty())
out += "[来源] 没有可用的登录/命令记录\n";
for (const auto& l : merged)
out += l + "\n";
return out;
}
#endif // !_WIN32
// ============== 窗口后端:后台采样线程(与 Windows 端 ActivityHistory 对齐)==============
class ActivityHistory
{
public:
static ActivityHistory& Instance()
{
static ActivityHistory inst;
return inst;
}
// probe 只能由采样线程调用(X11 连接不能跨线程共用,调用方要传自己的实例)
void Start(std::function<ProbeResult()> probe)
{
if (m_started.exchange(true)) return;
m_probe = std::move(probe);
m_running = true;
m_thread = std::thread(&ActivityHistory::Loop, this);
}
void Stop()
{
m_running = false;
if (m_thread.joinable())
m_thread.join();
}
// 最新在前;进行中的窗口(已驻留达阈值)排在最前
std::string Dump() const
{
std::lock_guard<std::mutex> lock(m_mutex);
std::string out;
if (!m_curTitle.empty() && m_curDwellSec >= ACTIVITY_MIN_DWELL_SEC)
out += FormatWindowRecord(m_curStartTime, m_curTitle, m_curDwellSec) + "\n";
for (const auto& r : m_records)
out += r + "\n";
return out;
}
private:
ActivityHistory() = default;
~ActivityHistory() { Stop(); }
ActivityHistory(const ActivityHistory&) = delete;
ActivityHistory& operator=(const ActivityHistory&) = delete;
void Loop()
{
unsigned long lastId = 0;
std::string lastTitle, startTime;
int dwellSec = 0;
while (m_running) {
ProbeResult p = m_probe ? m_probe() : ProbeResult();
{
std::lock_guard<std::mutex> lock(m_mutex);
if (p.winId == 0 || p.title.empty()) {
// 空闲/锁定/无标题:结账上一个窗口
if (lastId != 0 && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
m_records.push_front(FormatWindowRecord(startTime, lastTitle, dwellSec));
lastId = 0;
lastTitle.clear();
dwellSec = 0;
} else if (p.winId == lastId) {
// 同一窗口:标题变了也连续累计(浏览器标签切换标题常变)
++dwellSec;
lastTitle = p.title;
} else {
if (lastId != 0 && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
m_records.push_front(FormatWindowRecord(startTime, lastTitle, dwellSec));
lastId = p.winId;
lastTitle = p.title;
startTime = NowStr();
dwellSec = 1;
}
while (m_records.size() > ACTIVITY_HISTORY_MAX)
m_records.pop_back();
m_curTitle = lastTitle;
m_curStartTime = startTime;
m_curDwellSec = dwellSec;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
mutable std::mutex m_mutex;
std::deque<std::string> m_records; // 已完成记录,最新在前
std::string m_curTitle;
std::string m_curStartTime;
int m_curDwellSec = 0;
std::atomic<bool> m_running{ false };
std::atomic<bool> m_started{ false };
std::function<ProbeResult()> m_probe;
std::thread m_thread;
};
} // namespace LinuxActivity