6 Commits

Author SHA1 Message Date
1b792b91f5 fix(packaging): amd64 GUI 从未走过 electron 缓存,且空壳 node_modules 被当作已安装
干净 worktree 上打包时 GUI 被静默跳过。两个缺陷叠加,都属于「所有外层
检查都通过,只有嵌套的运行时缺失,而没有任何东西喊出来」。

## 一:electron 架构名与 Debian 架构名混用

electron 官方发布物命名用 x64/arm64,Debian 用 amd64/arm64。缓存查找
一直统一用 TAR_ARCH(amd64),于是 electron-v*-linux-x64.zip 永远命中
不到。arm64 两边恰好同名,所以上次修 arm64 GUI 架构污染(743b963)时
这个不一致没暴露。

推论:v1.0.3 的 amd64 GUI 实际是靠「回退到 host node_modules/electron/
dist」这条路组装的,不是走缓存——那条回退只在目标架构 == host 架构时
才允许,恰好成立所以没出错。干净 checkout 里没有完整 node_modules,
回退路径也没有,GUI 就消失了。

修法:单独映射 ELECTRON_ARCH(amd64→x64,arm64→arm64)。

## 二:判 node_modules 目录存在,而非判 electron 包存在

npm install 失败(离线/网络受限)会留下只有一两个条目的空壳
node_modules。原判据 [ ! -d node_modules ] 认为「已安装」,于是跳过
install → ever 读不到版本 → 缓存匹配退化到通配 → host dist 也没有 →
静默跳过 GUI。包名、目录名、变体名全部正确,只是没有 GUI。

修法:判据改为 electron/package.json 是否存在;目录在而包缺失时明确
说明「疑似上次 npm install 未完成」再重试;install 失败给出明确提示
而不是继续往下走。

顺带给 ever 加兜底:读不到已安装版本时从 package.json 的依赖声明取
数字部分(那里是 "^33.0.0" 这类范围,仅用于给缓存匹配一个提示)。

## 验证

干净 worktree(/tmp/rel104,release/v1.0.x)上重跑:
  node_modules 存在但 electron 缺失(疑似上次 npm install 未完成)
  electron 版本取自 package.json 依赖声明: 33.0.0(非精确)
  electron runtime: electron-v33.4.11-linux-x64.zip
  GUI built: build/homeagent-gui-linux-amd64 (263M, x86-64)

file -b 确认 electron 二进制为 x86-64,与目标架构一致(该硬校验由
743b963 引入,此处继续生效)。
2026-09-05 14:59:15 +08:00
208d39c296 chore(release): bump v1.0.4
v1.0.3 之后 release 线合入了两个修复(崩溃隔离测试误杀生产实例、
两处数据竞争),按发布流程第②步把版本号推进到 1.0.4。

同步更新:
  - internal/meta/meta.go    Version 1.0.3 → 1.0.4
  - deploy/packaging/installer.nsi   PRODUCT_VERSION 1.0.4
  - README.md / README_EN.md 项目状态加 v1.0.4 条目、下载文件名更新

SDKCompatibleVersion 保持 1.0.0:本版只改内核并发正确性,插件 ABI/
协议未变,存量 plugin.bin 无需重编。

此提交不 pick 回 main(main 版本号始终是下一个未发布版本)。
2026-09-05 07:26:01 +08:00
eb02f00998 fix(plugins): 修复隔离全量测试暴露的两处数据竞争
-go test ./... -race 全仓复验暴露的 7 处 race、5 个失败测试,全部定位。
两处独立缺陷,互不相关。

## 缺陷一(remotedevice,8 处 race):连接写无串行化

WARNING: DATA RACE
  Read at 0x... by goroutine 28:
    bufio.(*Writer).Available() / writeFrameHeader / PushData
  Previous write at 0x... by goroutine 27:
    bufio.(*Writer).Flush() / writeFrame / handleWS

同一连接的 bufio.Writer 被两条并发路径写:
  - handleWS 主循环:读到设备帧后回写 hello_ack/bind_ack/pong
  - PushJSON/PushData:agent→设备的下发路径,可来自任意 goroutine

bufio.Writer 不是线程安全的。不加锁就在 WriteByte/Flush 上撞——这
不是理论风险,TestWSPushDataAudio 的异步 PushData 与 handleWS 的
hello_ack 回写并发时被 -race 稳定抓到。

修法:wconn 增加 wmu(sync.Mutex),PushJSON/PushData 拿锁后整条
下发(start + N 个 chunk + end)持锁——设备侧按协议串行聚合,中途
被插帧会破坏协议顺序。handleWS 的 hello_ack/bind_ack/pong 也改走
同一把锁(wsWriteLocked 封装,避免调用方绕过)。设备已离线时不回写。

关键点:不能只锁 Push* 不锁 handleWS——那只是把竞争挪了个位置。

## 缺陷二(agentcli,1 处 race):共享读缓冲被并发读写

WARNING: DATA RACE
  Write at 0x... by goroutine 26:
    os.File.Read / (*linuxPty).Read / reader
  Previous read at 0x... by goroutine 25:
    runtime.slicecopy / readLoop

readLoop 创建 buf := make([]byte, ReadBufSize) 传给 reader goroutine
(t.session.Read(buf) 持续覆写),自己又在读到结果后
copy(data, buf[:r.n])——同一缓冲被读写并发。Go 的 pty 读走 OS 层
fd,专门在 reader 写下一段时读,跑 -race 稳定复现。

修法:readResult 携带 data field,reader 每次读完后把数据复制进自己
分配的切片再随结果传递,读取与拷贝之间不再共享任何可变状态。原 buf
保留(仍由 reader 独享用于 OS 读),readLoop 不再从其中 copy。

## 验证

  - 两个插件包 -race -count=2 全过
  - 全仓 go build / go vet / go test 通过
  - 全仓 go test ./... -race:32 包全过,0 DATA RACE,0 FAIL
  - SDK 冻结 diff = 0

其中 remotedevice 的 TestScreenseeEndToEnd / TestComputeruseEndToEnd
/ TestClipboardEndToEnd 原本因 race 挂,修后恢复全绿。
2026-09-05 07:24:02 +08:00
f478659b89 fix(test): 崩溃隔离测试误杀同机生产插件,且断言无效
## 现象

生产 homed 的 editdoc 子进程从 9-03 起被 SIGKILL 9 次,间隔完全不规律
(126~485 分钟),全部发生在无工具调用的空闲期。查过 OOM(dmesg/
journalctl -k/cgroup oom_kill 全为 0)、systemd 内存限制(MemoryMax=
infinity)、cron/timer、内核自身的 StopAll 路径、agent 执行过的 cmd_run
命令,以及 Pdeathsig 绑创建线程的可能——全部排除。

## 真因:测试杀了生产的进程

用 ftrace 的 signal_generate tracepoint 挂监视器后抓到发送者 cmdline:

  /tmp/go-build.../plugins.test -test.run=TestRealPlugin_CrashDoesNotKillKernel

findPluginPID 用**全系统** `pgrep -f plugin.bin`,然后只比"exe 路径含
editdoc"。生产实例的 /home/newqqagent/plugins/editdoc/plugin.bin 也满足
这个条件,谁先被 pgrep 列出来就杀谁。9 次 kill 全部落在有人跑 go test
的时段——18:18:30 那次正是一轮 `go test ./... -race` 的窗口。

