feat: 重启后恢复上下文 — 从记忆服务查询最近活动时间
- 新增 restoreContext() 在 Start() 时查询持久化记忆 - 取最近记忆的 CreatedAt 设为 lastUserMessage - 避免重启后思考出现"已经一天没说话了" Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -490,7 +490,7 @@ func NewThinker(
|
||||
adminNickname: adminNickname,
|
||||
memClient: memClient,
|
||||
pendingThoughts: make([]*PendingThought, 0),
|
||||
lastUserMessage: time.Now(),
|
||||
lastUserMessage: time.Now().Add(-5 * time.Minute), // overwritten by restoreContext
|
||||
stopCh: make(chan struct{}),
|
||||
chain: NewThinkChain(10),
|
||||
autoToolPolicy: DefaultAutonomousToolPolicy(),
|
||||
@@ -501,6 +501,37 @@ func NewThinker(
|
||||
}
|
||||
}
|
||||
|
||||
// restoreContext recovers the last user activity time from persistent storage.
|
||||
func (t *Thinker) restoreContext() {
|
||||
if t.memClient == nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
memories, err := t.memClient.Query(ctx, model.MemoryQuery{
|
||||
UserID: t.adminUserID,
|
||||
Limit: 5,
|
||||
})
|
||||
if err != nil || len(memories) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Find the most recent memory/activity timestamp.
|
||||
var latest time.Time
|
||||
for _, m := range memories {
|
||||
if m.CreatedAt.After(latest) {
|
||||
latest = m.CreatedAt
|
||||
}
|
||||
}
|
||||
if !latest.IsZero() {
|
||||
t.mu.Lock()
|
||||
t.lastUserMessage = latest
|
||||
t.mu.Unlock()
|
||||
log.Printf("[后台思考] 上下文已恢复: 最近活动 %v 前", time.Since(latest).Round(time.Second))
|
||||
}
|
||||
}
|
||||
|
||||
// Start 初始化后台思考器
|
||||
//
|
||||
// 双模式触发:
|
||||
@@ -512,6 +543,9 @@ func (t *Thinker) Start() {
|
||||
return
|
||||
}
|
||||
|
||||
// 恢复上下文:从持久化存储查询最近活动时间,避免重启后"失忆"
|
||||
t.restoreContext()
|
||||
|
||||
// 初始化静默检测定时器(但不启动,等第一次用户消息后启动)
|
||||
if t.silenceTimeout > 0 {
|
||||
t.silenceTimer = time.NewTimer(t.silenceTimeout)
|
||||
|
||||
Reference in New Issue
Block a user