fix: AIAgentService getContext(this) 改为外部传入,Index 添加 aboutToDisappear 释放 display 监听

- AIAgentService: 添加 appContext 字段,构造函数接收 Context 参数
- ChatPage: 创建 AIAgentService 时传入 getContext(this)
- Index: 添加 displayCallback 字段和 aboutToDisappear 释放监听
This commit is contained in:
root
2026-04-30 15:02:00 +08:00
parent b9a2cba2a7
commit ba44d50d7a
3 changed files with 14 additions and 3 deletions

View File

@ -15,7 +15,7 @@ export struct ChatPage {
async aboutToAppear() {
// 初始化图记忆服务和 Agent
const memoryService = new GraphMemoryService(this.db);
this.agentService = new AIAgentService(memoryService);
this.agentService = new AIAgentService(memoryService, getContext(this));
// 加载历史消息(兼容旧数据:无 session_id 时加载全部)
const rawHistory = await this.db.getChatHistory(50, this.agentService.getSessionId());

View File

@ -8,11 +8,18 @@ import { ImmersiveTabNavigation } from '../components/ImmersiveTabNavigation';
struct Index {
@State currentIndex: number = 0;
private db: GraphDatabase = new GraphDatabase();
private displayCallback?: (data: display.Display) => void;
aboutToAppear() {
this.db.init(getContext(this));
}
aboutToDisappear() {
if (this.displayCallback) {
display.off('change', this.displayCallback);
}
}
@Builder
tabContentBuilder() {
Column() {

View File

@ -6,6 +6,7 @@
*/
import http from '@ohos.net.http';
import dataPreferences from '@ohos.data.preferences';
import { Context } from '@ohos.app.ability.UIAbility';
import { GraphMemoryService, EntityInfo, RelationInfo, TaskInfo, MemoryRecallParams, MemoryCommitParams, MemoryPurgeParams, TimeRangeParams, PurgeCriteriaParams, NewRelationParams, PersonaUpdateParams, TaskCreateParams, TaskSetStateParams, TaskDeleteParams, TaskLinkInfoParams, TaskArchiveParams, TaskQueryParams, TripletInput, PersonaQueryResult, TaskQueryResult, MemoryRecallResult } from './GraphMemoryService';
export interface ChatMessage {
@ -382,8 +383,11 @@ export class AIAgentService {
private currentSessionId: string;
private turnCounter: number = 0;
constructor(memoryService: GraphMemoryService, sessionId?: string) {
private appContext: Context;
constructor(memoryService: GraphMemoryService, appContext: Context, sessionId?: string) {
this.memoryService = memoryService;
this.appContext = appContext;
this.currentSessionId = sessionId || `session-hm-${Date.now()}`;
}
@ -413,7 +417,7 @@ export class AIAgentService {
const taskResult = await this.memoryService.memoryRecall(recallParams);
// === 读取 API 配置 ===
const context = getContext(this);
const context = this.appContext;
const pref = await dataPreferences.getPreferences(context, 'trulymem_config');
const baseUrl: string = String(await pref.get('base_url', 'https://api.deepseek.com'));
const model: string = String(await pref.get('model', 'deepseek-chat'));