fix chatmodel

This commit is contained in:
2025-09-10 16:43:46 +08:00
parent e4ee688dc8
commit 07bd9923fc
8 changed files with 244 additions and 503 deletions
+67 -112
View File
@@ -49,14 +49,14 @@ export interface IChatPanelCallback {
/**
* 聊天控制器类 (MVP中的Presenter) - 单例模式
*
*
* 负责处理聊天相关的业务逻辑协调,包括:
* - 协调Model和View之间的交互
* - 处理用户交互和业务逻辑
* - 管理AI服务调用
* - 处理情绪状态更新
* - 错误处理和状态管理
*
*
* @example
* ```typescript
* const controller = ChatController.Instance;
@@ -115,12 +115,14 @@ export class ChatController {
* 初始化聊天控制器
* @param roleId 角色ID
*/
public initialize(roleId: number): void {
public initialize(categoryId: string, roleId: number): void {
this.dialogManager = DialogManager.getInstance();
// 初始化或切换到指定角色
if (!this.chatModel.initializeRole(roleId)) {
const error = new Error(`Failed to initialize ChatModel with roleId: ${roleId}`);
if (!this.chatModel.initializeRole(categoryId, roleId)) {
const error = new Error(
`Failed to initialize ChatModel with roleId: ${roleId}`
);
this.handleError(error);
return;
}
@@ -128,13 +130,13 @@ export class ChatController {
// 设置当前聊天的角色ID到AI服务
if (roleId && roleId > 0) {
ChatAIService.Instance.setCurrentRole(roleId);
// 从ChatHistoryManager加载对话记录到ChatModel中
this.loadDialogsFromHistory(roleId);
// 同步到DialogManager
this.syncDialogData();
console.log(`ChatController initialized with role ${roleId}`);
} else {
const error = new Error(`Invalid roleId: ${roleId}`);
@@ -147,21 +149,21 @@ export class ChatController {
* @param roleId 角色ID
* @returns 是否切换成功
*/
public switchRole(roleId: number): boolean {
if (!this.chatModel.switchToRole(roleId)) {
public switchRole(categoryId: string, roleId: number): boolean {
if (!this.chatModel.switchToRole(categoryId, roleId)) {
console.error(`Failed to switch to role ${roleId}`);
return false;
}
// 更新AI服务的当前角色
ChatAIService.Instance.setCurrentRole(roleId);
// 从ChatHistoryManager加载对话记录到ChatModel中
this.loadDialogsFromHistory(roleId);
// 同步对话数据到DialogManager
this.syncDialogData();
console.log(`ChatController switched to role ${roleId}`);
return true;
}
@@ -205,12 +207,15 @@ export class ChatController {
console.log(`Sending message to role ${roleId}: ${message}`);
// 发送消息给AI服务
const response = await ChatAIService.Instance.sendMessage(roleId, message);
const response = await ChatAIService.Instance.sendMessage(
roleId,
message
);
if (response) {
// 移除加载中的对话
this.dialogManager?.removeLoadingDialog();
// 添加AI回复到模型 (保持完整消息)
this.chatModel.addDialog(false, response);
@@ -222,7 +227,7 @@ export class ChatController {
this.callback?.onMessageReceived(response);
// 增加聊天次数计数
this.chatModel.incrementChatCount();
//this.chatModel.incrementChatCount();
// 注意:情绪状态将通过异步事件更新,不在这里同步获取
@@ -231,7 +236,7 @@ export class ChatController {
} else {
// 移除加载中的对话
this.dialogManager?.removeLoadingDialog();
const error = new Error("AI返回了空响应");
this.handleError(error);
return false;
@@ -239,11 +244,15 @@ export class ChatController {
} catch (error) {
// 移除加载中的对话
this.dialogManager?.removeLoadingDialog();
ErrorHandler.Instance.handleApiError(error, "ChatController.sendMessage", {
roleId: this.chatModel.getCurrentRoleId(),
message: message.substring(0, 100) + "..."
});
ErrorHandler.Instance.handleApiError(
error,
"ChatController.sendMessage",
{
roleId: this.chatModel.getCurrentRoleId(),
message: message.substring(0, 100) + "...",
}
);
this.handleError(error as Error);
return false;
}
@@ -257,27 +266,6 @@ export class ChatController {
return this.chatModel.getCurrentEmotion();
}
/**
* 获取当前角色数据
* @returns 角色数据对象,失败时返回null
*/
public getRoleData(): any {
if (!this.chatModel.validate()) {
return null;
}
try {
return {
basic: this.chatModel.getRoleData(),
detail: this.chatModel.getRoleDetail()
};
} catch (error) {
console.error(`Failed to get role data:`, error);
this.handleError(error as Error);
return null;
}
}
/**
* 清除当前角色的聊天历史
*/
@@ -291,10 +279,10 @@ export class ChatController {
try {
// 清除AI服务中的历史记录
ChatAIService.Instance.clearChatHistory(roleId);
// 清除模型中的对话记录
this.chatModel.clearDialogs();
console.log(`Chat history cleared for role ${roleId}`);
} catch (error) {
console.error("Failed to clear chat history:", error);
@@ -310,10 +298,10 @@ export class ChatController {
try {
// 清除AI服务中的历史记录
ChatAIService.Instance.clearChatHistory(roleId);
// 清除模型中的对话记录
this.chatModel.clearDialogs(roleId);
console.log(`Chat history cleared for role ${roleId}`);
} catch (error) {
console.error(`Failed to clear chat history for role ${roleId}:`, error);
@@ -387,18 +375,20 @@ export class ChatController {
// 从ChatHistoryManager加载聊天记录
const chatHistory = ChatHistoryManager.Instance.loadHistory(targetRoleId);
// 清空ChatModel中的对话记录
this.chatModel.clearDialogs(targetRoleId);
// 将ChatHistoryManager的记录转换为Dialog格式并添加到ChatModel
chatHistory.forEach(message => {
chatHistory.forEach((message) => {
const isPlayer = message.role === "user";
const content = message.parts.map(part => part.text).join("");
const content = message.parts.map((part) => part.text).join("");
this.chatModel.addDialog(isPlayer, content, targetRoleId);
});
console.log(`Loaded ${chatHistory.length} messages from ChatHistoryManager for role ${targetRoleId}`);
console.log(
`Loaded ${chatHistory.length} messages from ChatHistoryManager for role ${targetRoleId}`
);
}
/**
@@ -407,13 +397,17 @@ export class ChatController {
*/
public syncDialogData(): void {
if (!this.dialogManager || !this.chatModel.validate()) {
console.warn("Cannot sync dialog data: missing DialogManager or invalid ChatModel");
console.warn(
"Cannot sync dialog data: missing DialogManager or invalid ChatModel"
);
return;
}
const dialogs = this.chatModel.getDialogs();
this.dialogManager.syncFromChatModel(dialogs);
console.log(`Synced ${dialogs.length} dialogs from ChatModel to DialogManager`);
console.log(
`Synced ${dialogs.length} dialogs from ChatModel to DialogManager`
);
}
/**
@@ -430,7 +424,7 @@ export class ChatController {
roleId: targetRoleId,
dialogCount: this.chatModel.getDialogCount(targetRoleId),
lastDialog: this.chatModel.getLastDialog(targetRoleId),
currentEmotion: this.chatModel.getCurrentEmotion(targetRoleId)
currentEmotion: this.chatModel.getCurrentEmotion(targetRoleId),
};
}
@@ -442,7 +436,7 @@ export class ChatController {
const stats = {
totalCachedRoles: this.chatModel.getCachedRoleCount(),
currentRoleId: this.chatModel.getCurrentRoleId(),
roles: {} as any
roles: {} as any,
};
for (const roleId of allRoleIds) {
@@ -452,14 +446,6 @@ export class ChatController {
return stats;
}
/**
* 检查是否有指定角色的数据
* @param roleId 角色ID
*/
public hasRoleData(roleId: number): boolean {
return this.chatModel.hasRoleData(roleId);
}
/**
* 清除指定角色的所有数据
* @param roleId 角色ID
@@ -468,10 +454,10 @@ export class ChatController {
try {
// 清除AI服务中的历史记录
ChatAIService.Instance.clearChatHistory(roleId);
// 清除模型中的角色数据
this.chatModel.clearRoleData(roleId);
console.log(`All data cleared for role ${roleId}`);
} catch (error) {
console.error(`Failed to clear all data for role ${roleId}:`, error);
@@ -479,6 +465,14 @@ export class ChatController {
}
}
/**
* 检查是否有指定角色的数据
* @param roleId 角色ID
*/
public hasRoleData(categoryId:string,roleId: number): boolean {
return this.chatModel.hasRoleData(roleId);
}
/**
* 设置最大缓存角色数量
* @param maxCount 最大缓存数量
@@ -487,14 +481,6 @@ export class ChatController {
this.chatModel.setMaxCachedRoles(maxCount);
}
/**
* 获取模型状态摘要
* @param roleId 角色ID,不传则获取全局摘要
*/
public getModelSummary(roleId?: number): any {
return this.chatModel.getStateSummary(roleId);
}
/**
* 检查是否可以发送消息(基于聊天次数限制)
* @returns 是否可以发送消息
@@ -503,39 +489,6 @@ export class ChatController {
return this.chatModel.canChat();
}
/**
* 获取当前角色剩余聊天次数
* @returns 剩余聊天次数
*/
public getRemainingChats(): number {
return this.chatModel.getRemainingChatCount();
}
/**
* 获取当前角色已使用的聊天次数
* @returns 已使用的聊天次数
*/
public getUsedChats(): number {
return this.chatModel.getRoleChatCount();
}
/**
* 获取当前角色的聊天次数限制
* @returns 聊天次数限制
*/
public getChatLimit(): number {
return this.chatModel.getRoleChatLimit();
}
/**
* 重置当前角色的聊天次数
*/
public resetChatCount(): void {
this.chatModel.resetChatCount();
console.log("ChatController: Chat count reset for current role");
}
/**
* 处理情绪更新事件
* @param data 情绪更新数据 { roleId: number, emotion: VideoEmotion }
@@ -547,14 +500,16 @@ export class ChatController {
}
const { roleId, emotion } = data;
// 只处理当前角色的情绪更新
if (roleId === this.chatModel.getCurrentRoleId()) {
console.log(`ChatController: Emotion updated for role ${roleId}: ${VideoEmotion[emotion]}`);
console.log(
`ChatController: Emotion updated for role ${roleId}: ${VideoEmotion[emotion]}`
);
// 更新模型中的情绪状态
this.chatModel.setCurrentEmotion(emotion);
// 通知界面情绪更新
this.callback?.onEmotionUpdated(emotion);
}
@@ -568,4 +523,4 @@ export class ChatController {
console.error("ChatController error:", error);
this.callback?.onError(error);
}
}
}