之前几轮排查一直在生产实例内部找原因,方向从一开始就错了:杀手在仓库里。

## 更严重的是这个测试本身无效

旧断言是"SIGKILL 之后内核仍存活"。可内核本来就活着——即使信号发错了
对象(杀了生产实例的插件),测试内核的插件压根没死,断言照样通过。
**它在测一件没发生的事**,同时把生产环境打坏了,而绿色的测试结果掩盖了
这一切。这也是它能连续 9 次造成生产故障却从没被注意到的原因。

## 修法

findPluginPID 增加 root 硬约束:/proc/<pid>/exe 必须以测试自己的 plgDir
为前缀,且是目标插件,两道条件同时成立才算命中。root 为空直接 t.Fatal
——这不是可选过滤器,是防误杀的前提。

  - 用 exe 而非 cmdline:cmdline 可被进程自行改写,exe 符链由内核维护。
  - root 先过 EvalSymlinks:/tmp 在部分发行版上是符链,不归一化会让前缀
    比较永远不命中,退化成静默 Skip(那样测试就白跑了)。

断言改成两步:先轮询确认目标进程真的退出(3s 上限),再验内核未被连带。
两步都成立才能证明隔离生效。

## 验证

修复后跑 TestRealPlugin_CrashDoesNotKillKernel:
  - 杀的是 pid=3448366,exe 在 /tmp/hc_integration_3823918128/plugins 下 ✓
  - 生产 editdoc pid 测试前后均为 3362892,存活时长连续 ✓
  - 四个 TestRealPlugin_* 全部 PASS
2026-09-04 21:44:19 +08:00
743b963dec fix(packaging): arm64 GUI 塞了 x86-64 electron——按目标架构取运行时并强制校验
## 现象

v1.0.0 与 v1.0.1 的 arm64 full/client 包里,homed 与 waiter 都是正确的
aarch64,但 GUI 目录下的 electron 是 x86-64。实测从 gitcode 下载的
homeagent-full_1.0.1_arm64.deb:

  usr/bin/homed                    ELF 64-bit ARM aarch64   ✓
  usr/bin/waiter                   ELF 64-bit ARM aarch64   ✓
  usr/lib/homeagent-gui/electron   ELF 64-bit x86-64        ✗

在 arm64 机器上装完,双击 GUI 得到 Exec format error。

## 根因

build_gui 无条件 `cp -r "$gui_dir/node_modules/electron/dist"/*`,而那里
永远是 **host 架构**(本机 x64)。目录名 homeagent-gui-linux-arm64 只是
命名,内容从未跟着目标架构变。

这与 v1.0.0 arm64 缺 homed 是同一类错误:**产物名声称的架构与实际内容
不符**,且都因为没做交叉验证而漏过整个发布流程——包名对、目录名对、
主二进制对,只有一个嵌套的运行时是错的,没有任何一环会喊出来。

## 修法:三层取 + 一道强制校验

1. 优先从 electron 缓存取目标架构的 zip
   (~/.cache/electron/<hash>/electron-v<ver>-linux-<arch>.zip)。
   版本号从已安装的 node_modules/electron/package.json 读,保证运行时
   与 app 依赖一致。
2. 回退到 host node_modules/electron/dist 前**先比对架构**:只有目标
   架构 == host 架构才允许;否则打印缺哪个 zip、该放哪里,然后跳过 GUI。
3. 最后用 `file -b` 校验 electron 二进制的实际架构必须匹配目标架构,
   不符就删掉 GUI 目录并跳过。

第 3 步是关键。前两步是「尽量拿对的」,第 3 步是「绝不发错的」——
宁可不发 GUI,也不发装了跑不起来的包。`GUI built:` 日志行也加上架构
标注,日常构建就能看见。

## 验证

下载 arm64 electron 运行时(electron-v33.4.11-linux-arm64.zip,106MB,
unzip -t 无错,解出的 electron 确认为 ARM aarch64)放入缓存后重打包,
三个 arm64 deb 实测:

  server   homed=aarch64  waiter=aarch64
  full     homed=aarch64  waiter=aarch64  electron=aarch64
  client                  waiter=aarch64  electron=aarch64
  amd64 对照                              electron=x86-64

arm64 tar.gz 从 120M 涨到 125M,也印证运行时换成了正确架构。
2026-09-04 20:06:14 +08:00
6b87a1de14 fix(build): GUI 输出目录用 --config.directories.output,-o 是 --mac 的别名
electron-builder 的 `-o` 是 `--mac`/`--macos` 的短别名(见 --help 的
Building 段),不是 output。于是 `-o "$BUILD_DIR"` 被当成 macOS 的 target
列表,报:

  ⨯ Unknown target: /home/program/trueagent/build

路径被 lowercase 后去匹配 target 名表,所以错误信息里的路径是全小写的
——这也是它看起来像「路径错」而实际是「参数位置错」的原因,v1.0.1 与
v1.0.3 两次发布都因此手工组装过 GUI。

改用 --config.directories.output=<dir>,已实测确认产物落在指定目录。

同时把 GUI 构建失败降级为警告:homed/waiter/initconfig 是发布主体,
而 GUI 依赖 electron 运行时下载(离线机器、arm64 缺缓存都会失败)。
set -euo pipefail 下不接住的话,一个可选组件会让整轮跨平台构建全废——
v1.0.3 就是这样只产出了 linux/amd64 三个二进制、arm64 与 windows
压根没跑到。
2026-09-04 19:01:29 +08:00
9 changed files with 302 additions and 74 deletions

View File

