代码整理,ai相关配置转luban,聊天气泡缓存
This commit is contained in:
@@ -0,0 +1,212 @@
|
||||
import { sys } from "cc";
|
||||
|
||||
export interface ChatMessage {
|
||||
role: "user" | "model";
|
||||
parts: { text: string }[];
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
export interface ChatHistory {
|
||||
roleId: number;
|
||||
messages: ChatMessage[];
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天历史管理器
|
||||
* 负责聊天记录的本地存储、加载和管理
|
||||
*/
|
||||
export class ChatHistoryManager {
|
||||
private static _instance: ChatHistoryManager;
|
||||
|
||||
public static get Instance(): ChatHistoryManager {
|
||||
if (!this._instance) {
|
||||
this._instance = new ChatHistoryManager();
|
||||
}
|
||||
return this._instance;
|
||||
}
|
||||
|
||||
private constructor() {}
|
||||
|
||||
/**
|
||||
* 保存聊天历史到本地
|
||||
* @param roleId 角色ID
|
||||
* @param messages 消息列表
|
||||
*/
|
||||
public saveHistory(roleId: number, messages: ChatMessage[]): void {
|
||||
const key = `chat_history_${roleId}`;
|
||||
try {
|
||||
const history: ChatHistory = {
|
||||
roleId: roleId,
|
||||
messages: messages,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now()
|
||||
};
|
||||
|
||||
sys.localStorage.setItem(key, JSON.stringify(history));
|
||||
console.log(`Saved chat history for role ${roleId}, ${messages.length} messages`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to save chat history for role ${roleId}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从本地加载聊天历史
|
||||
* @param roleId 角色ID
|
||||
* @returns 消息列表,如果没有历史记录则返回空数组
|
||||
*/
|
||||
public loadHistory(roleId: number): ChatMessage[] {
|
||||
const key = `chat_history_${roleId}`;
|
||||
try {
|
||||
const data = sys.localStorage.getItem(key);
|
||||
if (data) {
|
||||
const history: ChatHistory = JSON.parse(data);
|
||||
console.log(`Loaded chat history for role ${roleId}: ${history.messages.length} messages`);
|
||||
return history.messages;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to load chat history for role ${roleId}:`, error);
|
||||
// 如果数据损坏,清除错误的数据
|
||||
this.clearHistory(roleId);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除指定角色的聊天历史
|
||||
* @param roleId 角色ID
|
||||
*/
|
||||
public clearHistory(roleId: number): void {
|
||||
const key = `chat_history_${roleId}`;
|
||||
sys.localStorage.removeItem(key);
|
||||
console.log(`Cleared chat history for role ${roleId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加消息到历史记录
|
||||
* @param roleId 角色ID
|
||||
* @param message 消息对象
|
||||
*/
|
||||
public appendMessage(roleId: number, message: ChatMessage): void {
|
||||
const history = this.loadHistory(roleId);
|
||||
|
||||
// 添加时间戳
|
||||
message.timestamp = Date.now();
|
||||
history.push(message);
|
||||
|
||||
// 限制历史长度,保留最近100条消息
|
||||
if (history.length > 100) {
|
||||
history.splice(0, history.length - 100);
|
||||
console.log(`Trimmed chat history for role ${roleId} to 100 messages`);
|
||||
}
|
||||
|
||||
this.saveHistory(roleId, history);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定角色的消息数量
|
||||
* @param roleId 角色ID
|
||||
* @returns 消息数量
|
||||
*/
|
||||
public getMessageCount(roleId: number): number {
|
||||
const history = this.loadHistory(roleId);
|
||||
return history.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最近的N条消息
|
||||
* @param roleId 角色ID
|
||||
* @param count 消息数量
|
||||
* @returns 最近的消息列表
|
||||
*/
|
||||
public getRecentMessages(roleId: number, count: number = 10): ChatMessage[] {
|
||||
const history = this.loadHistory(roleId);
|
||||
return history.slice(-count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有聊天历史
|
||||
*/
|
||||
public clearAllHistory(): void {
|
||||
// 查找所有chat_history_开头的key
|
||||
const keysToRemove: string[] = [];
|
||||
for (let i = 0; i < sys.localStorage.length; i++) {
|
||||
const key = sys.localStorage.key(i);
|
||||
if (key && key.startsWith('chat_history_')) {
|
||||
keysToRemove.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
// 删除找到的所有聊天历史
|
||||
keysToRemove.forEach(key => {
|
||||
sys.localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
console.log(`Cleared all chat histories, ${keysToRemove.length} records removed`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有有历史记录的角色ID列表
|
||||
* @returns 角色ID数组
|
||||
*/
|
||||
public getAllHistoryRoleIds(): number[] {
|
||||
const roleIds: number[] = [];
|
||||
for (let i = 0; i < sys.localStorage.length; i++) {
|
||||
const key = sys.localStorage.key(i);
|
||||
if (key && key.startsWith('chat_history_')) {
|
||||
const roleId = parseInt(key.replace('chat_history_', ''));
|
||||
if (!isNaN(roleId)) {
|
||||
roleIds.push(roleId);
|
||||
}
|
||||
}
|
||||
}
|
||||
return roleIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 准备上传到远程服务器(预留接口)
|
||||
* @param roleId 角色ID
|
||||
*/
|
||||
public async syncToRemote(roleId: number): Promise<void> {
|
||||
const history = this.loadHistory(roleId);
|
||||
if (history.length === 0) {
|
||||
console.log(`No history to sync for role ${roleId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// TODO: 调用 HttpUnit.ins.api 上传到服务器
|
||||
// await HttpUnit.ins.api("chat/save_history", {
|
||||
// role_id: roleId,
|
||||
// messages: history
|
||||
// }, "POST");
|
||||
|
||||
console.log(`Ready to sync ${history.length} messages for role ${roleId} to remote server`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to sync history for role ${roleId}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从远程服务器下载历史(预留接口)
|
||||
* @param roleId 角色ID
|
||||
*/
|
||||
public async syncFromRemote(roleId: number): Promise<void> {
|
||||
try {
|
||||
// TODO: 调用 HttpUnit.ins.api 从服务器获取历史
|
||||
// const response = await HttpUnit.ins.api("chat/get_history", {
|
||||
// role_id: roleId
|
||||
// }, "GET");
|
||||
|
||||
// if (response && response.messages) {
|
||||
// this.saveHistory(roleId, response.messages);
|
||||
// console.log(`Synced ${response.messages.length} messages from remote for role ${roleId}`);
|
||||
// }
|
||||
|
||||
console.log(`Ready to sync history from remote server for role ${roleId}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to sync from remote for role ${roleId}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"ver": "4.0.24",
|
||||
"importer": "typescript",
|
||||
"imported": true,
|
||||
"uuid": "8f8fd495-37ee-4577-871f-daf8800b42ed",
|
||||
"files": [],
|
||||
"subMetas": {},
|
||||
"userData": {}
|
||||
}
|
||||
@@ -1,24 +1,24 @@
|
||||
import { find } from "cc";
|
||||
import { ChatContentsLayout } from "../ui/components/ChatContentsLayout";
|
||||
import { DemoData } from "../utils/DemoData";
|
||||
import { DemoData } from "../data/DialogData";
|
||||
import { NavigationManager } from "./NavigationManager";
|
||||
import Utils from "db://assets/Scripts/Main/Common/Utils";
|
||||
import {InnerMsgCode} from "db://assets/Scripts/Main/Config/InnerMsgCode";
|
||||
import { InnerMsgCode } from "db://assets/Scripts/Main/Config/InnerMsgCode";
|
||||
|
||||
/**
|
||||
* 对话管理器
|
||||
*
|
||||
*
|
||||
* 专注于管理对话数据和对话流程,导航功能已迁移至NavigationManager
|
||||
*
|
||||
*
|
||||
* @author AI Chat System
|
||||
* @version 2.0.0
|
||||
*/
|
||||
export class DialogManager {
|
||||
private static _instance: DialogManager;
|
||||
|
||||
|
||||
/**
|
||||
* 获取DialogManager的单例实例
|
||||
*
|
||||
*
|
||||
* @returns {DialogManager} 对话管理器实例
|
||||
* @static
|
||||
*/
|
||||
@@ -35,10 +35,10 @@ export class DialogManager {
|
||||
|
||||
/** 对话数据实例 */
|
||||
private demoData: DemoData;
|
||||
|
||||
|
||||
/** 当前主题ID */
|
||||
private themeId = -1;
|
||||
|
||||
|
||||
/** 聊天内容布局组件引用 */
|
||||
public layoutout: ChatContentsLayout;
|
||||
|
||||
@@ -47,19 +47,25 @@ export class DialogManager {
|
||||
* @deprecated 请直接使用 NavigationManager.Instance.navigateToGirlList()
|
||||
*/
|
||||
public EnterGirlList(id: number = null): void {
|
||||
console.warn("DemoManager.EnterGirlList is deprecated, use NavigationManager instead");
|
||||
if(id != null) { this.themeId = id; }
|
||||
if(this.themeId !== -1) {
|
||||
console.warn(
|
||||
"DemoManager.EnterGirlList is deprecated, use NavigationManager instead"
|
||||
);
|
||||
if (id != null) {
|
||||
this.themeId = id;
|
||||
}
|
||||
if (this.themeId !== -1) {
|
||||
NavigationManager.Instance.navigateToGirlList(this.themeId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 进入聊天页面(委托给NavigationManager)
|
||||
* @deprecated 请直接使用 NavigationManager.Instance.navigateToChat()
|
||||
*/
|
||||
public EnterChat(id: number): void {
|
||||
console.warn("DemoManager.EnterChat is deprecated, use NavigationManager instead");
|
||||
console.warn(
|
||||
"DemoManager.EnterChat is deprecated, use NavigationManager instead"
|
||||
);
|
||||
NavigationManager.Instance.navigateToChat(id);
|
||||
}
|
||||
|
||||
@@ -68,35 +74,44 @@ export class DialogManager {
|
||||
* @deprecated 请直接使用 NavigationManager.Instance.navigateToGirlDetail()
|
||||
*/
|
||||
public EnterDetail(id: number): void {
|
||||
console.warn("DemoManager.EnterDetail is deprecated, use NavigationManager instead");
|
||||
console.warn(
|
||||
"DemoManager.EnterDetail is deprecated, use NavigationManager instead"
|
||||
);
|
||||
NavigationManager.Instance.navigateToGirlDetail(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新对话内容
|
||||
*
|
||||
*
|
||||
* @param {boolean} isPlayer - 是否为玩家消息
|
||||
* @param {string} str - 消息内容
|
||||
* @param {boolean} fromPlayer - 是否来自玩家输入(用于清理对话)
|
||||
*/
|
||||
public updateDialog(isPlayer: boolean, str: string, fromPlayer: boolean = false): void {
|
||||
if(fromPlayer) {
|
||||
public updateDialog(
|
||||
isPlayer: boolean,
|
||||
str: string,
|
||||
fromPlayer: boolean = false
|
||||
): void {
|
||||
if (fromPlayer) {
|
||||
this.demoData.cleanDialog();
|
||||
}
|
||||
this.demoData.pushDialog(isPlayer, str);
|
||||
console.log("Dialog updated:", { isPlayer, content: str.substring(0, 50) + "..." });
|
||||
console.log("Dialog updated:", {
|
||||
isPlayer,
|
||||
content: str.substring(0, 50) + "...",
|
||||
});
|
||||
Utils.sendInnerMsg(InnerMsgCode.Chat_DialogRefresh);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有对话记录
|
||||
*
|
||||
*
|
||||
* @returns {Dialog[]} 对话记录数组
|
||||
*/
|
||||
public getDialogs() {
|
||||
return this.demoData.GetDialogs();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 清空当前对话记录
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user