mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-09-21 09:28:14 +00:00
记忆系统在 1.1.0 支持了二进制多媒体节点,但那条链路只对**内核自己**开放: 用户在 qq 发图能落进 CAS、能被记忆引用,而插件调 Commit / DocMemory().Insert 交进来的媒体一律无处安放。原因是三层都断着,且**每一层都不报错**。 ## 一、公开 SDK:补上媒体的表达能力(全部新增,无签名变更) - `Triple` += `SentenceText`、`MediaDigests` - `Doc` += `MediaDigests`、`Attachments`;新增 `MediaAttachment` - `TextEvent` += `Attachments` - `DocMemoryAPI` += `InsertWithMedia` - `IOInjector` += `InjectInputMedia` / `InjectInputMediaSync` / `InjectInterruptMedia` - `PluginSDK` 补上一直缺失的 `SetToolBlocks` 包装(接口里有、便捷方法里没有) `MediaAttachment` 一个类型服务两个方向:给 `Data`+`MIME` 是新内容(CAS 按字节 去重),只给 `Digest` 是引用已有内容。读路径**只回元数据不回字节**——一次检索 可能命中几十份媒体,全塞回去会把跨进程消息撑爆。 媒体注入不能搭 `SetToolBlocks` 的车:那个方法只在工具处理函数内部可用,且媒体 要等下一条 tool message 才到模型手上。插件主动发起一轮带媒体的对话、以及中断 注入,需要自己的签名,且媒体在**本轮**就送到模型。 ## 二、内核桥接层:原先在静默裁字段 `internal/sdk/memory_impl.go` 此前只搬自己认识的几个字段,其余丢弃且返回 nil: - 图记忆丢 `Confidence`/`SubjectType`/`ObjectType`/`SentenceText`,又走 `Commit` 而非 `CommitWithMedia`(不回 sentenceIDs)→ 媒体绑定链 `SentenceText → sentences → sentence_id → media_refs` 一步都走不通,插件即便按格式写好标记也永远挂不上; - 知识库 `Query` 只回 ID/Title/Content,`Insert` 只写这三个;`Remove` 不解引用, 于是那些媒体永久处于「被引用」状态,GC 收不掉、磁盘只增不减 (内核的归档路径 `releaseDocMedia` 做了这一步,插件路径漏了同一步)。 规则改为:**内部结构有的字段一律透传**。标记格式处理作为包级私有辅助留在桥接 层自己手里,但必须与内核 `mediaSummaryForEvent` 字节兼容——两边要能互读对方 写下的标记。 标记插入必须在 `ds.Insert` **之前**(向量索引取 `Summary + " " + Content`, 之后补的标记检索不到),引用绑定必须在**之后**(owner_id 是 Insert 生成的 ID)。 ## 三、跨进程链路:不接线就是全体外部插件编译失败 `go test` 直接把这一层拍出来了——`procIO does not implement sdk.IOInjector`。 公开接口加方法后,生成模板不跟上,**每个外部插件都编不过**,是硬失败不是软降级。 六处接线:`protocol.go` 四个 method 常量、`capability.go` 能力归属、 `corehandler.go` 四个分派分支、`proc_core.go` 委托、`proc_main.go.tmpl` 模板侧 实现、以及三个测试替身。 ## 四、统一输入主干:把模态从「函数选择」降级为「字段」 `processTextInput` / `processMediaInput` 合并为 `processInput`。这个分叉是历史 产物而非设计:`processTextInput` 本来就处理媒体(`bindEventMedia` + `mediaSummaryForEvent`,与媒体路径尾部完全相同),`process()` 只看 `stageCtx.Extra["media_blocks"]`、根本不认识 `evt.Type`。模态是输入的**属性**, 不是输入的**种类**。 媒体路径由此获得它一直缺的六项:去重、`no_memory`、通道 `Cleaner`、中断语义、 `_consolidation_` 路由、正确的 `EventRawInput`。 最后一项是个真 bug:媒体路径发布 `"content": evt.Payload`(一个 map),而 `webui/handler.go` 断言 `.(string)` → 断言失败、`content == ""`、提前返回。 **用户发的图从来没出现在 WebUI 聊天记录里。** `media_blocks` 同时接受 `[]agentAPI.ContentBlock` 与 `[]pubsdk.ContentBlock`: 字段一致但 Go 不自动转换,只认一种的后果是另一种被静默丢弃。 ## 五、模型可调用的三个工具 `memory_commit` 的 `sentence_text` **从未暴露给模型**,而它是绑定链上的必经环节; 连同 `media_digests` 一起补进 JSON schema 与工具文档。`doc_commit` 加 `media_digests`。`doc_query` 把关联媒体单独一行附在结果末尾(正文按 2000 字截断, 标记通常就在尾部)。 标记由**内核**生成而非插件/模型拼装:要求调用方知道格式,等于让一个拼写错误 静默切断引用绑定,而全链路无人报错。 ## 六、WebUI 上传走真实媒体链路 图片/音频读回字节拼 data URL 注入 `media_blocks`(8MB 上限,超限退回按路径处理)。 此前只注入一句「文件已保存到 <路径>」,指望模型自己调 `files_read`——但那返回 文本,图片字节对模型永远不可见。附件类型识别扩展到 audio 并在缺 Content-Type 时按扩展名兜底(判错不只是卡片样式问题,图片被当普通文件就进不了视觉链路)。 ## 测试 - `internal/sdk/memory_impl_test.go`(12 例,此前该包**没有任何测试文件**) - `internal/agent/core/inputunify_test.go`(统一主干 + 双静态类型 + 三工具媒体) - `third_party/homeagent-sdk/sdk/stress_test.go`(13 例并发压测) 压测抓到两处**真**竞态(不是理论风险):`PluginSDK` 的 API 字段与 `autoRestart` 无锁,而写方(内核注入 API、插件 `SetAutoRestart`)与读方(插件后台 goroutine 注入、内核 registry 读 `AutoRestart`)天然跨 goroutine。加 `apiMu` 修掉;约定 只在持锁期间取字段值,取完即释放再调用——持锁调用会把 `InjectInputSync` 这类 阻塞到 agent 回复(可达数分钟)的方法与 `SetIOInjector` 串起来,让插件重载卡死。 测试还抓出两个自身缺陷:`bindDocMedia` 把同一份媒体数两次(`AddRef` 幂等所以表 是对的,但日志说「绑定 2 个」而实际 1 条——误导后续排查),以及用单字符实体名 时 `validEntityName` 静默跳过、`Commit` 返回 nil 却什么都没写。 存量插件不需要改一行也不需要重编:新增方法由插件调用、内核实现,不调就不受影响。 17 个 example 插件源码零改动通过类型检查。
668 lines
15 KiB
Go
668 lines
15 KiB
Go
//go:build linux || windows
|
||
|
||
package agentcli
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"strings"
|
||
"sync"
|
||
"testing"
|
||
"time"
|
||
|
||
sdk "gitcode.com/JianFeeeee/HomeAgent/internal/sdk"
|
||
sdkpub "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||
)
|
||
|
||
type toolCapture struct {
|
||
handlers map[string]sdk.ToolHandler
|
||
defs map[string]sdk.ToolDef
|
||
}
|
||
|
||
func newToolCapture() *toolCapture {
|
||
return &toolCapture{
|
||
handlers: make(map[string]sdk.ToolHandler),
|
||
defs: make(map[string]sdk.ToolDef),
|
||
}
|
||
}
|
||
|
||
func (tc *toolCapture) RegisterTool(name string, def sdk.ToolDef, handler sdk.ToolHandler) error {
|
||
tc.handlers[name] = handler
|
||
tc.defs[name] = def
|
||
return nil
|
||
}
|
||
func (tc *toolCapture) RegisterStage(stage sdk.Stage, handler sdk.StageHandler) {}
|
||
func (tc *toolCapture) RegisterAPI(name string) error { return nil }
|
||
|
||
func setupPlugin() (*Plugin, *toolCapture, error) {
|
||
p := New("agentcli")
|
||
tc := newToolCapture()
|
||
sdk := sdk.New("agentcli", sdk.SDKConfig{
|
||
RegTool: tc.RegisterTool,
|
||
RegStage: tc.RegisterStage,
|
||
RegAPI: tc.RegisterAPI,
|
||
Settings: sdk.NewSettings("agentcli", nil),
|
||
})
|
||
if err := p.Start(sdk); err != nil {
|
||
return nil, nil, err
|
||
}
|
||
return p, tc, nil
|
||
}
|
||
|
||
func TestKeyMapping(t *testing.T) {
|
||
tests := []struct {
|
||
key string
|
||
expected []byte
|
||
}{
|
||
{"enter", []byte{0x0D}},
|
||
{"tab", []byte{0x09}},
|
||
{"escape", []byte{0x1B}},
|
||
{"esc", []byte{0x1B}},
|
||
{"backspace", []byte{0x7F}},
|
||
{"delete", []byte{0x1B, 0x5B, 0x33, 0x7E}},
|
||
{"home", []byte{0x1B, 0x5B, 0x48}},
|
||
{"end", []byte{0x1B, 0x5B, 0x46}},
|
||
{"up", []byte{0x1B, 0x5B, 0x41}},
|
||
{"down", []byte{0x1B, 0x5B, 0x42}},
|
||
{"left", []byte{0x1B, 0x5B, 0x44}},
|
||
{"right", []byte{0x1B, 0x5B, 0x43}},
|
||
{"page_up", []byte{0x1B, 0x5B, 0x35, 0x7E}},
|
||
{"page_down", []byte{0x1B, 0x5B, 0x36, 0x7E}},
|
||
{"ctrl_a", []byte{0x01}},
|
||
{"ctrl_z", []byte{0x1A}},
|
||
{"alt_a", []byte{0x1B, 'a'}},
|
||
{"alt_z", []byte{0x1B, 'z'}},
|
||
{"f1", []byte{0x1B, 0x5B, 0x50}},
|
||
{"f4", []byte{0x1B, 0x5B, 0x53}},
|
||
{"f12", []byte{0x1B, 0x5B, 0x32, 0x34, 0x7E}},
|
||
}
|
||
|
||
for _, tt := range tests {
|
||
t.Run(tt.key, func(t *testing.T) {
|
||
result, err := mapKey(tt.key)
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
if !bytesEqual(result, tt.expected) {
|
||
t.Fatalf("expected %v, got %v", tt.expected, result)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestKeyMappingInvalid(t *testing.T) {
|
||
_, err := mapKey("unknown_key")
|
||
if err == nil {
|
||
t.Fatal("expected error for unknown key")
|
||
}
|
||
}
|
||
|
||
func bytesEqual(a, b []byte) bool {
|
||
if len(a) != len(b) {
|
||
return false
|
||
}
|
||
for i := range a {
|
||
if a[i] != b[i] {
|
||
return false
|
||
}
|
||
}
|
||
return true
|
||
}
|
||
|
||
func TestListEmpty(t *testing.T) {
|
||
p, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer p.Stop()
|
||
|
||
handler := tc.handlers["terminal_list"]
|
||
result, err := handler(map[string]interface{}{})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ := json.Marshal(result)
|
||
var resp map[string]interface{}
|
||
json.Unmarshal(data, &resp)
|
||
|
||
if resp["status"] != "ok" {
|
||
t.Fatalf("expected status ok, got %v", resp["status"])
|
||
}
|
||
if resp["count"].(float64) != 0 {
|
||
t.Fatalf("expected count 0, got %v", resp["count"])
|
||
}
|
||
}
|
||
|
||
func TestCreateAndCloseTerminal(t *testing.T) {
|
||
p, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer p.Stop()
|
||
|
||
createHandler := tc.handlers["terminal_create"]
|
||
result, err := createHandler(map[string]interface{}{
|
||
"command": "echo hello",
|
||
"timeout": "10s",
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ := json.Marshal(result)
|
||
var createResp map[string]interface{}
|
||
json.Unmarshal(data, &createResp)
|
||
|
||
if v, ok := createResp["error"]; ok {
|
||
t.Skipf("PTY not available in this environment: %v", v)
|
||
}
|
||
if createResp["status"] != "created" {
|
||
t.Fatalf("expected status created, got %v", createResp["status"])
|
||
}
|
||
|
||
id := createResp["id"].(string)
|
||
if id == "" {
|
||
t.Fatal("expected non-empty terminal id")
|
||
}
|
||
|
||
// Give the terminal a moment to output
|
||
time.Sleep(200 * time.Millisecond)
|
||
|
||
// Read output
|
||
readHandler := tc.handlers["terminal_read"]
|
||
result, err = readHandler(map[string]interface{}{
|
||
"id": id,
|
||
"clear": true,
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ = json.Marshal(result)
|
||
var readResp map[string]interface{}
|
||
json.Unmarshal(data, &readResp)
|
||
if readResp["status"] != "ok" {
|
||
t.Fatalf("expected status ok, got %v", readResp["status"])
|
||
}
|
||
|
||
// Close
|
||
closeHandler := tc.handlers["terminal_close"]
|
||
result, err = closeHandler(map[string]interface{}{
|
||
"id": id,
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ = json.Marshal(result)
|
||
var closeResp map[string]interface{}
|
||
json.Unmarshal(data, &closeResp)
|
||
if closeResp["status"] != "closed" {
|
||
t.Fatalf("expected status closed, got %v", closeResp["status"])
|
||
}
|
||
}
|
||
|
||
func TestCreateTerminalMissingArgs(t *testing.T) {
|
||
p, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer p.Stop()
|
||
|
||
handler := tc.handlers["terminal_create"]
|
||
result, err := handler(map[string]interface{}{})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ := json.Marshal(result)
|
||
var resp map[string]interface{}
|
||
json.Unmarshal(data, &resp)
|
||
|
||
if v, ok := resp["error"]; ok {
|
||
t.Skipf("PTY not available in this environment: %v", v)
|
||
}
|
||
if resp["status"] != "created" {
|
||
t.Fatalf("expected status created, got %v", resp["status"])
|
||
}
|
||
id := resp["id"].(string)
|
||
p.handleClose(map[string]interface{}{"id": id})
|
||
}
|
||
|
||
func TestWriteToNonexistentTerminal(t *testing.T) {
|
||
_, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
handler := tc.handlers["terminal_write"]
|
||
result, err := handler(map[string]interface{}{
|
||
"id": "nonexistent",
|
||
"input": "test",
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ := json.Marshal(result)
|
||
var resp map[string]interface{}
|
||
json.Unmarshal(data, &resp)
|
||
|
||
if _, ok := resp["error"]; !ok {
|
||
t.Fatal("expected error for nonexistent terminal")
|
||
}
|
||
}
|
||
|
||
func TestReadNonexistentTerminal(t *testing.T) {
|
||
_, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
handler := tc.handlers["terminal_read"]
|
||
result, err := handler(map[string]interface{}{
|
||
"id": "nonexistent",
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ := json.Marshal(result)
|
||
var resp map[string]interface{}
|
||
json.Unmarshal(data, &resp)
|
||
|
||
if _, ok := resp["error"]; !ok {
|
||
t.Fatal("expected error for nonexistent terminal")
|
||
}
|
||
}
|
||
|
||
func TestResizeNonexistentTerminal(t *testing.T) {
|
||
_, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
handler := tc.handlers["terminal_resize"]
|
||
result, err := handler(map[string]interface{}{
|
||
"id": "nonexistent",
|
||
"rows": float64(40),
|
||
"cols": float64(120),
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ := json.Marshal(result)
|
||
var resp map[string]interface{}
|
||
json.Unmarshal(data, &resp)
|
||
|
||
if _, ok := resp["error"]; !ok {
|
||
t.Fatal("expected error for nonexistent terminal")
|
||
}
|
||
}
|
||
|
||
func TestCloseNonexistentTerminal(t *testing.T) {
|
||
_, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
handler := tc.handlers["terminal_close"]
|
||
result, err := handler(map[string]interface{}{
|
||
"id": "nonexistent",
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ := json.Marshal(result)
|
||
var resp map[string]interface{}
|
||
json.Unmarshal(data, &resp)
|
||
|
||
if _, ok := resp["error"]; !ok {
|
||
t.Fatal("expected error for nonexistent terminal")
|
||
}
|
||
}
|
||
|
||
func TestTerminalWriteRequiresId(t *testing.T) {
|
||
_, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
handler := tc.handlers["terminal_write"]
|
||
result, err := handler(map[string]interface{}{
|
||
"input": "test",
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ := json.Marshal(result)
|
||
var resp map[string]interface{}
|
||
json.Unmarshal(data, &resp)
|
||
|
||
if _, ok := resp["error"]; !ok {
|
||
t.Fatal("expected error when id is missing")
|
||
}
|
||
}
|
||
|
||
func TestTerminalWriteRequiresContent(t *testing.T) {
|
||
_, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
handler := tc.handlers["terminal_write"]
|
||
result, err := handler(map[string]interface{}{
|
||
"id": "test",
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
data, _ := json.Marshal(result)
|
||
var resp map[string]interface{}
|
||
json.Unmarshal(data, &resp)
|
||
|
||
if _, ok := resp["error"]; !ok {
|
||
t.Fatal("expected error when both input and key are missing")
|
||
}
|
||
}
|
||
|
||
func TestToolsRegistered(t *testing.T) {
|
||
p, tc, err := setupPlugin()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer p.Stop()
|
||
|
||
expectedTools := []string{
|
||
"terminal_create",
|
||
"terminal_write",
|
||
"terminal_read",
|
||
"terminal_resize",
|
||
"terminal_close",
|
||
"terminal_list",
|
||
}
|
||
|
||
for _, name := range expectedTools {
|
||
if _, ok := tc.handlers[name]; !ok {
|
||
t.Errorf("tool %s not registered", name)
|
||
}
|
||
}
|
||
}
|
||
|
||
// ——— Phase 6: 通知节流测试(mock 终端 + 捕获注入) ———
|
||
|
||
type injectCapture struct {
|
||
mu sync.Mutex
|
||
texts []string
|
||
}
|
||
|
||
func (c *injectCapture) InjectInterruptText(source, channel, text string) {
|
||
c.mu.Lock()
|
||
c.texts = append(c.texts, text)
|
||
c.mu.Unlock()
|
||
}
|
||
func (c *injectCapture) InjectText(source, channel, text string) {
|
||
c.mu.Lock()
|
||
c.texts = append(c.texts, text)
|
||
c.mu.Unlock()
|
||
}
|
||
func (c *injectCapture) InjectTextNoMemory(source, channel, text string) {
|
||
c.mu.Lock()
|
||
c.texts = append(c.texts, text)
|
||
c.mu.Unlock()
|
||
}
|
||
|
||
func (c *injectCapture) SetToolBlocks(blocks []sdkpub.ContentBlock) {
|
||
// 测试桩:忽略多模态块
|
||
}
|
||
func (c *injectCapture) InjectInputSync(source, channel, text string) string { return "" }
|
||
|
||
// 三个带媒体的注入方法同样记录文本:本测试只关心「注入了什么话」,
|
||
// 媒体块的转发在 core 的 injectedBlocks 测试里覆盖。
|
||
func (c *injectCapture) InjectInputMedia(source, channel, text string, blocks []sdkpub.ContentBlock) {
|
||
c.mu.Lock()
|
||
c.texts = append(c.texts, text)
|
||
c.mu.Unlock()
|
||
}
|
||
|
||
func (c *injectCapture) InjectInputMediaSync(source, channel, text string, blocks []sdkpub.ContentBlock) string {
|
||
return ""
|
||
}
|
||
|
||
func (c *injectCapture) InjectInterruptMedia(source, channel, text string, blocks []sdkpub.ContentBlock) {
|
||
c.mu.Lock()
|
||
c.texts = append(c.texts, text)
|
||
c.mu.Unlock()
|
||
}
|
||
|
||
func (c *injectCapture) snapshot() []string {
|
||
c.mu.Lock()
|
||
defer c.mu.Unlock()
|
||
out := make([]string, len(c.texts))
|
||
copy(out, c.texts)
|
||
return out
|
||
}
|
||
|
||
// mockTerm 可控输出流的假终端:Read 从 data chan 取数据,可模拟进程退出/读取错误
|
||
type mockTerm struct {
|
||
mu sync.Mutex
|
||
data chan []byte
|
||
running bool
|
||
err error
|
||
}
|
||
|
||
func newMockTerm() *mockTerm {
|
||
return &mockTerm{data: make(chan []byte, 16), running: true}
|
||
}
|
||
|
||
func (m *mockTerm) Read(buf []byte) (int, error) {
|
||
for {
|
||
m.mu.Lock()
|
||
err := m.err
|
||
running := m.running
|
||
m.mu.Unlock()
|
||
if err != nil {
|
||
return 0, err
|
||
}
|
||
if !running {
|
||
return 0, fmt.Errorf("process exited")
|
||
}
|
||
select {
|
||
case data, ok := <-m.data:
|
||
if !ok {
|
||
return 0, fmt.Errorf("closed")
|
||
}
|
||
n := copy(buf, data)
|
||
return n, nil
|
||
case <-time.After(20 * time.Millisecond):
|
||
}
|
||
}
|
||
}
|
||
|
||
func (m *mockTerm) WriteString(s string) (int, error) { return len(s), nil }
|
||
func (m *mockTerm) Resize(rows, cols uint16) error { return nil }
|
||
func (m *mockTerm) Running() bool {
|
||
m.mu.Lock()
|
||
defer m.mu.Unlock()
|
||
return m.running
|
||
}
|
||
func (m *mockTerm) Kill() error { return nil }
|
||
func (m *mockTerm) Close() error { return nil }
|
||
|
||
func (m *mockTerm) push(data []byte) {
|
||
m.data <- data
|
||
}
|
||
|
||
func (m *mockTerm) setRunning(v bool) {
|
||
m.mu.Lock()
|
||
m.running = v
|
||
m.mu.Unlock()
|
||
}
|
||
|
||
func (m *mockTerm) setErr(err error) {
|
||
m.mu.Lock()
|
||
m.err = err
|
||
m.mu.Unlock()
|
||
}
|
||
|
||
func newTestSession(term ptyTerm) *TerminalSession {
|
||
return &TerminalSession{
|
||
id: "t1",
|
||
session: term,
|
||
createdAt: time.Now(),
|
||
timeout: 10 * time.Minute,
|
||
stopCh: make(chan struct{}),
|
||
done: make(chan struct{}),
|
||
}
|
||
}
|
||
|
||
func startReadLoop(p *Plugin, s *sdk.PluginSDK, t *TerminalSession) {
|
||
p.wg.Add(1)
|
||
go p.readLoop(t, s)
|
||
}
|
||
|
||
func waitInjected(c *injectCapture, substr string, timeout time.Duration) bool {
|
||
deadline := time.Now().Add(timeout)
|
||
for time.Now().Before(deadline) {
|
||
for _, text := range c.snapshot() {
|
||
if strings.Contains(text, substr) {
|
||
return true
|
||
}
|
||
}
|
||
time.Sleep(20 * time.Millisecond)
|
||
}
|
||
return false
|
||
}
|
||
|
||
// Phase 6: 持续吐进度时,通知频率显著低于 500ms/条(节流生效)
|
||
func TestReadLoopNotifyThrottle(t *testing.T) {
|
||
p := New("agentcli")
|
||
p.notifyBytes = 2048
|
||
p.notifyInterval = 2 * time.Second
|
||
|
||
capture := &injectCapture{}
|
||
sdkInst := sdk.New("agentcli", sdk.SDKConfig{
|
||
RegTool: newToolCapture().RegisterTool,
|
||
RegStage: func(sdk.Stage, sdk.StageHandler) {},
|
||
RegAPI: func(string) error { return nil },
|
||
Settings: sdk.NewSettings("agentcli", nil),
|
||
})
|
||
sdkInst.SetIOInjector(capture)
|
||
|
||
term := newMockTerm()
|
||
ts := newTestSession(term)
|
||
startReadLoop(p, sdkInst, ts)
|
||
|
||
if !waitInjected(capture, "已启动", 2*time.Second) {
|
||
t.Fatal("expected startup notification")
|
||
}
|
||
|
||
// 持续以 100B/50ms(=2KB/s) 吐进度 3 秒
|
||
stop := make(chan struct{})
|
||
go func() {
|
||
ticker := time.NewTicker(50 * time.Millisecond)
|
||
defer ticker.Stop()
|
||
chunk := make([]byte, 100)
|
||
for i := range chunk {
|
||
chunk[i] = 'x'
|
||
}
|
||
for {
|
||
select {
|
||
case <-stop:
|
||
return
|
||
case <-ticker.C:
|
||
term.push(chunk)
|
||
}
|
||
}
|
||
}()
|
||
|
||
time.Sleep(3 * time.Second)
|
||
close(stop)
|
||
|
||
notifies := 0
|
||
for _, text := range capture.snapshot() {
|
||
if strings.Contains(text, "有新输出") {
|
||
notifies++
|
||
}
|
||
}
|
||
// 3 秒持续输出,500ms/条 的旧行为应有 6 条;节流后 ≤3 条
|
||
if notifies > 3 {
|
||
t.Errorf("notify throttle ineffective: %d notifies in 3s (expected <=3)", notifies)
|
||
}
|
||
if notifies == 0 {
|
||
t.Error("expected at least one output notification")
|
||
}
|
||
|
||
close(ts.stopCh)
|
||
<-ts.done
|
||
}
|
||
|
||
// Phase 6: 进程退出 → 立即通知(两条路径:PTY Read 返回 EOF 走"读取结束",
|
||
// 或 reader 阻塞时顶部 terminalRunning 检测走"进程已退出")
|
||
func TestReadLoopNotifyOnExit(t *testing.T) {
|
||
p := New("agentcli")
|
||
p.notifyBytes = 2048
|
||
p.notifyInterval = 2 * time.Second
|
||
|
||
capture := &injectCapture{}
|
||
sdkInst := sdk.New("agentcli", sdk.SDKConfig{
|
||
RegTool: newToolCapture().RegisterTool,
|
||
RegStage: func(sdk.Stage, sdk.StageHandler) {},
|
||
RegAPI: func(string) error { return nil },
|
||
Settings: sdk.NewSettings("agentcli", nil),
|
||
})
|
||
sdkInst.SetIOInjector(capture)
|
||
|
||
term := newMockTerm()
|
||
ts := newTestSession(term)
|
||
startReadLoop(p, sdkInst, ts)
|
||
|
||
if !waitInjected(capture, "已启动", 2*time.Second) {
|
||
t.Fatal("expected startup notification")
|
||
}
|
||
|
||
term.setRunning(false)
|
||
gotExit := waitInjected(capture, "进程已退出", 2*time.Second)
|
||
gotReadEnd := waitInjected(capture, "读取结束", time.Second)
|
||
if !gotExit && !gotReadEnd {
|
||
t.Error("expected immediate notification on process exit (either 进程已退出 or 读取结束)")
|
||
}
|
||
close(ts.stopCh)
|
||
}
|
||
|
||
// Phase 6: 读取错误/EOF → 立即通知
|
||
func TestReadLoopNotifyOnReadError(t *testing.T) {
|
||
p := New("agentcli")
|
||
p.notifyBytes = 2048
|
||
p.notifyInterval = 2 * time.Second
|
||
|
||
capture := &injectCapture{}
|
||
sdkInst := sdk.New("agentcli", sdk.SDKConfig{
|
||
RegTool: newToolCapture().RegisterTool,
|
||
RegStage: func(sdk.Stage, sdk.StageHandler) {},
|
||
RegAPI: func(string) error { return nil },
|
||
Settings: sdk.NewSettings("agentcli", nil),
|
||
})
|
||
sdkInst.SetIOInjector(capture)
|
||
|
||
term := newMockTerm()
|
||
ts := newTestSession(term)
|
||
startReadLoop(p, sdkInst, ts)
|
||
|
||
if !waitInjected(capture, "已启动", 2*time.Second) {
|
||
t.Fatal("expected startup notification")
|
||
}
|
||
|
||
term.setErr(fmt.Errorf("read timeout"))
|
||
if !waitInjected(capture, "读取结束", 3*time.Second) {
|
||
t.Error("expected immediate notification on read error")
|
||
}
|
||
close(ts.stopCh)
|
||
<-ts.done
|
||
}
|