@ -193,6 +193,8 @@ internal/
## 项目状态 ## 项目状态
**v1.0.4** — 两处数据竞争修复(现网 `/api/v1/device/ws` 通道与终端推流)。此前 `-race` 全仓复验即暴露:`remotedevice` 网关对同一连接的 `bufio.Writer` 由两条路径并发写(`handleWS` 主循环回写 hello_ack/绑定回执/pong`PushJSON`/`PushData` 的 agent→设备下发`bufio.Writer` 非线程安全,`TestWSPushDataAudio` 异步下发即稳定撞车;`agentcli` 终端把共享读缓冲传给 reader goroutineOS 层持续覆写)又在 `readLoop``copy(data, buf[:r.n])`,读写并发。修法:连接级写锁(`wconn.wmu`Push* 与 handleWS 共用同一把锁,`PushData` 整条下发持锁保证协议顺序)与「读结果随 `readResult` 自带切片传递、不再共享缓冲」。全仓 `go test ./... -race` 由 7 处 race / 5 个测试 FAIL 变为 32 包全绿。
**v1.0.3** — 内核 stage 协调器双重解锁修复。现网 homed 主进程曾一次 `fatal error: sync: unlock of unlocked mutex` 整体死亡(带走全部 27 个子进程插件):`Host.endStage` 把「递减 inflight、判定最后离开者」放在 `coordMu` 临界区之外,而摘除协调器在临界区之内,于是后到插件能挂进一个正在收尾的协调器、被误判成最后离开者,对同一把 `stageMu` 解了两次。**`sync.Mutex` 双重解锁是 runtime fatal 而非 panic两层 `recover` 结构上拦不住**,这才让「插件崩溃不拖垮内核」的隔离设计整体失效。修法是把计数、判定、摘除收进同一临界区,并把首进者写共享段的 `enter()` 也移入锁内(此前后到者可能读到写一半的段)。配套 5 个回归用例,含把旧实现 stash 回来验证测试确实能复现 fatal 的反向验证。 **v1.0.3** — 内核 stage 协调器双重解锁修复。现网 homed 主进程曾一次 `fatal error: sync: unlock of unlocked mutex` 整体死亡(带走全部 27 个子进程插件):`Host.endStage` 把「递减 inflight、判定最后离开者」放在 `coordMu` 临界区之外,而摘除协调器在临界区之内,于是后到插件能挂进一个正在收尾的协调器、被误判成最后离开者,对同一把 `stageMu` 解了两次。**`sync.Mutex` 双重解锁是 runtime fatal 而非 panic两层 `recover` 结构上拦不住**,这才让「插件崩溃不拖垮内核」的隔离设计整体失效。修法是把计数、判定、摘除收进同一临界区,并把首进者写共享段的 `enter()` 也移入锁内(此前后到者可能读到写一半的段)。配套 5 个回归用例,含把旧实现 stash 回来验证测试确实能复现 fatal 的反向验证。
**v1.0.1** — 多模态 bugfix。插件 ABI/协议未变1.0.0 编出的 `plugin.bin` 无需重编。修三类缺陷1**看图假成功**——媒体块挂在 tool message 上不被模型当作可视内容实测同一张图tool message 0/3 读到、独立 user message 3/3改为另起一条紧随其后的 user message 承载落实插件文案一直在说的「注入后续对话」2**新增多模态能力声明与回退链**——`core.llm.sources.<name>.vision/.audio` 声明源能否真正处理媒体(网关会静默剥离 `image_url` 后仍返回 200带图与不带图 prompt_tokens 完全相同),不支持时自动走视觉源转写成文字,并落实了 `core.input_processing.image.fallback_provider` 这批早已注册却从未被读取的配置项3**`see_video` 帧数语义反了**——`fps=1/N` 是频率不是数量20s 视频请求 10 帧只得 2 帧、请求 1 帧反得 20 帧,改为 `ffprobe` 取时长 + `fps=N/时长` + `-frames:v` 硬封顶。 **v1.0.1** — 多模态 bugfix。插件 ABI/协议未变1.0.0 编出的 `plugin.bin` 无需重编。修三类缺陷1**看图假成功**——媒体块挂在 tool message 上不被模型当作可视内容实测同一张图tool message 0/3 读到、独立 user message 3/3改为另起一条紧随其后的 user message 承载落实插件文案一直在说的「注入后续对话」2**新增多模态能力声明与回退链**——`core.llm.sources.<name>.vision/.audio` 声明源能否真正处理媒体(网关会静默剥离 `image_url` 后仍返回 200带图与不带图 prompt_tokens 完全相同),不支持时自动走视觉源转写成文字,并落实了 `core.input_processing.image.fallback_provider` 这批早已注册却从未被读取的配置项3**`see_video` 帧数语义反了**——`fps=1/N` 是频率不是数量20s 视频请求 10 帧只得 2 帧、请求 1 帧反得 20 帧,改为 `ffprobe` 取时长 + `fps=N/时长` + `-frames:v` 硬封顶。
@ -222,7 +224,7 @@ internal/
| **client** | waiter + 桌面 GUI | 连接远程 HomeAgent | | **client** | waiter + 桌面 GUI | 连接远程 HomeAgent |
- Linux`.deb`amd64/arm64)、`.rpm`x86_64)、`.tar.gz` - Linux`.deb`amd64/arm64)、`.rpm`x86_64)、`.tar.gz`
- Windows`HomeAgent_v1.0.3_{Full,Server,Client}_win64.exe`NSIS 安装向导 - Windows`HomeAgent_v1.0.4_{Full,Server,Client}_win64.exe`NSIS 安装向导
- 免安装`homeagent-bin-<os>_<arch>.tar.gz` homed/waiter/initconfig - 免安装`homeagent-bin-<os>_<arch>.tar.gz` homed/waiter/initconfig
- 校验`SHA256SUMS` - 校验`SHA256SUMS`

View File

