diff --git a/backend/ai-core/internal/background/thinker.go b/backend/ai-core/internal/background/thinker.go index 1c910e3..2ce7955 100644 --- a/backend/ai-core/internal/background/thinker.go +++ b/backend/ai-core/internal/background/thinker.go @@ -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)