processMessages 处理消息队列
(ctx context.Context)
| 19 | |
| 20 | // processMessages 处理消息队列 |
| 21 | func (a *Agent) processMessages(ctx context.Context) { |
| 22 | procLog.Info(ctx, "processMessages started", map[string]any{"agent_id": a.id}) |
| 23 | |
| 24 | a.mu.Lock() |
| 25 | if a.state != types.AgentStateReady { |
| 26 | procLog.Warn(ctx, "agent not ready, skipping", map[string]any{"agent_id": a.id, "state": a.state}) |
| 27 | a.mu.Unlock() |
| 28 | return // 已经在处理中 |
| 29 | } |
| 30 | a.state = types.AgentStateWorking |
| 31 | a.iterationCount = 0 // 重置迭代计数 |
| 32 | a.initialThinkingSent = false // 重置初始思考事件标志,允许新用户消息触发新的"任务规划" |
| 33 | initialMsgCount := len(a.messages) |
| 34 | procLog.Info(ctx, "agent state changed to working", map[string]any{"agent_id": a.id, "message_count": initialMsgCount}) |
| 35 | a.mu.Unlock() |
| 36 | |
| 37 | defer func() { |
| 38 | a.mu.Lock() |
| 39 | a.state = types.AgentStateReady |
| 40 | // 检查是否有新的用户消息需要处理 |
| 41 | // 只有当最后一条消息是用户消息时才需要重新处理 |
| 42 | // (避免 assistant 响应触发无限循环) |
| 43 | hasNewUserMessage := false |
| 44 | if len(a.messages) > initialMsgCount { |
| 45 | lastMsg := a.messages[len(a.messages)-1] |
| 46 | hasNewUserMessage = lastMsg.Role == types.MessageRoleUser |
| 47 | } |
| 48 | a.mu.Unlock() |
| 49 | |
| 50 | // 如果有新的用户消息,重新触发处理 |
| 51 | // 注意:使用新的 context,而不是可能已取消的旧 context |
| 52 | // 这样即使用户点击了"停止",新消息仍然可以被处理 |
| 53 | if hasNewUserMessage { |
| 54 | newCtx := context.Background() |
| 55 | go a.processMessages(newCtx) |
| 56 | } |
| 57 | }() |
| 58 | |
| 59 | // 发送状态变更事件 |
| 60 | a.eventBus.EmitMonitor(&types.MonitorStateChangedEvent{ |
| 61 | State: types.AgentStateWorking, |
| 62 | }) |
| 63 | |
| 64 | // 设置断点 |
| 65 | a.setBreakpoint(types.BreakpointPreModel) |
| 66 | |
| 67 | procLog.Info(ctx, "calling runModelStep", map[string]any{"agent_id": a.id}) |
| 68 | |
| 69 | // 调用模型 |
| 70 | if err := a.runModelStep(ctx); err != nil { |
| 71 | procLog.Error(ctx, "runModelStep failed", map[string]any{"agent_id": a.id, "error": err.Error()}) |
| 72 | a.eventBus.EmitMonitor(&types.MonitorErrorEvent{ |
| 73 | Severity: "error", |
| 74 | Phase: "model", |
| 75 | Message: err.Error(), |
| 76 | }) |
| 77 | } |
| 78 |
no test coverage detected