@ -179,6 +179,8 @@ External plugin development: see [homeagent-sdk](https://gitcode.com/JianFeeeee/
## Project Status ## Project Status
**v1.0.4** — Two data-race fixes (the live `/api/v1/device/ws` gateway and terminal streaming). A full `-race` pass exposed both: `remotedevice` wrote one connection's `bufio.Writer` from two concurrent paths (`handleWS` loop replies hello_ack/bind_ack/pong, plus `PushJSON`/`PushData` agent→device pushes) — `bufio.Writer` is not thread-safe, and `TestWSPushDataAudio` async push hit it reliably; `agentcli` handed the shared read buffer to the reader goroutine (which the OS keeps overwriting) while `readLoop` did `copy(data, buf[:r.n])` — concurrent read/write of the same buffer. Fix: connection-level write lock (`wconn.wmu`, shared by Push* and handleWS; `PushData` holds it across the whole start/chunks/end sequence to preserve protocol order) plus carrying read results in per-result slices instead of a shared buffer. Repo-wide `go test ./... -race` went from 7 races / 5 failing tests to all-clean.
**v1.0.3** — Kernel stage-coordinator double-unlock fix. The production `homed` main process once died outright with `fatal error: sync: unlock of unlocked mutex`, taking all 27 subprocess plugins with it: `Host.endStage` performed "decrement inflight, decide whether I'm the last leaver" *outside* the `coordMu` critical section while detaching the coordinator *inside* it, so a late-arriving plugin could attach to a coordinator that was already finishing, be misjudged as the last leaver, and unlock the same `stageMu` twice. **A `sync.Mutex` double unlock is a runtime fatal, not a panic, so the two layers of `recover` structurally cannot catch it**—which is exactly why the "a crashing plugin must not take down the kernel" isolation design failed wholesale here. The fix folds counting, decision, and detach into one critical section, and also moves the first arriver's `enter()` (which writes the shared segment) inside the lock—previously a late arriver could read a half-written segment. Ships with 5 regression cases, including a reverse check that stashes the old implementation back to confirm the tests really do reproduce the fatal. **v1.0.3** — Kernel stage-coordinator double-unlock fix. The production `homed` main process once died outright with `fatal error: sync: unlock of unlocked mutex`, taking all 27 subprocess plugins with it: `Host.endStage` performed "decrement inflight, decide whether I'm the last leaver" *outside* the `coordMu` critical section while detaching the coordinator *inside* it, so a late-arriving plugin could attach to a coordinator that was already finishing, be misjudged as the last leaver, and unlock the same `stageMu` twice. **A `sync.Mutex` double unlock is a runtime fatal, not a panic, so the two layers of `recover` structurally cannot catch it**—which is exactly why the "a crashing plugin must not take down the kernel" isolation design failed wholesale here. The fix folds counting, decision, and detach into one critical section, and also moves the first arriver's `enter()` (which writes the shared segment) inside the lock—previously a late arriver could read a half-written segment. Ships with 5 regression cases, including a reverse check that stashes the old implementation back to confirm the tests really do reproduce the fatal.
**v1.0.1** — Multimodal bugfix. The plugin ABI/protocol is unchanged, so `plugin.bin` artifacts built for 1.0.0 need no rebuild. Three defects fixed: (1) **vision silently failing**—media blocks attached to a tool message are not treated as viewable content by the model (measured on one image: 0/3 read from a tool message, 3/3 from a standalone user message); media now rides its own user message placed immediately after, which is what the plugin's own wording ("injected into the following conversation") always claimed; (2) **new multimodal capability declaration + fallback chain**`core.llm.sources.<name>.vision/.audio` declares whether a source can genuinely process media (a gateway may strip `image_url` and still return 200, with identical prompt_tokens with and without the image); when it cannot, media is transcribed to text via a vision-capable source, finally wiring up the long-registered but never-read `core.input_processing.image.fallback_provider` settings; (3) **`see_video` frame-count semantics were inverted**—`fps=1/N` is a *rate*, not a count, so a 20s video yielded 2 frames when 10 were requested and 20 frames when 1 was requested; now `ffprobe` measures duration and the filter becomes `fps=N/duration` with `-frames:v` as a hard cap. **v1.0.1** — Multimodal bugfix. The plugin ABI/protocol is unchanged, so `plugin.bin` artifacts built for 1.0.0 need no rebuild. Three defects fixed: (1) **vision silently failing**—media blocks attached to a tool message are not treated as viewable content by the model (measured on one image: 0/3 read from a tool message, 3/3 from a standalone user message); media now rides its own user message placed immediately after, which is what the plugin's own wording ("injected into the following conversation") always claimed; (2) **new multimodal capability declaration + fallback chain**`core.llm.sources.<name>.vision/.audio` declares whether a source can genuinely process media (a gateway may strip `image_url` and still return 200, with identical prompt_tokens with and without the image); when it cannot, media is transcribed to text via a vision-capable source, finally wiring up the long-registered but never-read `core.input_processing.image.fallback_provider` settings; (3) **`see_video` frame-count semantics were inverted**—`fps=1/N` is a *rate*, not a count, so a 20s video yielded 2 frames when 10 were requested and 20 frames when 1 was requested; now `ffprobe` measures duration and the filter becomes `fps=N/duration` with `-frames:v` as a hard cap.
@ -208,7 +210,7 @@ External plugin development: see [homeagent-sdk](https://gitcode.com/JianFeeeee/
| **client** | waiter + desktop GUI | Connecting to a remote HomeAgent | | **client** | waiter + desktop GUI | Connecting to a remote HomeAgent |
- Linux: `.deb` (amd64/arm64), `.rpm` (x86_64), `.tar.gz` - Linux: `.deb` (amd64/arm64), `.rpm` (x86_64), `.tar.gz`
- Windows: `HomeAgent_v1.0.3_{Full,Server,Client}_win64.exe` (NSIS installer) - Windows: `HomeAgent_v1.0.4_{Full,Server,Client}_win64.exe` (NSIS installer)
- Portable: `homeagent-bin-<os>_<arch>.tar.gz` (homed/waiter/initconfig) - Portable: `homeagent-bin-<os>_<arch>.tar.gz` (homed/waiter/initconfig)
- Verification: `SHA256SUMS` - Verification: `SHA256SUMS`

View File

@ -153,6 +153,14 @@ build_initconfig() {
} }
# ---- gui (Electron) ---- # ---- gui (Electron) ----
#
# 输出目录必须用 --config.directories.output**不能用 -o**
# electron-builder 的 `-o` 是 `--mac`/`--macos` 的短别名(见 --help 的 Building 段),
# 不是 output。此前 `-o "$BUILD_DIR"` 被当成 macOS 的 target 列表,报
# Unknown target: /home/program/trueagent/build
# (路径被 lowercase 后去匹配 target 名表,所以错误信息里的路径是全小写的,
# 这也是它看起来像「路径错」而实际是「参数位置错」的原因)。
# v1.0.1 与 v1.0.3 两次发布都因此手工组装过 GUI。
build_gui() { build_gui() {
if [ -n "${GOOS:-}" ] && [ "$GOOS" != "$("$GO" env GOOS)" ]; then if [ -n "${GOOS:-}" ] && [ "$GOOS" != "$("$GO" env GOOS)" ]; then
echo "[SKIP] gui ${GOOS}/${GOARCH} — electron-builder handles cross-platform natively; run 'all' on CI host" echo "[SKIP] gui ${GOOS}/${GOARCH} — electron-builder handles cross-platform natively; run 'all' on CI host"
@ -170,12 +178,21 @@ build_gui() {
# 不传 --configelectron-builder 默认从 package.json 的 "build" 键读配置。 # 不传 --configelectron-builder 默认从 package.json 的 "build" 键读配置。
# 传 --config package.json 会让它把**整个** package.json 当配置校验, # 传 --config package.json 会让它把**整个** package.json 当配置校验,
# 于是 devDependencies / build / scripts 全被判为 "unknown property" 而失败。 # 于是 devDependencies / build / scripts 全被判为 "unknown property" 而失败。
(cd "$gui_dir" && npx electron-builder \ #
--linux --win --mac \ # GUI 失败不中断整体构建homed/waiter/initconfig 是发布的主体,
--x64 --arm64 \ # 而 GUI 依赖 electron 运行时下载离线机器、arm64 缺缓存都会失败)。
-p never \ # set -e 下若不接住,一个可选组件会让整轮跨平台构建全废。
-o "$BUILD_DIR") if (cd "$gui_dir" && npx electron-builder \
echo " OK" --linux --win --mac \
--x64 --arm64 \
-p never \
--config.directories.output="$BUILD_DIR"); then
echo " OK"
else
echo " WARN: gui 构建失败(可选组件,不影响 homed/waiter/initconfig"
echo " Linux 包可用 deploy/packaging/package-linux.sh 内置的手工组装路径"
return 0
fi
} }
# ---- dispatch ---- # ---- dispatch ----

View File

@ -14,7 +14,7 @@
# 此前硬编码 0.8.0 而 release 已到 1.0.0,装出来的包在「添加/删除程序」里 # 此前硬编码 0.8.0 而 release 已到 1.0.0,装出来的包在「添加/删除程序」里
# 会显示错误版本DisplayVersion 也取自这个宏)。 # 会显示错误版本DisplayVersion 也取自这个宏)。
!ifndef PRODUCT_VERSION !ifndef PRODUCT_VERSION
!define PRODUCT_VERSION "1.0.3" !define PRODUCT_VERSION "1.0.4"
!endif !endif
!if "${VARIANT}" == "full" !if "${VARIANT}" == "full"

View File

@ -9,14 +9,20 @@ PACKAGE_ROOT="${PROJECT_ROOT}/deploy/packaging/linux"
GO="${GO:-$(command -v go 2>/dev/null || echo "go")}" GO="${GO:-$(command -v go 2>/dev/null || echo "go")}"
ARCH="${1:-amd64}" # amd64 or arm64 ARCH="${1:-amd64}" # amd64 or arm64
# electron 官方发布物用 x64/arm64 命名,而 Debian 用 amd64/arm64。
# 两者在 arm64 上恰好同名amd64 上不同——此前缓存查找统一用 TAR_ARCH
# amd64于是 electron-v*-linux-x64.zip 永远命中不到amd64 GUI 只能
# 靠"回退到 host node_modules"这条路组装。干净 worktree 里没有完整
# node_modulesGUI 就被静默跳过。故单独映射。
ACTION="${2:-all}" # all, build, deb, tar, rpm ACTION="${2:-all}" # all, build, deb, tar, rpm
DEB_ARCH="$ARCH" DEB_ARCH="$ARCH"
RPM_ARCH="$ARCH" RPM_ARCH="$ARCH"
TAR_ARCH="$ARCH" TAR_ARCH="$ARCH"
case "$ARCH" in case "$ARCH" in
amd64) DEB_ARCH="amd64"; RPM_ARCH="x86_64"; TAR_ARCH="amd64" ;; amd64) DEB_ARCH="amd64"; RPM_ARCH="x86_64"; TAR_ARCH="amd64"; ELECTRON_ARCH="x64" ;;
arm64) DEB_ARCH="arm64"; RPM_ARCH="aarch64"; TAR_ARCH="arm64" ;; arm64) DEB_ARCH="arm64"; RPM_ARCH="aarch64"; TAR_ARCH="arm64"; ELECTRON_ARCH="arm64" ;;
*) echo "Unknown arch: $ARCH (use amd64 or arm64)"; exit 1 ;; *) echo "Unknown arch: $ARCH (use amd64 or arm64)"; exit 1 ;;
esac esac
@ -122,6 +128,15 @@ build_go() {
} }
# ---- build GUI (manual directory assembly, avoids electron-packager network issues) ---- # ---- build GUI (manual directory assembly, avoids electron-packager network issues) ----
#
# electron 运行时必须按**目标架构**取,不能用 host 的
# node_modules/electron/dist——那里永远是 host 架构(本机 x64
# v1.0.0 / v1.0.1 的 arm64 full/client 包都踩了这个坑:目录名带
# -arm64、homed/waiter 确实是 aarch64但里面的 electron 是 x86-64
# 在 arm64 机器上一启动就是 Exec format error从未被交叉验证过
#
# 现在改为优先从 electron 缓存里取对应架构的 zip并在最后做
# 一道强制校验:架构不符就删掉目录并跳过 GUI宁可不发也不发坏包。
build_gui() { build_gui() {
local gui_dir="$PROJECT_ROOT/cmd/gui" local gui_dir="$PROJECT_ROOT/cmd/gui"
local gui_out="$BUILD_DIR/homeagent-gui-linux-${TAR_ARCH}" local gui_out="$BUILD_DIR/homeagent-gui-linux-${TAR_ARCH}"
@ -133,22 +148,81 @@ build_gui() {
echo ">>> Building GUI directory for linux/$ARCH..." echo ">>> Building GUI directory for linux/$ARCH..."
if [ ! -d "$gui_dir/node_modules" ]; then # 判据是 electron 包本身在不在,而不是 node_modules 目录在不在。
#
# npm install 失败(离线、网络受限)会留下一个只有一两个条目的空壳
# node_modules目录存在但 electron 缺失。只看目录会以为"已安装"
# 于是 ever 读不到版本、缓存匹配退化、最后走到"host dist 也没有"而
# 静默跳过 GUI——包名和目录名全都正确只是没有 GUI没有任何一步报错。
if [ ! -f "$gui_dir/node_modules/electron/package.json" ]; then
if [ -d "$gui_dir/node_modules" ]; then
echo " node_modules 存在但 electron 缺失(疑似上次 npm install 未完成)"
fi
echo " npm install..." echo " npm install..."
(cd "$gui_dir" && npm install --production) if ! (cd "$gui_dir" && npm install --production); then
echo " WARNING: npm install 失败——离线环境下这是预期的。"
echo " GUI 需要 cmd/gui/node_modules/electron 或 ~/.cache/electron 缓存。"
fi
fi fi
local electron_dir="$gui_dir/node_modules/electron/dist" # electron 版本优先从已安装的包里读,保证运行时与 app 依赖一致。
if [ ! -f "$electron_dir/electron" ]; then # 读不到时退而从 package.json 的依赖声明里取数字部分(它可能写成
echo " WARNING: electron binary not found at $electron_dir. GUI will be skipped." # "^33.0.0" 这类范围,只用于给缓存匹配一个提示,匹配不上仍会走通配)。
return local ever
ever=$(python3 -c "import json;print(json.load(open('$gui_dir/node_modules/electron/package.json'))['version'])" 2>/dev/null || true)
if [ -z "$ever" ]; then
ever=$(python3 -c "
import json, re
d = json.load(open('$gui_dir/package.json'))
spec = (d.get('devDependencies', {}) or {}).get('electron') or (d.get('dependencies', {}) or {}).get('electron') or ''
m = re.search(r'(\\d+(?:\\.\\d+)*)', spec)
print(m.group(1) if m else '')
" 2>/dev/null || true)
[ -n "$ever" ] && echo " electron 版本取自 package.json 依赖声明: $ever(非精确)"
fi
mkdir -p "$gui_out"
# 优先:缓存里的目标架构 zip~/.cache/electron/<hash>/electron-v<ver>-linux-<arch>.zip
local zip=""
if [ -n "$ever" ]; then
zip=$(find "$HOME/.cache/electron" -name "electron-v${ever}-linux-${ELECTRON_ARCH}.zip" 2>/dev/null | head -1)
fi
if [ -z "$zip" ]; then
zip=$(find "$HOME/.cache/electron" -name "electron-v*-linux-${ELECTRON_ARCH}.zip" 2>/dev/null | head -1)
fi
if [ -n "$zip" ]; then
echo " electron runtime: $(basename "$zip")"
unzip -q -o "$zip" -d "$gui_out"
else
# 回退:仅当目标架构 == host 架构时才能用 host 的 dist
local host_arch
case "$(uname -m)" in
x86_64) host_arch=amd64 ;;
aarch64|arm64) host_arch=arm64 ;;
*) host_arch=unknown ;;
esac
if [ "$TAR_ARCH" != "$host_arch" ]; then
echo " WARNING: 缺 electron-v*-linux-${ELECTRON_ARCH}.zip 缓存,且目标架构与 host"
echo " ($host_arch) 不同——不能用 host 的 electron 冒充。跳过 GUI。"
echo " 解法:下载 electron-v${ever:-<ver>}-linux-${ELECTRON_ARCH}.zip 到"
echo " ~/.cache/electron/<任意子目录>/ 后重跑。"
rm -rf "$gui_out"
return
fi
local electron_dir="$gui_dir/node_modules/electron/dist"
if [ ! -f "$electron_dir/electron" ]; then
echo " WARNING: electron binary not found at $electron_dir. GUI will be skipped."
rm -rf "$gui_out"
return
fi
echo " electron runtime: host node_modules (同架构 $host_arch)"
cp -r "$electron_dir"/* "$gui_out/" 2>/dev/null
fi fi
mkdir -p "$gui_out/resources/app/node_modules" mkdir -p "$gui_out/resources/app/node_modules"
mkdir -p "$gui_out/resources/app/renderer" mkdir -p "$gui_out/resources/app/renderer"
# copy electron runtime (binary + shared libs)
cp -r "$electron_dir"/* "$gui_out/" 2>/dev/null
rm -f "$gui_out/resources/default_app.asar" 2>/dev/null rm -f "$gui_out/resources/default_app.asar" 2>/dev/null
# copy app source # copy app source
@ -190,7 +264,28 @@ LAUNCHER
chmod +x "$gui_out/homeagent-gui" chmod +x "$gui_out/homeagent-gui"
chmod +x "$gui_out/electron" chmod +x "$gui_out/electron"
echo " GUI built: $gui_out ($(du -sh "$gui_out" | cut -f1))" # 最后一道强制校验electron 二进制的实际架构必须匹配目标架构。
# 不做这步就会重现 v1.0.0/v1.0.1 的隐形坏包:包名、目录名、
# homed/waiter 全对,只有 electron 是错架构,直到用户在 arm64 机器上
# 双击才发现 Exec format error。
local want_pat
case "$TAR_ARCH" in
amd64) want_pat="x86-64" ;;
arm64) want_pat="aarch64" ;;
*) want_pat="" ;;
esac
if [ -n "$want_pat" ]; then
local got
got=$(file -b "$gui_out/electron" 2>/dev/null || echo "")
if ! printf '%s' "$got" | grep -q "$want_pat"; then
echo " ERROR: electron 架构不符——期望 $want_pat,实际: ${got%%,*}"
echo " 删除 GUI 目录并跳过(宁可不发,也不发装了跑不起来的包)。"
rm -rf "$gui_out"
return
fi
fi
echo " GUI built: $gui_out ($(du -sh "$gui_out" | cut -f1), $(file -b "$gui_out/electron" | cut -d, -f2 | tr -d ' '))"
echo "" echo ""
} }

View File

@ -13,7 +13,7 @@ var (
// //
// 1.0.1:多模态修复。仅内核与内置插件改动,插件 ABI/协议未变, // 1.0.1:多模态修复。仅内核与内置插件改动,插件 ABI/协议未变,
// 1.0.0 编出的 plugin.bin 无需重编。 // 1.0.0 编出的 plugin.bin 无需重编。
Version = "1.0.3" Version = "1.0.4"
// Commit 是构建时的 Git commit hash。 // Commit 是构建时的 Git commit hash。
Commit = "unknown" Commit = "unknown"

View File

@ -18,10 +18,10 @@ import (
) )
const ( const (
DefaultTimeout = 5 * time.Minute DefaultTimeout = 5 * time.Minute
ReadBufSize = 4096 ReadBufSize = 4096
MaxOutputBuffer = 128 * 1024 MaxOutputBuffer = 128 * 1024
DefaultNotifyBytes = 2048 // 积累 2KB 未读输出再通知 DefaultNotifyBytes = 2048 // 积累 2KB 未读输出再通知
DefaultNotifyInterval = 2 * time.Second // 同一终端两次通知的最小间隔(兜底) DefaultNotifyInterval = 2 * time.Second // 同一终端两次通知的最小间隔(兜底)
) )
@ -68,12 +68,12 @@ type TerminalSession struct {
done chan struct{} done chan struct{}
// 通知节流字段 // 通知节流字段
unreadBytes int // 最近一次通知后积累的未读字节数 unreadBytes int // 最近一次通知后积累的未读字节数
lastNotify time.Time // 最近一次通知时间 lastNotify time.Time // 最近一次通知时间
lastData time.Time // 最近一次读到的数据时间(用于判定输出停止) lastData time.Time // 最近一次读到的数据时间(用于判定输出停止)
lastFeedback time.Time // 最近一次定时反馈时间 lastFeedback time.Time // 最近一次定时反馈时间
backoff time.Duration // 输出风暴退避:持续高速输出时通知间隔翻倍 backoff time.Duration // 输出风暴退避:持续高速输出时通知间隔翻倍
watch terminalWatch // 该终端的提醒规则 watch terminalWatch // 该终端的提醒规则
// 实时画面推流terminal_output 事件) // 实时画面推流terminal_output 事件)
stream bytes.Buffer // 待推送的增量输出,由 readLoop 每 200ms flush 一次 stream bytes.Buffer // 待推送的增量输出,由 readLoop 每 200ms flush 一次
@ -226,7 +226,7 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
Description: "创建一个新的交互式终端会话。返回终端 ID后续通过此 ID 进行读写操作。适用于运行交互式程序如 vim、ssh、top、nano 等。" + Description: "创建一个新的交互式终端会话。返回终端 ID后续通过此 ID 进行读写操作。适用于运行交互式程序如 vim、ssh、top、nano 等。" +
"通知模式通过 notify 参数选择(默认 exitexit=仅命令执行结束后提醒一次interval=定时反馈(如 interval=30s 每 30 秒反馈一次状态摘要);" + "通知模式通过 notify 参数选择(默认 exitexit=仅命令执行结束后提醒一次interval=定时反馈(如 interval=30s 每 30 秒反馈一次状态摘要);" +
"buffer=未读输出积累到指定字节数后提醒(如 buffer=8192多个模式用逗号组合如 interval=30s,buffer=8192。终端默认 5 分钟后自动关闭,可通过 timeout 参数调整。", "buffer=未读输出积累到指定字节数后提醒(如 buffer=8192多个模式用逗号组合如 interval=30s,buffer=8192。终端默认 5 分钟后自动关闭,可通过 timeout 参数调整。",
NoMemory: true, NoMemory: true,
Parameters: map[string]interface{}{ Parameters: map[string]interface{}{
"type": "object", "type": "object",
"properties": map[string]interface{}{ "properties": map[string]interface{}{
@ -283,7 +283,7 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
}) })
s.RegisterTool("terminal_read", sdk.ToolDef{ s.RegisterTool("terminal_read", sdk.ToolDef{
Name: "terminal_read", Name: "terminal_read",
Description: "读取指定终端的输出。mode=new默认返回自上次读取以来的新输出并清空缓冲mode=now 返回终端当前显示的全部屏幕内容(不清空缓冲)。如需持续监控请多次调用。", Description: "读取指定终端的输出。mode=new默认返回自上次读取以来的新输出并清空缓冲mode=now 返回终端当前显示的全部屏幕内容(不清空缓冲)。如需持续监控请多次调用。",
NoMemory: true, NoMemory: true,
Parameters: map[string]interface{}{ Parameters: map[string]interface{}{
@ -759,11 +759,11 @@ func (p *Plugin) handleList() (interface{}, error) {
defer p.mu.Unlock() defer p.mu.Unlock()
type termInfo struct { type termInfo struct {
ID string `json:"id"` ID string `json:"id"`
Command string `json:"command"` Command string `json:"command"`
Uptime string `json:"uptime"` Uptime string `json:"uptime"`
ExpiresIn string `json:"expires_in"` ExpiresIn string `json:"expires_in"`
Running bool `json:"running"` Running bool `json:"running"`
} }
var terms []termInfo var terms []termInfo
@ -787,8 +787,8 @@ func (p *Plugin) handleList() (interface{}, error) {
} }
return map[string]interface{}{ return map[string]interface{}{
"status": "ok", "status": "ok",
"count": len(terms), "count": len(terms),
"terminals": terms, "terminals": terms,
}, nil }, nil
} }
@ -797,6 +797,9 @@ func (p *Plugin) readLoop(t *TerminalSession, s *sdk.PluginSDK) {
defer p.wg.Done() defer p.wg.Done()
defer close(t.done) defer close(t.done)
// reader 协程独享这个读缓冲:结果随 readResult 携带,
// readLoop 不再从其中做 copy见 reader 注释,那是对共享缓冲
// 的并发读写,-race 实测触发)。
buf := make([]byte, ReadBufSize) buf := make([]byte, ReadBufSize)
pollInterval := 200 * time.Millisecond pollInterval := 200 * time.Millisecond
@ -816,7 +819,7 @@ func (p *Plugin) readLoop(t *TerminalSession, s *sdk.PluginSDK) {
t.lastFeedback = now t.lastFeedback = now
t.mu.Unlock() t.mu.Unlock()
// 硬上限:未读输出积累达到该值也通知一次(防大输出静默丢失),频率极低 // 硬上限:未读输出积累达到该值也通知一次(防大输出静默丢失),频率极低
hardNotifyBytes := 64 * 1024 hardNotifyBytes := 64 * 1024
hardNotifyInterval := 10 * time.Second hardNotifyInterval := 10 * time.Second
// 输出停止判定:超过该时长无新数据则视为输出停止 // 输出停止判定:超过该时长无新数据则视为输出停止
@ -886,9 +889,7 @@ func (p *Plugin) readLoop(t *TerminalSession, s *sdk.PluginSDK) {
return return
} }
if r.n > 0 { if r.n > 0 {
data := make([]byte, r.n) t.appendOutput(r.data)
copy(data, buf[:r.n])
t.appendOutput(data)
// 缓冲阈值通知(仅当 agent 显式选择 buffer 模式,或未读积累达到硬上限)。 // 缓冲阈值通知(仅当 agent 显式选择 buffer 模式,或未读积累达到硬上限)。
// 默认模式(仅 exit 提醒)下不随输出流通知,杜绝通知风暴。 // 默认模式(仅 exit 提醒)下不随输出流通知,杜绝通知风暴。
@ -951,15 +952,28 @@ func previewTail(s string, n int) string {
} }
type readResult struct { type readResult struct {
n int n int
err error data []byte
err error
} }
// reader 从终端读取输出并通过 channel 交给 readLoop。
//
// 读到的数据**随结果一起传**而不是复用外层共享的 buf
// reader 是唯一写 buf 的 goroutinereadLoop 又常在 reader 尚未
// 写完下一段时就从 buf[:r.n] 做 copy——同一个 shared buf 被并发
// 读写就是 data race-race 实测触发)。改为每个结果自带切片后,
// 读与拷贝天然隔离,不再共享可变状态。
func (p *Plugin) reader(t *TerminalSession, buf []byte, ch chan<- readResult) { func (p *Plugin) reader(t *TerminalSession, buf []byte, ch chan<- readResult) {
for { for {
n, err := t.session.Read(buf) n, err := t.session.Read(buf)
var data []byte
if n > 0 {
data = make([]byte, n)
copy(data, buf[:n])
}
select { select {
case ch <- readResult{n, err}: case ch <- readResult{n, data, err}:
case <-t.stopCh: case <-t.stopCh:
return return
} }

View File

@ -213,27 +213,68 @@ func TestRealPlugin_CrashDoesNotKillKernel(t *testing.T) {
t.Fatal("editdoc 未加载") t.Fatal("editdoc 未加载")
} }
// 找插件子进程并 SIGKILL // 找插件子进程并 SIGKILL
pid := findPluginPID(t, "editdoc") //
// 必须拿 plgDir 限定范围:旧实现用全系统 pgrep -f plugin.bin 后
// 只比“路径含 editdoc”于是在跑着生产实例的机器上它会把
// /home/newqqagent/plugins/editdoc/plugin.bin 当成目标杀掉(实测 9 次,
// 全部落在有人跑 go test 的时段)。更糟的是此时本测试仍会通过:
// 它断言的是测试内核存活,而那个内核的插件压根没死——**它在测一件
// 没发生的事**,同时还把生产环境打坏了。
pid := findPluginPID(t, plgDir, "editdoc")
if pid == 0 { if pid == 0 {
t.Skip("未找到插件子进程(进程名匹配失败)") t.Skip("未找到本测试自己拉起的插件子进程")
} }
t.Logf("kill 插件进程 pid=%d", pid) t.Logf("kill 插件进程 pid=%d (exe 在 %s 下)", pid, plgDir)
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil { if err := syscall.Kill(pid, syscall.SIGKILL); err != nil {
t.Fatalf("kill: %v", err) t.Fatalf("kill: %v", err)
} }
// 内核必须存活并能继续工作 // 先确认目标进程真的死了。
time.Sleep(300 * time.Millisecond) //
// 这步不能省:旧版直接断言“内核存活”,而内核本来就活着——
// 即使 SIGKILL 发错了对象(杀了生产实例的插件)测试也会结束。
// 先验“目标真死”再验“内核未被连带”,两步都成立才能证明隔离生效。
deadline := time.Now().Add(3 * time.Second)
dead := false
for time.Now().Before(deadline) {
if syscall.Kill(pid, 0) != nil {
dead = true
break
}
time.Sleep(50 * time.Millisecond)
}
if !dead {
t.Fatalf("pid=%d 在 SIGKILL 后 3s 内未退出,崩溃隔离无从验证", pid)
}
// 内核(本测试进程)必须存活并能继续工作
if env.pluginReg.List() == nil { if env.pluginReg.List() == nil {
t.Fatal("内核在插件崩溃后不可用") t.Fatal("内核在插件崩溃后不可用")
} }
t.Logf("插件崩溃后内核存活,已加载插件数=%d", len(env.pluginReg.List())) t.Logf("插件进程已确认退出,内核存活,已加载插件数=%d", len(env.pluginReg.List()))
} }
// findPluginPID 按二进制路径找插件子进程 pid。 // findPluginPID 在**指定插件目录下**找插件子进程 pid。
func findPluginPID(t *testing.T, name string) int { //
// root 参数是硬约束,不是可选过滤器:本函数的唯一用途是给崩溃隔离
// 测试提供一个“可以安全 SIGKILL 的 pid”而安全的定义就是它必须属于
// 本测试自己的临时目录。不带这个约束就会误杀同机生产实例的插件。
//
// 匹配依据是 /proc/<pid>/exe 的真实路径必须以 root 为前缀。
// 用 exe 而不用 cmdlinecmdline 可被进程自行改写,而 exe 符链由内核维护。
// root 先过一道 EvalSymlinks/tmp 在部分发行版上是符链(如 macOS 的
// /tmp -> /private/tmp不归一化会让前缀比较永远不命中退化成静默 Skip。
func findPluginPID(t *testing.T, root, name string) int {
t.Helper() t.Helper()
if root == "" {
t.Fatal("findPluginPID: root 不得为空(防止误杀全系统同名插件)")
}
realRoot, err := filepath.EvalSymlinks(root)
if err != nil {
realRoot = root
}
out, err := exec.Command("pgrep", "-f", "plugin.bin").Output() out, err := exec.Command("pgrep", "-f", "plugin.bin").Output()
if err != nil { if err != nil {
return 0 return 0
@ -244,15 +285,18 @@ func findPluginPID(t *testing.T, name string) int {
if pid == 0 { if pid == 0 {
continue continue
} }
// 校验 cwd 或 cmdline 含插件名
exe, err := os.Readlink(fmt.Sprintf("/proc/%d/exe", pid)) exe, err := os.Readlink(fmt.Sprintf("/proc/%d/exe", pid))
if err == nil && strings.Contains(exe, name) { if err != nil {
return pid continue
} }
cwd, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", pid)) // 两道条件同时成立才算命中:在本测试的目录树内,且是目标插件
if err == nil && strings.Contains(cwd, name) { if !strings.HasPrefix(exe, realRoot+string(os.PathSeparator)) {
return pid continue
} }
if !strings.Contains(exe, name) {
continue
}
return pid
} }
return 0 return 0
} }

View File

@ -37,6 +37,24 @@ type DeviceMeta struct {
type wconn struct { type wconn struct {
deviceID string deviceID string
w *bufio.Writer w *bufio.Writer
// wmu 序列化对该连接 bufio.Writer 的所有写。
//
// 两个角色会并发写同一连接handleWS 主循环(读设备帧后的 hello_ack/
// bind_ack/pong 回写)与 PushJSON/PushDataagent→设备的下发路径可能
// 来自任意 goroutine。bufio.Writer 不是线程安全的,不加锁会在
// WriteByte/Flush 上产生 data race生产实测触发
wmu sync.Mutex
}
// lockWrite 对 wconn 加写锁并返回 writer调用方必须 defer unlockWrite。
// 单独写成方法而不是直接暴露字段,避免调用方绕过锁。
func (c *wconn) lockWrite() *bufio.Writer {
c.wmu.Lock()
return c.w
}
func (c *wconn) unlockWrite() {
c.wmu.Unlock()
} }
// Registry 是设备接入网关的注册表:管理在线连接、设备元数据。线程安全。 // Registry 是设备接入网关的注册表:管理在线连接、设备元数据。线程安全。
@ -319,7 +337,9 @@ func (r *Registry) PushJSON(deviceID string, payload map[string]interface{}) err
if !ok { if !ok {
return fmt.Errorf("device %s not online", deviceID) return fmt.Errorf("device %s not online", deviceID)
} }
return writeText(c.w, mustJSON(payload)) w := c.lockWrite()
defer c.unlockWrite()
return writeText(w, mustJSON(payload))
} }
// PushCmd 向设备发送命令执行请求。 // PushCmd 向设备发送命令执行请求。
@ -348,7 +368,11 @@ func (r *Registry) PushData(deviceID, reqID, kind, mime string, data []byte) err
if !ok { if !ok {
return fmt.Errorf("device %s not online", deviceID) return fmt.Errorf("device %s not online", deviceID)
} }
if err := writeText(c.w, mustJSON(map[string]interface{}{ // 整条下发start + N 个 chunk + end持锁设备侧按协议串行聚合
// 若中途被 handleWS 的 hello/pong 插帧会破坏协议顺序。
w := c.lockWrite()
defer c.unlockWrite()
if err := writeText(w, mustJSON(map[string]interface{}{
"op": "cmd_speech_start", "op": "cmd_speech_start",
"req_id": reqID, "req_id": reqID,
"kind": kind, "kind": kind,
@ -363,11 +387,11 @@ func (r *Registry) PushData(deviceID, reqID, kind, mime string, data []byte) err
if end > len(data) { if end > len(data) {
end = len(data) end = len(data)
} }
if err := writeBinary(c.w, data[off:end]); err != nil { if err := writeBinary(w, data[off:end]); err != nil {
return fmt.Errorf("push data chunk: %w", err) return fmt.Errorf("push data chunk: %w", err)
} }
} }
if err := writeText(c.w, mustJSON(map[string]interface{}{ if err := writeText(w, mustJSON(map[string]interface{}{
"op": "cmd_speech_end", "op": "cmd_speech_end",
"req_id": reqID, "req_id": reqID,
})); err != nil { })); err != nil {
@ -618,6 +642,26 @@ func (r *Registry) ServeWS(w http.ResponseWriter, req *http.Request) {
go r.handleWS(conn, rw) go r.handleWS(conn, rw)
} }
// wsWriteLocked 在指定设备连接的写锁保护下执行写回调。
//
// handleWS 主循环与 Push* 是两条并发写同一 bufio.Writer 的路径,
// 必须共用同一把锁。handleWS 里拿到的是 rw.Writer与 conns 存储的是
// 同一个对象),回写前必须经此函数取锁,否则跟 Push* 依然会撞。
//
// 注意设备已离线conns 中已删除)时直接报错——设备断开后仍尝试
// 回写没有意义,还可能在已关闭的 bufio 上写入。
func (r *Registry) wsWriteLocked(deviceID string, fn func(w *bufio.Writer) error) error {
r.mu.RLock()
c, ok := r.conns[deviceID]
r.mu.RUnlock()
if !ok {
return fmt.Errorf("device %s not online", deviceID)
}
w := c.lockWrite()
defer c.unlockWrite()
return fn(w)
}
func (r *Registry) handleWS(conn net.Conn, rw *bufio.ReadWriter) { func (r *Registry) handleWS(conn net.Conn, rw *bufio.ReadWriter) {
defer conn.Close() defer conn.Close()
var curID string var curID string
@ -635,7 +679,9 @@ func (r *Registry) handleWS(conn net.Conn, rw *bufio.ReadWriter) {
payload, isClose, opcode, err := readFrame(rw.Reader) payload, isClose, opcode, err := readFrame(rw.Reader)
if err != nil { if err != nil {
if err == errPing { if err == errPing {
if werr := writePong(rw.Writer); werr != nil { // pong 也走写锁:它可能在 Push* 持锁推送大块数据时到达。
err := r.wsWriteLocked(curID, writePong)
if err != nil {
return return
} }
continue continue
@ -679,11 +725,13 @@ func (r *Registry) handleWS(conn net.Conn, rw *bufio.ReadWriter) {
r.mu.Lock() r.mu.Lock()
r.conns[meta.DeviceID] = &wconn{deviceID: meta.DeviceID, w: rw.Writer} r.conns[meta.DeviceID] = &wconn{deviceID: meta.DeviceID, w: rw.Writer}
r.mu.Unlock() r.mu.Unlock()
if err := writeText(rw.Writer, mustJSON(map[string]interface{}{ if err := r.wsWriteLocked(meta.DeviceID, func(w *bufio.Writer) error {
"op": "hello_ack", return writeText(w, mustJSON(map[string]interface{}{
"device": meta.DeviceID, "op": "hello_ack",
"online": true, "device": meta.DeviceID,
})); err != nil { "online": true,
}))
}); err != nil {
return return
} }
case "bind": case "bind":
@ -694,11 +742,17 @@ func (r *Registry) handleWS(conn net.Conn, rw *bufio.ReadWriter) {
// 默认不授权bind 仅验证 token + 登记设备;授权完全由用户手动 // 默认不授权bind 仅验证 token + 登记设备;授权完全由用户手动
// GUI 设备页 / REST /api/v1/device/auth控制绝不自动授权。 // GUI 设备页 / REST /api/v1/device/auth控制绝不自动授权。
} }
if err := writeText(rw.Writer, mustJSON(map[string]interface{}{"op": "bind_ack", "ok": true})); err != nil { err := r.wsWriteLocked(curID, func(w *bufio.Writer) error {
return writeText(w, mustJSON(map[string]interface{}{"op": "bind_ack", "ok": true}))
})
if err != nil {
return return
} }
} else { } else {
if err := writeText(rw.Writer, mustJSON(map[string]interface{}{"op": "bind_ack", "ok": false, "error": "bad token"})); err != nil { err := r.wsWriteLocked(curID, func(w *bufio.Writer) error {
return writeText(w, mustJSON(map[string]interface{}{"op": "bind_ack", "ok": false, "error": "bad token"}))
})
if err != nil {
return return
} }
} }