feat: 后台思考可被前台消息中断 — 用户发消息时cancel运行中的思考

This commit is contained in:
2026-06-24 18:21:36 +08:00
parent fab934fb12
commit ebd6f40425
@@ -199,6 +199,7 @@ type Thinker struct {
lastUserMessage time.Time lastUserMessage time.Time
lastThinkTime time.Time lastThinkTime time.Time
lastProactiveMsgTime time.Time lastProactiveMsgTime time.Time
thinkCancel context.CancelFunc // 取消当前思考,让步于前台
// 思考计数器(用于周期性记忆维护,每 N 次思考触发一次) // 思考计数器(用于周期性记忆维护,每 N 次思考触发一次)
thinkCount int thinkCount int
@@ -417,6 +418,9 @@ func (t *Thinker) IsUserRecentlyActive(d time.Duration) bool {
return time.Since(t.lastUserMessage) < d return time.Since(t.lastUserMessage) < d
} }
// ThinkerConfig 后台思考配置 // ThinkerConfig 后台思考配置
type ThinkerConfig struct { type ThinkerConfig struct {
Enabled bool Enabled bool
@@ -528,6 +532,7 @@ func (t *Thinker) restoreContext() {
} }
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() defer cancel()
defer func() { t.mu.Lock(); t.thinkCancel = nil; t.mu.Unlock() }()
memories, err := t.memClient.Query(ctx, model.MemoryQuery{ memories, err := t.memClient.Query(ctx, model.MemoryQuery{
UserID: t.adminUserID, UserID: t.adminUserID,
@@ -631,6 +636,10 @@ func (t *Thinker) RecordUserMessage(sessionID string) {
// 用户主动发消息时重置主动消息推送冷却——活跃对话中应允许昔涟回复 // 用户主动发消息时重置主动消息推送冷却——活跃对话中应允许昔涟回复
t.lastProactiveMsgTime = time.Time{} t.lastProactiveMsgTime = time.Time{}
t.mu.Unlock() t.mu.Unlock()
if t.thinkCancel != nil {
t.thinkCancel()
t.thinkCancel = nil
}
// 重置静默检测定时器 // 重置静默检测定时器
t.resetSilenceTimer() t.resetSilenceTimer()
@@ -1070,6 +1079,20 @@ func (t *Thinker) performThink(triggerReason string) {
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel() defer cancel()
t.mu.Lock()
t.thinkCancel = cancel
t.mu.Unlock()
// 0. 让步于前台——如果用户最近有活动(非post_chat),跳过本次思考。
if triggerReason != "post_chat" {
t.mu.Lock()
sinceLastUser := time.Since(t.lastUserMessage)
t.mu.Unlock()
if sinceLastUser < 10*time.Second {
log.Printf("[后台思考] 用户 %v 前有活动,让步于前台回复,跳过思考", sinceLastUser.Round(time.Second))
return
}
}
log.Printf("[后台思考] 开始思考周期 (触发原因=%s, 计数=%d)...", triggerReason, currentCount) log.Printf("[后台思考] 开始思考周期 (触发原因=%s, 计数=%d)...", triggerReason, currentCount)