diff --git a/.DS_Store b/.DS_Store index e477019..27b5101 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/build/index.html b/build/index.html index 0c81130..27317b5 100644 --- a/build/index.html +++ b/build/index.html @@ -8,12 +8,12 @@ NPCs - - - - - - + + + + + + diff --git a/build/locales/en/bs.json b/build/locales/en/bs.json index bc4d299..125bf29 100644 --- a/build/locales/en/bs.json +++ b/build/locales/en/bs.json @@ -57,7 +57,11 @@ }, "skills": { "manageTemplate": "Manage Skill Templates", - "createNew": "Create New", + "createNew": "Create New Skill", + "customSkills": "Custom Skills", + "chooseOnline": "Choose the online version", + "executionSteps": "Skills are visualized through process orchestration to clarify task execution steps", + "sceneTemplates": "We provide scene templates for your use and reference", "manageProjects": "Manage your personal projects here, including skill deployment and editing", "skillSearch": "Skill Search", "confirmDeleteSkill": "Confirm the deletion of this skill?", @@ -80,6 +84,7 @@ "skillDescTooLong": "Skill description is too long, should not exceed 200 characters", "errorTitle": "Key Information Error", "onlineFailure": "Online failure", + "onlineSuccessful": "Online Successful", "custom": "Custom", "skillTemplate": "Skill Template", "skillTemplateChoose": "You can choose a template from here to start, or create an advanced template", @@ -92,7 +97,23 @@ "createdBy": "Created by", "offline": "Offline", "online": "Online", - "guideWords": "Guide Words" + "guideWords": "Guide Words", + "currentVersion": "Current Version: ", + "importLocal": "Import local components", + "save": "Saved", + "import": "Import", + "export": "Export", + "code": "Code", + "simplify": "Simplify", + "saveVersion": "SaveVersion", + "deleteOrNot": "Do you want to delete", + "version": "version", + "saveSuccessful": "Save Successful", + "supportVersions": "Support splitting into multiple version branches for development and comparison between versions.", + "guideQuestions50": "Guide questions to a maximum of 50 characters", + "promptWords1000": "The maximum number of prompt words is 1000 characters", + "contactAdmin": "Please contact the administrator's online assistant", + "deleteSure": "Are you sure you want to delete this tool?" }, "chat": { "newChat": "New Chat", @@ -238,7 +259,7 @@ "rootDirectory": "Root directory", "createOneKnowledge": "Create a knowledge base", "webSite": "Web site synchronization", - "knowledge": "Knowledge base type", + "knowledgeType": "Knowledge base type", "knowledgeDescription": "Knowledge base can be built by importing files, webpage links, or manually entering them", "webSiteDescription": "Web site synchronization allows you to directly use a webpage link to build a knowledge base", "baseSet": "Basic Settings", @@ -262,7 +283,27 @@ "foldDesc": "This is a folder", "noFold": "We don't have a folder yet, create one quickly", "selectFold": "Please select a folder", - "confirmDelete": "Confirm deletion" + "confirmDelete": "Confirm deletion", + "dataset": "Dataset", + "config": "Configure", + "queueLen": "Queue length", + "allKnowledge": "All datasets", + "file": "File", + "dataTotal": "Total data volume", + "lastUpdate": "Last update time", + "state": "State", + "syncData": "Synchronize data", + "manualDataset": "Manual dataset", + "textDataset": "Text dataset", + "tableDataset": "Table Dataset", + "createImport": "Create/Import", + "knowledge": "Knowledge base", + "web": "Website", + "knowledgeId": "Knowledge Base ID", + "knowledgeImg": "Knowledge Base Avatar", + "indexModel": "Index model", + "dataUp": "Single data upper limit", + "introduce": "Introduce" }, "code": { "editPythonCodeDescription": "Edit your Python code here. This code snippet accepts module imports and a function definition. Make sure your function returns a string.", @@ -402,6 +443,139 @@ "previousPage": "Previous Page", "nextPage": "Next Page", "formatError": "Format Error", + "port": "PORT", + "cancle": "Cancle", + "tip": "Prompt", + "deleteAssistant": "Are you sure to delete this assistant?", + "build": { + "create": "Create", + "assistant": "Assistant", + "skill": "Skills", + "tools": "Tools", + "save": "Save", + "online": "Online", + "retry": "Retry", + "use": "Use", + "useAll": "Use All", + "assistantConfiguration": "Assistant Configuration", + "createAssistant": "Create a New Assistant", + "assistantPortrait": "Assistant Portrait", + "portraitOptimization": "Assistant portrait optimization", + "automaticOptimization": "Automatic optimization", + "createDescription": "Create your assistant by describing roles and tasks", + "nextDescription": "Assistant can call multiple skills and tools", + "searchAssistant": "Search for the assistant you need", + "manageAssistant": "Manage your assistant on this page, including online and offline activities, editing, and more", + "establishAssistant": "Create Assistant", + "assistantName": "Assistant Name", + "giveAssistantName": "Give the assistant a name", + "whatWant": "What is the role of an assistant and what specific tasks do you want to complete?", + "example": "Example", + "exampleOne": "You are XX, with XX experience, skilled in XX, ...", + "exampleTwo": "Your task is XX, and you need to follow the following steps to execute it:", + "automaticallyConfigurations": "Automatically select relevant configurations for you", + "prompt": "Provide a detailed and specific description of the interaction between the assistant and the user, such as the assistant's identity, specific methods and steps for completing tasks, tone of voice when answering questions, and what issues should be noted", + "openingRemarks": "Opening remarks", + "guidingQuestions": "Guiding Questions", + "promptReplaced": "Prompt word replaced", + "guideReplaced": "Guide word replaced", + "openingReplaced": "Opening word replaced", + "toolsReplaced": "Tools replaced", + "skillsReplaced": "Skills replaced", + "allReplaced": "All replaced", + "basicConfiguration": "Basic configuration", + "modelConfiguration": "AI Model configuration", + "model": "Model", + "temperature": "Temperature", + "openingIntroduction": "Opening Introduction", + "openingStatement": "Opening Statement", + "assistantMessageFormat": "The assistant will send this message at the beginning of each conversation, supports Markdown format", + "maximumPromptLength": "The prompt can be up to 1000 characters", + "recommendQuestionsForUsers": "Provide recommended questions for users to guide them to ask. When there are more than 3, 3 will be randomly selected.", + "maxCharacters50": "Up to 50 characters", + "enterGuidingQuestions": "Please enter guiding questions", + "knowledge": "Knowledge", + "knowledgeBase": "Knowledge Base", + "autoCall": "Auto Call", + "callingMethod": "Calling Method", + "autoCallDescription": "Retrieve and recall the added knowledge base in every conversation.", + "onDemandCall": "On-Demand Call", + "onDemandCallDescription": "Prompt to call the RecallKnowledge (copyable) method in the assistant's profile (prompt words), and only retrieve the knowledge base when needed.", + "createNewKnowledge": "Create New Knowledge Base", + "refresh": "Refresh", + "abilities": "Abilities", + "skillDescription": "Implement complex and stable business process orchestration through a visual interface, such as project planning and report analysis.", + "selectKnowledgeBase": "Please select a knowledge base", + "searchBaseName": "Search for knowledge base name", + "debugPreview": "Debug Preview", + "addTool": "Add Tool", + "search": "Search", + "empty": "Nothing here", + "onlineSA": "Go online skills&assistants", + "params": "Parameters", + "added": "Added", + "add": "Add", + "configurationUpdated": "Configuration updated", + "addSkill": "Add Skill", + "createSkill": "Create Skill", + "nameRequired": "Name cannot be empty", + "nameMaxLength": "Name can have at most 50 characters", + "descMaxLength": "Description can have at most 1000 characters", + "editAssistant": "Edit Assistant", + "enterName": "Enter a name for the assistant", + "assistantDesc": "Assistant Description", + "enterDesc": "Introduce assistant functionality, visible in conversations and assistant pages", + "cancel": "Cancel", + "confirm": "Confirm", + "forBetter": "For better assistant effect, the description needs to be greater than 20 words", + "forExample": "For example, the identity of an assistant, specific methods and steps for completing tasks, tone of voice when answering questions, and what issues to pay attention to, etc" + }, + "tools1": { + "addTool": "Add Tool", + "createCustomTool": " Custom Tool", + "builtinTools": "Built-in Tools", + "customTools": "Custom Tools", + "search": "Search", + "empty": "Empty", + "manageCustomTools": "Manage your custom tools on this page, including creating and editing them.", + "name": "Name", + "enterToolName": "Enter tool name", + "openapiSchema": "OpenAPI Schema", + "enterOpenAPISchema": "Enter your OpenAPI schema", + "importFromUrl": "Import from URL", + "examples": "Examples", + "weatherJson": "Weather (JSON)", + "petShopYaml": "Pet Shop (YAML)", + "authenticationType": "Authentication Type", + "authType": "Authentication Type", + "none": "None", + "apiKey": "API Key", + "basic": "Basic", + "bearer": "Bearer", + "availableTools": "Available Tools", + "description": "Description", + "method": "Method", + "path": "Path", + "delete": "Delete", + "cancel": "Cancel", + "save": "Save" + }, + "test": { + "test": "Test", + "addTest": "Please add test cases first", + "uploadTest": "Upload test cases", + "explain": "The test case is the input of the current component and only supports txt files, with a maximum of 20 lines", + "testRun": "Test Run", + "testCase": "Test Case", + "run": "Run", + "downloadResults": "Download Run Results", + "testCases": "Enter test cases...", + "parametersAndValues": "Parameters and Values", + "parameter": "Parameter", + "value": "Value", + "result": "Test Result", + "outResultPlaceholder": "Click the button to output the result" + }, "agents": { "AgentInitializer":{ "display_name": "AgentInitializer", diff --git a/build/locales/zh/bs.json b/build/locales/zh/bs.json index 1b511ed..0c44f9a 100644 --- a/build/locales/zh/bs.json +++ b/build/locales/zh/bs.json @@ -42,9 +42,9 @@ "roleList": "角色列表", "confirmText": "是否删除", "roleName": "角色名称", - "skillAuthorization": "NPC授权", + "skillAuthorization": "能力授权", "knowledgeAuthorization": "知识库授权", - "skillName": "NPC名称", + "skillName": "能力名称", "creator": "创建人", "usePermission": "使用权限", "managePermission": "管理权限", @@ -55,40 +55,61 @@ "language": "语言" }, "skills": { - "manageTemplate": "管理NPC模板", - "createNew": "新建", - "manageProjects": "这里管理您的个人项目,对NPC上下线、编辑等等", - "skillSearch": "NPC搜索", - "confirmDeleteSkill": "确认删除该NPC?", - "backToSkillList": "返回NPC列表", - "skillTemplateManagement": "NPC模板管理,模板对所有用户可见,支持拖拽排序、删除操作", + "manageTemplate": "管理技能模板", + "createNew": "新建技能", + "customSkills": "自定义技能", + "chooseOnline": "选择上线版本", + "executionSteps": "技能通过可视化的流程编排,明确任务执行步骤", + "sceneTemplates": "我们提供场景模板供您使用和参考", + "manageProjects": "在此页面管理您的技能,对技能上下线、编辑等等", + "skillSearch": "搜索您需要的技能", + "confirmDeleteSkill": "确认删除该技能?", + "backToSkillList": "返回技能列表", + "skillTemplateManagement": "技能模板管理,模板对所有用户可见,支持拖拽排序、删除操作", "templateName": "模板名称", "templateDescription": "模板描述", - "confirmText": "是否确认删除该NPC模板?", - "skillSettings": "NPC设置", + "confirmText": "是否确认删除该技能模板?", + "skillSettings": "技能设置", "basicInfo": "基础信息", - "skillName": "NPC名称", + "skillName": "技能名称", "description": "描述", "parameterInfo": "参数信息", "advancedConfiguration": "高级配置", "nextStep": "下一步,高级配置", - "skillNameRequired": "请填写NPC名称", - "skillNameTooLong": "NPC名称过长,不要超过30字", + "skillNameRequired": "请填写技能名称", + "skillNameTooLong": "技能名称过长,不要超过30字", "skillNameExists": "该名称已存在", - "skillDescRequired": "请填写NPC描述", - "skillDescTooLong": "NPC描述过长,不要超过200字", + "skillDescRequired": "请填写技能描述", + "skillDescTooLong": "技能描述过长,不要超过200字", "errorTitle": "关键信息有误", "onlineFailure": "上线失败", + "onlineSuccessful": "上线成功", "custom": "自定义", - "skillTemplate": "NPC模板", + "skillTemplate": "技能模板", "skillTemplateChoose": "您可以从这里挑选一个模板开始,或者自定义高级模板", "createTemplate": "创建模板", - "createSuccessTitle": "NPC创建成功", + "createSuccessTitle": "技能创建成功", "createFailureTitle": "创建失败", "createdBy": "创建用户", "offline": "下线", "online": "上线", - "guideWords": "引导词" + "guideWords": "引导词", + "currentVersion": "当前版本:", + "importLocal": "导入本地组件", + "save": "保存", + "import": "导入", + "export": "导出", + "code": "代码", + "simplify": "简化", + "saveVersion": "另存为新版本", + "deleteOrNot": "是否删除", + "version": "版本", + "saveSuccessful": "保存成功", + "supportVersions": "支持分成多个版本分支,分别进行开发以及版本间的比较。", + "guideQuestions50": "引导问题最多50个字符", + "promptWords1000": "提示词最多为1000个字符", + "contactAdmin": "请联系管理员上线NPC", + "deleteSure": "确认删除该工具?" }, "chat": { "newChat": "新建会话", @@ -96,8 +117,8 @@ "inputPlaceholder": "请输入问题", "uploadFileTooltip": "上传文件", "sendTooltip": "发送", - "skillTempsTitle": "NPC选择", - "skillTempsDesc": "选择一个您想使用的线上NPC", + "skillTempsTitle": "能力选择", + "skillTempsDesc": "选择一个您想使用的线上能力", "forms": "表单", "networkError": "网络连接出现错误,请尝试以下方法", "networkErrorList1": "操作不要过快", @@ -137,7 +158,7 @@ "warningTooltip": "处理异常", "inProgressOnlineStatus": "上线中", "inProgressOfflineStatus": "下线中", - "confirmModelOffline": "是否确认下线该模型,下线后使用该模型服务的NPC将无法正常工作", + "confirmModelOffline": "是否确认下线该模型,下线后使用该模型服务的能力将无法正常工作", "confirmOfflineButtonText": "下线", "modelManagement": "模型管理", "modelFineTune": "模型Finetune", @@ -172,7 +193,7 @@ "searchComponent": "查找组件", "knowledgeBaseSelection": "知识库选择", "searchKnowledgeBase": "搜索知识库", - "minimumParamSetDescription": "您可以在此设置NPC所需的最小参数集", + "minimumParamSetDescription": "您可以在此设置能力所需的最小参数集", "paramList": "参数列表", "saveConfig": "保存配置", "componentLabel": "组件", @@ -181,9 +202,9 @@ "parameterLabel": "参数", "notification": "消息", "noNewNotifications": "没有新的通知", - "skillName": "NPC名", + "skillName": "能力名", "nameTooLong": "名称过长", - "skillDescription": "NPC描述", + "skillDescription": "能力描述", "enterVarName": "请输入变量名", "varNameExists": "变量名重复", "text": "文本", @@ -230,7 +251,7 @@ "rootDirectory": "根目录", "createOneKnowledge": "创建一个知识库", "webSite": "Web站点同步", - "knowledge": "知识库类型", + "knowledgeType": "知识库类型", "knowledgeDescription": "可通过导入文件、网页链接或手动录入形式构建知识库", "webSiteDescription": "Web站点同步允许你直接使用一个网页链接构建知识库", "baseSet": "基本设置", @@ -254,7 +275,27 @@ "foldDesc": "这是一个文件夹", "noFold": "还没有文件夹,快快创建一个吧~", "selectFold": "请选择文件夹", - "confirmDelete": "确定删除" + "confirmDelete": "确定删除", + "dataset": "数据集", + "config": "配置", + "queueLen": "排队长度", + "allKnowledge": "全部数据集", + "file": "文件", + "dataTotal": "数据总量", + "lastUpdate": "最后更新时间", + "state": "状态", + "syncData": "同步数据", + "manualDataset": "手动数据集", + "textDataset": "文本数据集", + "tableDataset": "表格数据集", + "createImport": "新建/导入", + "knowledge": "知识库", + "web": "网站", + "knowledgeId": "知识库ID", + "knowledgeImg": "知识库头像", + "indexModel": "索引模型", + "dataUp": "单条数据上限", + "introduce": "介绍" }, "code": { "editPythonCodeDescription": "编辑你的 Python 代码此代码片段接受模块导入和一个函数定义。确保您的函数返回一个字符串。", @@ -266,11 +307,11 @@ "codeError": "这段代码有问题,请检查以下", "checkAndSave": "检查 & 保存", "export": "导出", - "exportToJSON": "导出NPC到json文件中", + "exportToJSON": "导出能力到json文件中", "keyInformationMissing": "您有一些关键信息没有填: ", - "skillNameMissing": "请填写NPC名称", + "skillNameMissing": "请填写能力名称", "useOwnAPIKeys": "使用自己的API keys", - "exportSkill": "导出NPC", + "exportSkill": "导出能力", "uploadFile": "上传文件", "clickOrDragHere": "点击或将文件拖拽到这里上传", "dropFileHere": "将文件拖拽到这里上传", @@ -287,7 +328,7 @@ "file": "文件", "sizeExceedsLimit": "超过50M", "editDictionary": "编辑词典", - "exportCodeDialogTip": "生成代码,将流程集成到外部应用程序中 (打开此页面前请先buildNPC)。", + "exportCodeDialogTip": "生成代码,将流程集成到外部应用程序中 (打开此页面前请先build能力)。", "chunkOverlap": "切分文本重叠长度" }, "report": { @@ -304,8 +345,8 @@ "varLength": "长度不能超过" }, "status": { - "1004": "该NPC已被删除", - "1008": "当前NPC未上线,无法直接对话", + "1004": "该能力已被删除", + "1008": "当前能力未上线,无法直接对话", "1005": "" }, "all": "全部", @@ -394,6 +435,139 @@ "previousPage": "上一页", "nextPage": "下一页", "formatError": "格式错误", + "port": "服务端口", + "cancle": "取消", + "tip": "提示", + "deleteAssistant": "确认删除该NPC?", + "build": { + "create": "创建", + "assistant": "NPC", + "skill": "技能", + "tools": "工具", + "save": "保存", + "online": "上线", + "retry": "重试", + "use": "使用", + "useAll": "全部使用", + "assistantConfiguration": "NPC配置", + "createAssistant": "新建NPC", + "assistantPortrait": "NPC画像", + "portraitOptimization": "NPC画像优化", + "automaticOptimization": "自动优化", + "createDescription": "通过描述角色和任务来创建你的NPC", + "nextDescription": "NPC可以调用多个技能和工具", + "searchAssistant": "搜索您需要的NPC", + "manageAssistant": "在此页面管理您的NPC,对NPC上下线、编辑等等", + "establishAssistant": "创建NPC", + "assistantName": "NPC名称", + "giveAssistantName": "给NPC取一个名字", + "whatWant": "你希望NPC的角色是什么,具体完成什么任务?", + "example": "示例", + "exampleOne": "你是 XX,具有 XX 经验,擅长 XX,…", + "exampleTwo": "你的任务是 XX ,需要按照以下步骤执行:", + "automaticallyConfigurations": "自动为您选择相关配置", + "prompt": "详细、具体地描述NPC与用户的交互方式,例如NPC的身份、完成任务的具体方法和步骤、回答问题时的语气以及应该注意什么问题等", + "openingRemarks": "开场白", + "guidingQuestions": "引导问题", + "promptReplaced": "提示词已替换", + "guideReplaced": "引导词已替换", + "openingReplaced": "开场白已替换", + "toolsReplaced": "工具已替换", + "skillsReplaced": "技能已替换", + "allReplaced": "已全部替换", + "basicConfiguration": "基础配置", + "modelConfiguration": "AI模型配置", + "model": "模型", + "temperature": "温度", + "openingIntroduction": "开场引导", + "openingStatement": "开场白", + "assistantMessageFormat": "NPC将在每次对话开始时发送此信息,支持 Markdown 格式", + "maximumPromptLength": "提示词最多为1000个字符", + "recommendQuestionsForUsers": "为用户提供推荐问题,引导用户提问,超过3个时将随机选取3个", + "maxCharacters50": "最多50个字符", + "enterGuidingQuestions": "请输入引导问题", + "knowledge": "知识", + "knowledgeBase": "知识库", + "autoCall": "自动调用", + "callingMethod": "调用方式", + "autoCallDescription": "每轮对话都会对添加的知识库进行检索召回。", + "onDemandCall": "按需调用", + "onDemandCallDescription": "在NPC画像(提示词)中提示调用 RecallKnowledge(可复制)方法,在有需要时才对知识库进行检索。", + "createNewKnowledge": "新建知识库", + "refresh": "刷新", + "abilities": "能力", + "skillDescription": "通过可视化界面实现复杂和稳定的业务流程编排,例如项目计划和报告分析", + "selectKnowledgeBase": "请选择知识库", + "searchBaseName": "搜索知识库名称", + "debugPreview": "调试预览", + "addTool": "添加工具", + "search": "搜索", + "empty": "空空如也", + "onlineSA": "上线技能&NPC", + "params": "参数", + "added": "已添加", + "add": "添加", + "configurationUpdated": "配置已更新", + "addSkill": "添加技能", + "createSkill": "创建技能", + "nameRequired": "名称不可为空", + "nameMaxLength": "名称最多50个字符", + "descMaxLength": "最多1000个字符", + "editAssistant": "编辑NPC", + "enterName": "给NPC取一个名字", + "assistantDesc": "NPC描述", + "enterDesc": "介绍NPC功能,描述在会话和NPC页面可见", + "cancel": "取消", + "confirm": "确认", + "forBetter": "为了更好的NPC效果,描述需要大于20 个字", + "forExample": "例如NPC的身份、完成任务的具体方法和步骤、回答问题时的语气以及应该注意什么问题等" + }, + "tools1": { + "addTool": "添加工具", + "createCustomTool": "自定义工具", + "builtinTools": "内置工具", + "customTools": "自定义工具", + "search": "搜索", + "empty": "空空如也", + "manageCustomTools": "在此页面管理您的自定义工具,对自定义工具创建、编辑等等", + "name": "名称", + "enterToolName": "输入工具名称", + "openapiSchema": "OpenAPI Schema", + "enterOpenAPISchema": "输入您的 OpenAPI schema", + "importFromUrl": "从 URL 导入", + "examples": "示例", + "weatherJson": "天气(JSON)", + "petShopYaml": "宠物商店(YAML)", + "authenticationType": "鉴权方式", + "authType": "认证类型", + "none": "无", + "apiKey": "API Key", + "basic": "Basic", + "bearer": "Bearer", + "availableTools": "可用工具", + "description": "描述", + "method": "方法", + "path": "路径", + "delete": "删除", + "cancel": "取消", + "save": "保存" + }, + "test": { + "test": "测试", + "addTest": "请先填写测试用例", + "uploadTest": "上传测试用例", + "explain": "为测试用例是当前组件的输入,只支持 txt 文件,最多 20 行", + "testRun": "测试运行", + "testCase": "测试用例", + "run": "运行", + "downloadResults": "下载运行结果", + "testCases": "输入测试用例...", + "parametersAndValues": "参数和值", + "parameter": "参数", + "value": "值", + "result": "测试结果", + "outResultPlaceholder": "点击按钮,输出结果" + }, "agents": { "AgentInitializer": { "display_name": "AgentInitializer", @@ -613,8 +787,8 @@ }, "autogen_roles": { "AutoGenAssistant": { - "display_name": "自动生成助手", - "description": "助手代理,设计用于使用大语言模型LLM解决任务。", + "display_name": "自动生成NPC", + "description": "NPC代理,设计用于使用大语言模型LLM解决任务。", "description_url": "https://lxm3ki8hexz.feishu.cn/wiki/Yz5GwMpO7ioj8nkRSZlcsriXnJ3", "template": { "model_name": { @@ -640,7 +814,7 @@ } }, "output_types":[ - "自动生成助手" + "自动生成NPC" ] }, "AutoGenCoder": { diff --git a/public/locales/zh/bs.json b/public/locales/zh/bs.json index e1f0d61..0c44f9a 100644 --- a/public/locales/zh/bs.json +++ b/public/locales/zh/bs.json @@ -108,7 +108,7 @@ "supportVersions": "支持分成多个版本分支,分别进行开发以及版本间的比较。", "guideQuestions50": "引导问题最多50个字符", "promptWords1000": "提示词最多为1000个字符", - "contactAdmin": "请联系管理员上线助手", + "contactAdmin": "请联系管理员上线NPC", "deleteSure": "确认删除该工具?" }, "chat": { @@ -438,10 +438,10 @@ "port": "服务端口", "cancle": "取消", "tip": "提示", - "deleteAssistant": "确认删除该助手?", + "deleteAssistant": "确认删除该NPC?", "build": { "create": "创建", - "assistant": "助手", + "assistant": "NPC", "skill": "技能", "tools": "工具", "save": "保存", @@ -449,24 +449,24 @@ "retry": "重试", "use": "使用", "useAll": "全部使用", - "assistantConfiguration": "助手配置", - "createAssistant": "新建助手", - "assistantPortrait": "助手画像", - "portraitOptimization": "助手画像优化", + "assistantConfiguration": "NPC配置", + "createAssistant": "新建NPC", + "assistantPortrait": "NPC画像", + "portraitOptimization": "NPC画像优化", "automaticOptimization": "自动优化", - "createDescription": "通过描述角色和任务来创建你的助手", - "nextDescription": "助手可以调用多个技能和工具", - "searchAssistant": "搜索您需要的助手", - "manageAssistant": "在此页面管理您的助手,对助手上下线、编辑等等", - "establishAssistant": "创建助手", - "assistantName": "助手名称", - "giveAssistantName": "给助手取一个名字", - "whatWant": "你希望助手的角色是什么,具体完成什么任务?", + "createDescription": "通过描述角色和任务来创建你的NPC", + "nextDescription": "NPC可以调用多个技能和工具", + "searchAssistant": "搜索您需要的NPC", + "manageAssistant": "在此页面管理您的NPC,对NPC上下线、编辑等等", + "establishAssistant": "创建NPC", + "assistantName": "NPC名称", + "giveAssistantName": "给NPC取一个名字", + "whatWant": "你希望NPC的角色是什么,具体完成什么任务?", "example": "示例", "exampleOne": "你是 XX,具有 XX 经验,擅长 XX,…", "exampleTwo": "你的任务是 XX ,需要按照以下步骤执行:", "automaticallyConfigurations": "自动为您选择相关配置", - "prompt": "详细、具体地描述助手与用户的交互方式,例如助手的身份、完成任务的具体方法和步骤、回答问题时的语气以及应该注意什么问题等", + "prompt": "详细、具体地描述NPC与用户的交互方式,例如NPC的身份、完成任务的具体方法和步骤、回答问题时的语气以及应该注意什么问题等", "openingRemarks": "开场白", "guidingQuestions": "引导问题", "promptReplaced": "提示词已替换", @@ -481,7 +481,7 @@ "temperature": "温度", "openingIntroduction": "开场引导", "openingStatement": "开场白", - "assistantMessageFormat": "助手将在每次对话开始时发送此信息,支持 Markdown 格式", + "assistantMessageFormat": "NPC将在每次对话开始时发送此信息,支持 Markdown 格式", "maximumPromptLength": "提示词最多为1000个字符", "recommendQuestionsForUsers": "为用户提供推荐问题,引导用户提问,超过3个时将随机选取3个", "maxCharacters50": "最多50个字符", @@ -492,7 +492,7 @@ "callingMethod": "调用方式", "autoCallDescription": "每轮对话都会对添加的知识库进行检索召回。", "onDemandCall": "按需调用", - "onDemandCallDescription": "在助手画像(提示词)中提示调用 RecallKnowledge(可复制)方法,在有需要时才对知识库进行检索。", + "onDemandCallDescription": "在NPC画像(提示词)中提示调用 RecallKnowledge(可复制)方法,在有需要时才对知识库进行检索。", "createNewKnowledge": "新建知识库", "refresh": "刷新", "abilities": "能力", @@ -503,7 +503,7 @@ "addTool": "添加工具", "search": "搜索", "empty": "空空如也", - "onlineSA": "上线技能&助手", + "onlineSA": "上线技能&NPC", "params": "参数", "added": "已添加", "add": "添加", @@ -513,14 +513,14 @@ "nameRequired": "名称不可为空", "nameMaxLength": "名称最多50个字符", "descMaxLength": "最多1000个字符", - "editAssistant": "编辑助手", - "enterName": "给助手取一个名字", - "assistantDesc": "助手描述", - "enterDesc": "介绍助手功能,描述在会话和助手页面可见", + "editAssistant": "编辑NPC", + "enterName": "给NPC取一个名字", + "assistantDesc": "NPC描述", + "enterDesc": "介绍NPC功能,描述在会话和NPC页面可见", "cancel": "取消", "confirm": "确认", - "forBetter": "为了更好的助手效果,描述需要大于20 个字", - "forExample": "例如助手的身份、完成任务的具体方法和步骤、回答问题时的语气以及应该注意什么问题等" + "forBetter": "为了更好的NPC效果,描述需要大于20 个字", + "forExample": "例如NPC的身份、完成任务的具体方法和步骤、回答问题时的语气以及应该注意什么问题等" }, "tools1": { "addTool": "添加工具", @@ -787,8 +787,8 @@ }, "autogen_roles": { "AutoGenAssistant": { - "display_name": "自动生成助手", - "description": "助手代理,设计用于使用大语言模型LLM解决任务。", + "display_name": "自动生成NPC", + "description": "NPC代理,设计用于使用大语言模型LLM解决任务。", "description_url": "https://lxm3ki8hexz.feishu.cn/wiki/Yz5GwMpO7ioj8nkRSZlcsriXnJ3", "template": { "model_name": { @@ -814,7 +814,7 @@ } }, "output_types":[ - "自动生成助手" + "自动生成NPC" ] }, "AutoGenCoder": { diff --git a/src/.DS_Store b/src/.DS_Store index d397f2b..4eacb2c 100644 Binary files a/src/.DS_Store and b/src/.DS_Store differ diff --git a/src/App.css b/src/App.css index f667543..46ddec9 100644 --- a/src/App.css +++ b/src/App.css @@ -191,9 +191,9 @@ } path.react-flow__edge-interaction:hover { - stroke: #eebbbb; + stroke: #ffe999; stroke-opacity: 1; - stroke-width: 12; + stroke-width: 10; } .selection-tool-box { diff --git a/src/assets/.DS_Store b/src/assets/.DS_Store index b2fcee6..792e682 100644 Binary files a/src/assets/.DS_Store and b/src/assets/.DS_Store differ diff --git a/src/assets/chat/.DS_Store b/src/assets/chat/.DS_Store index ff1897a..e46c1af 100644 Binary files a/src/assets/chat/.DS_Store and b/src/assets/chat/.DS_Store differ diff --git a/src/assets/chat/xinjian1.png b/src/assets/chat/xinjian1.png new file mode 100644 index 0000000..73022e4 Binary files /dev/null and b/src/assets/chat/xinjian1.png differ diff --git a/src/assets/chat/xinjian2.png b/src/assets/chat/xinjian2.png new file mode 100644 index 0000000..f5f92d7 Binary files /dev/null and b/src/assets/chat/xinjian2.png differ diff --git a/src/assets/npc/.DS_Store b/src/assets/npc/.DS_Store index 5a14dde..c423b6e 100644 Binary files a/src/assets/npc/.DS_Store and b/src/assets/npc/.DS_Store differ diff --git a/src/assets/npc/border-r.png b/src/assets/npc/border-r.png new file mode 100644 index 0000000..053171f Binary files /dev/null and b/src/assets/npc/border-r.png differ diff --git a/src/assets/npc/jianhua.png b/src/assets/npc/jianhua.png new file mode 100644 index 0000000..67210e6 Binary files /dev/null and b/src/assets/npc/jianhua.png differ diff --git a/src/assets/npc/lingcun.png b/src/assets/npc/lingcun.png new file mode 100644 index 0000000..2444f61 Binary files /dev/null and b/src/assets/npc/lingcun.png differ diff --git a/src/assets/npc/nengliIcon1.png b/src/assets/npc/nengliIcon1.png new file mode 100644 index 0000000..1514f38 Binary files /dev/null and b/src/assets/npc/nengliIcon1.png differ diff --git a/src/assets/npc/tuichu.png b/src/assets/npc/tuichu.png new file mode 100644 index 0000000..80c49e1 Binary files /dev/null and b/src/assets/npc/tuichu.png differ diff --git a/src/assets/npc/xiaoxi.png b/src/assets/npc/xiaoxi.png new file mode 100644 index 0000000..a75a510 Binary files /dev/null and b/src/assets/npc/xiaoxi.png differ diff --git a/src/assets/npc/图层 1863@2x (1).png b/src/assets/npc/图层 1863@2x (1).png new file mode 100644 index 0000000..75ca173 Binary files /dev/null and b/src/assets/npc/图层 1863@2x (1).png differ diff --git a/src/components/bs-comp/cardComponent/index.tsx b/src/components/bs-comp/cardComponent/index.tsx index 5e336e5..d95ffe3 100644 --- a/src/components/bs-comp/cardComponent/index.tsx +++ b/src/components/bs-comp/cardComponent/index.tsx @@ -60,8 +60,11 @@ export const gradients = [ // 'bg-fuchsia-700', // 'bg-pink-600', // 'bg-rose-600' -export function TitleIconBg({ id, className = '', children = }) { - return
{children}
+export function TitleIconBg({ img, id, className = '', children = }) { + if(img) return
+ {children} +
+ return
{children}
} export default function CardComponent({ diff --git a/src/components/bs-comp/chatComponent/ChatInput.tsx b/src/components/bs-comp/chatComponent/ChatInput.tsx index e4dda6e..35405d9 100644 --- a/src/components/bs-comp/chatComponent/ChatInput.tsx +++ b/src/components/bs-comp/chatComponent/ChatInput.tsx @@ -232,11 +232,11 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on } return
-
+
{/* form */} { formShow &&
-
+
{inputForm}
@@ -296,7 +296,7 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on } }} > -

内容由AI生成,仅供参考

+ {/*

内容由AI生成,仅供参考

*/}

{appConfig.dialogTips}

diff --git a/src/components/bs-comp/chatComponent/MessageBs.tsx b/src/components/bs-comp/chatComponent/MessageBs.tsx index f8961de..445a0b1 100644 --- a/src/components/bs-comp/chatComponent/MessageBs.tsx +++ b/src/components/bs-comp/chatComponent/MessageBs.tsx @@ -11,6 +11,17 @@ import remarkMath from "remark-math"; import MessageButtons from "./MessageButtons"; import SourceEntry from "./SourceEntry"; import { useMessageStore } from "./messageStore"; +import robot from "../../../assets/robot.png"; +import robotU from "../../../assets/robotU.png"; +import robot2 from "../../../assets/robot2.png"; +import robot3 from "../../../assets/robot3.png"; +import btnEdit from "../../../assets/chat/btn-edit.png"; +import btnReSend from "../../../assets/chat/btn-reSend.png"; +import btnDel from "../../../assets/chat/btn-del.png"; +import npcIcon from "../../../assets/npc/npcIcon.png"; +import nengliIcon from "../../../assets/npc/nengliIcon.png"; +import { TitleIconBg } from "../cardComponent"; +import Thumbs from "@/pages/ChatAppPage/components/Thumbs"; // 颜色列表 const colorList = [ @@ -76,27 +87,51 @@ export default function MessageBs({ data, onUnlike = () => { }, onSource }: { da } const chatId = useMessageStore(state => state.chatId) - + console.log(data) return
{data.sender &&

{data.sender}

} -
-
+
+ {/* {(data.flow_id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || data.flow_id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } + {data.flow_id == "ca214b41-2b73-4585-b172-bf1e546cf6ec" && } + {(data.flow_id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && data.flow_id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && data.flow_id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && } */} + {data.flow_id && } + +
+
+ {data.message.toString() ? mkdown : } + {/* @user */} + {data.receiver &&

@ {data.receiver.user_name}

} + {/* 光标 */} + {data.message.toString() && !data.end &&
} +
+ + {/* 赞 踩 */} + {!!data.id && data.end && + } +
+ {/*
{data.message.toString() ?
- {mkdown} + {mkdown} */} {/* @user */} - {data.receiver &&

@ {data.receiver.user_name}

} + {/* {data.receiver &&

@ {data.receiver.user_name}

} */} {/* 光标 */} {/* {data.message.toString() && !data.end &&
} */} -
+ {/*
:
} -
+
*/}
{/* 附加信息 */} - { + {/* { !!data.id && data.end &&
{ }, onSource }: { da onCopy={handleCopyMessage} >
- } + } */}
}; diff --git a/src/components/bs-comp/chatComponent/MessagePanne.tsx b/src/components/bs-comp/chatComponent/MessagePanne.tsx index 1b90706..3939f5d 100644 --- a/src/components/bs-comp/chatComponent/MessagePanne.tsx +++ b/src/components/bs-comp/chatComponent/MessagePanne.tsx @@ -56,7 +56,7 @@ export default function MessagePanne({ useName, guideWord, loadMore }) { return () => messagesRef.current?.removeEventListener('scroll', handleScroll) }, [messagesRef.current, messages, chatId]); - return
+ return
{guideWord && } diff --git a/src/components/bs-comp/chatComponent/MessageSystem.tsx b/src/components/bs-comp/chatComponent/MessageSystem.tsx index 6a719ae..df249bd 100644 --- a/src/components/bs-comp/chatComponent/MessageSystem.tsx +++ b/src/components/bs-comp/chatComponent/MessageSystem.tsx @@ -24,7 +24,7 @@ export default function MessageSystem({ data }) { () => ( data.thought && {data.thought.toString()} @@ -33,9 +33,10 @@ export default function MessageSystem({ data }) { ) const border = { system: 'border-slate-500', question: 'border-amber-500', processing: 'border-cyan-600', answer: 'border-lime-600', report: 'border-slate-500', guide: 'border-none' } + const style = { system: 'style-system', question: 'style-question', processing: 'border-cyan-600', answer: 'style-answer', report: 'style-system' } return
-
+
{logMkdown} {data.category === 'report' && handleCopy(e.target.parentNode)}>}
diff --git a/src/components/bs-comp/chatComponent/MessageUser.tsx b/src/components/bs-comp/chatComponent/MessageUser.tsx index 1f8635a..9524847 100644 --- a/src/components/bs-comp/chatComponent/MessageUser.tsx +++ b/src/components/bs-comp/chatComponent/MessageUser.tsx @@ -3,6 +3,9 @@ import { ChatMessageType } from "@/types/chat"; import { MagnifyingGlassIcon, Pencil2Icon, ReloadIcon } from "@radix-ui/react-icons"; import { useContext } from "react"; import { useMessageStore } from "./messageStore"; +import robotU from "../../../assets/robotU.png"; +import btnEdit from "../../../assets/chat/btn-edit.png"; +import btnReSend from "../../../assets/chat/btn-reSend.png"; export default function MessageUser({ useName, data }: { data: ChatMessageType }) { const msg = data.message[data.chatKey] @@ -25,16 +28,33 @@ export default function MessageUser({ useName, data }: { data: ChatMessageType } } return
-
+
+
+
+ {/* {chat.category === 'loading' && } */} + {msg} +
+ +
+ {!running && handleResend(false)} className="w-[28px] cursor-pointer" alt=""/>} + {!running && handleResend(true)} className="w-[28px] cursor-pointer" alt=""/>} + {/* */} + {/* {!showSearch && onSearch(chat.message[chat.chatKey])}>} */} +
+
+ {/*

{userName}

*/} + +
+ {/*
{useName &&

{useName}

}
{msg}
-
+
*/} {/* 附加信息 */} - { + {/* { // 数组类型的 data通常是文件上传消息,不展示附加按钮 !Array.isArray(data.message.data) &&
@@ -45,6 +65,6 @@ export default function MessageUser({ useName, data }: { data: ChatMessageType }
} -
+
*/}
}; diff --git a/src/components/bs-comp/chatComponent/RunLog.tsx b/src/components/bs-comp/chatComponent/RunLog.tsx index eaa5414..b199329 100644 --- a/src/components/bs-comp/chatComponent/RunLog.tsx +++ b/src/components/bs-comp/chatComponent/RunLog.tsx @@ -41,7 +41,7 @@ export default function RunLog({ data }) { return
setOpen(!open)}> -
+
{ data.end ? : @@ -50,7 +50,7 @@ export default function RunLog({ data }) {
-
+

{data.thought}

diff --git a/src/components/bs-comp/chatComponent/messageStore.ts b/src/components/bs-comp/chatComponent/messageStore.ts index 83b299b..0399039 100644 --- a/src/components/bs-comp/chatComponent/messageStore.ts +++ b/src/components/bs-comp/chatComponent/messageStore.ts @@ -26,8 +26,8 @@ type State = { } type Actions = { - loadHistoryMsg: (flowid: string, chatId: string) => Promise; - loadMoreHistoryMsg: (flowid: string) => Promise; + loadHistoryMsg: (flowid: string, chatId: string, flow_type: string) => Promise; + loadMoreHistoryMsg: (flowid: string, flow_type: string) => Promise; destory: () => void; createSendMsg: (inputs: any, inputKey?: string) => void; createWsMsg: (data: any) => void; @@ -81,20 +81,21 @@ export const useMessageStore = create((set, get) => ({ setShowGuideQuestion(bln: boolean) { set({ showGuideQuestion: bln }) }, - async loadHistoryMsg(flowid, chatId) { - const res = await getChatHistory(flowid, chatId, 30, 0) + async loadHistoryMsg(flowid, chatId, flow_type) { + console.log(111) + const res = await getChatHistory(flowid, chatId, 30, 0, flow_type) const msgs = handleHistoryMsg(res) currentChatId = chatId set({ historyEnd: false, messages: msgs.reverse() }) }, - async loadMoreHistoryMsg(flowid) { + async loadMoreHistoryMsg(flowid, flow_type) { if (get().running) return // 会话进行中禁止加载more历史 if (get().historyEnd) return // 没有更多历史纪录 const chatId = get().chatId const prevMsgs = get().messages // 最后一条消息id不存在,忽略 loadmore if (!prevMsgs[0]?.id) return - const res = await getChatHistory(flowid, chatId, 10, prevMsgs[0]?.id || 0) + const res = await getChatHistory(flowid, chatId, 10, prevMsgs[0]?.id || 0, flow_type) // 过滤非同一会话消息 if (res[0]?.chat_id !== currentChatId) { return console.warn('loadMoreHistoryMsg chatId not match, ignore') diff --git a/src/components/bs-comp/sheets/SkillChatSheet.tsx b/src/components/bs-comp/sheets/SkillChatSheet.tsx index 1ca75e4..36f5096 100644 --- a/src/components/bs-comp/sheets/SkillChatSheet.tsx +++ b/src/components/bs-comp/sheets/SkillChatSheet.tsx @@ -5,10 +5,20 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { useNavigate } from "react-router-dom"; import { SearchInput } from "../../bs-ui/input"; import { Sheet, SheetContent, SheetDescription, SheetTitle, SheetTrigger } from "../../bs-ui/sheet"; -import CardComponent from "../cardComponent"; +import CardComponent, { TitleIconBg } from "../cardComponent"; import { SkillIcon } from "@/components/bs-icons/skill"; import { AssistantIcon } from "@/components/bs-icons/assistant"; import { useTranslation } from "react-i18next"; +import borderR from "../../../assets/npc/border-r.png"; +import { SpotlightCard } from "@lobehub/ui"; +import { Flexbox } from 'react-layout-kit'; +import robot from "../../../assets/robot.png"; +import robot2 from "../../../assets/robot2.png"; +import robot3 from "../../../assets/robot3.png"; +import zidingyi1 from "../../../assets/npc/zidingyi1.png"; +import zidingyi2 from "../../../assets/npc/zidingyi2.png"; +import npcIcon from "../../../assets/npc/npcIcon.png"; +import nengliIcon from "../../../assets/npc/nengliIcon.png"; export default function SkillChatSheet({ children, onSelect }) { const [open, setOpen] = useState(false) @@ -32,19 +42,71 @@ export default function SkillChatSheet({ children, onSelect }) { return allDataRef.current.filter(el => el.name.toLowerCase().includes(keyword.toLowerCase())) }, [keyword]) + const render = (item: any) => ( + { onSelect(item); setOpen(false) }}> + {/* */} + {/* +
{item.name}
+
{item.name}
+
*/} + {/* onSelect(item)}> + + +
+ {item.name} +
+ {item.description} +
+
*/} +
+ + +
+ {/* */} + {(item.id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || item.id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } + {item.id == "ca214b41-2b73-4585-b172-bf1e546cf6ec" && } + {(item.id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && item.id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && item.id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && } +
+
+
+
+
+ {/* {(item.id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || item.id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } + {item.id == "ca214b41-2b73-4585-b172-bf1e546cf6ec" && } + {(item.id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && item.id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && item.id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && } */} + {/* */} + +
+

{item.name}

+
+ {/*
绘画类
+
绘画类
*/} +
+
+
+

{item.desc}

+
+ {item.flow_type === 'flow' ? '能力' : 'NPC'} +
+
+ ); + return {children} - +
e.stopPropagation()}> -
- {t('chat.dialogueSelection')} - {t('chat.chooseSkillOrAssistant')} - setKeyword(e.target.value)} /> +
+ {/* */}
-
- { +
+ 选择对话 + 选择一个您想使用的上线NPC或能力 + setKeyword(e.target.value)} /> +
+
+ {/* { options.length ? options.map((flow, i) => ( - {flow.flow_type === 'flow' ? '技能' : '助手'} + {flow.flow_type === 'flow' ? '技能' : 'NPC'} } onClick={() => { onSelect(flow); setOpen(false) }} @@ -64,7 +126,8 @@ export default function SkillChatSheet({ children, onSelect }) {

{t('build.empty')}

- } + } */} +
diff --git a/src/components/bs-comp/sheets/SkillSheet.tsx b/src/components/bs-comp/sheets/SkillSheet.tsx index 8fecfc6..27d8e03 100644 --- a/src/components/bs-comp/sheets/SkillSheet.tsx +++ b/src/components/bs-comp/sheets/SkillSheet.tsx @@ -19,6 +19,7 @@ import robot2 from "../../../assets/robot2.png"; import robot3 from "../../../assets/robot3.png"; import zidingyi1 from "../../../assets/npc/zidingyi1.png"; import zidingyi2 from "../../../assets/npc/zidingyi2.png"; +import borderR from "../../../assets/npc/border-r.png"; export default function SkillSheet({ select, children, onSelect }) { const [keyword, setKeyword] = useState(""); @@ -107,9 +108,12 @@ export default function SkillSheet({ select, children, onSelect }) { return ( {children} - +
e.stopPropagation()}> -
+
+ {/* */} +
+
{t("build.addSkill")} {children} - +
e.stopPropagation()}> +
+ {/* */} +
{t('build.addTool')}
@@ -67,7 +71,7 @@ export default function ToolsSheet({ select, onSelect, children }) { > {/* */} {type === "default" ? : } - 内置工具 + 内置工具
{type === "custom" ? : } {/* */} - 自定义工具 + 自定义工具
diff --git a/src/components/bs-ui/button/actionButton.tsx b/src/components/bs-ui/button/actionButton.tsx index 3080dcf..e43fdc7 100644 --- a/src/components/bs-ui/button/actionButton.tsx +++ b/src/components/bs-ui/button/actionButton.tsx @@ -14,14 +14,14 @@ export default function ActionButton({ ...props }) { - return
+ return
<> {buttonTipContent ? - + {buttonTipContent} @@ -34,10 +34,11 @@ export default function ActionButton({ - + {dropDown} diff --git a/src/components/bs-ui/input/index.tsx b/src/components/bs-ui/input/index.tsx index 633230b..1bc4b29 100644 --- a/src/components/bs-ui/input/index.tsx +++ b/src/components/bs-ui/input/index.tsx @@ -115,7 +115,7 @@ const InputList = React.forwardRef handleChange(e.target.value, item.id, index)} onInput={(e) => { diff --git a/src/components/bs-ui/select/index.tsx b/src/components/bs-ui/select/index.tsx index 9d77ecb..c65dde2 100644 --- a/src/components/bs-ui/select/index.tsx +++ b/src/components/bs-ui/select/index.tsx @@ -23,7 +23,7 @@ const SelectTrigger = React.forwardRef< span]:line-clamp-1 data-[placeholder]:text-gray-400", + "group flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-[#1a1a1a] px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 data-[placeholder]:text-gray-400", className )} {...props} diff --git a/src/components/bs-ui/sheet/index.tsx b/src/components/bs-ui/sheet/index.tsx index 139b76d..ef7d192 100644 --- a/src/components/bs-ui/sheet/index.tsx +++ b/src/components/bs-ui/sheet/index.tsx @@ -40,7 +40,7 @@ const sheetVariants = cva( "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom", left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm", right: - "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm", + "inset-y-0 right-0 h-full w-3/4 data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm", }, }, defaultVariants: { diff --git a/src/components/bs-ui/toast/toast.tsx b/src/components/bs-ui/toast/toast.tsx index dbceda4..bdf011c 100644 --- a/src/components/bs-ui/toast/toast.tsx +++ b/src/components/bs-ui/toast/toast.tsx @@ -99,7 +99,7 @@ const ToastTitle = React.forwardRef< >(({ className, ...props }, ref) => ( )) diff --git a/src/controllers/API/assistant.ts b/src/controllers/API/assistant.ts index b2f98eb..5c72313 100644 --- a/src/controllers/API/assistant.ts +++ b/src/controllers/API/assistant.ts @@ -22,8 +22,8 @@ export const getAssistantsApi = async (page, limit, name): Promise { - return await axios.post(`/api/v1/assistant`, { name, prompt, logo: '' }) +export const createAssistantsApi = async (name, prompt, avatar_img, avatar_color) => { + return await axios.post(`/api/v1/assistant`, { name, prompt, logo: '', avatar_img, avatar_color }) }; // 获取助手详情 diff --git a/src/controllers/API/flow.ts b/src/controllers/API/flow.ts index e42a571..e052ed4 100644 --- a/src/controllers/API/flow.ts +++ b/src/controllers/API/flow.ts @@ -203,7 +203,9 @@ export async function updateFlowApi( name: updatedFlow.name, data: updatedFlow.data, description: updatedFlow.description, - guide_word: updatedFlow.guide_word + guide_word: updatedFlow.guide_word, + avatar_img: updatedFlow.avatar_img, + avatar_color: updatedFlow.avatar_color, }); } diff --git a/src/controllers/API/index.ts b/src/controllers/API/index.ts index 4fd924d..950ec95 100644 --- a/src/controllers/API/index.ts +++ b/src/controllers/API/index.ts @@ -107,9 +107,9 @@ export function updateTempApi(temp_id, data) { * 获取知识库列表 * */ -export async function readFileLibDatabase(page = 1, pageSize = 40, name = '', parentId = '',type = '') { +export async function readFileLibDatabase(page = 1, pageSize = 40, name = '') { try { - const response: { data: any[], total: number } = await axios.get(`/api/v1/knowledge/?page_num=${page}&page_size=${pageSize}&name=${name}&parent_id=${parentId}&type=${type}`); + const response: { data: any[], total: number } = await axios.get(`/api/v1/knowledge/?page_num=${page}&page_size=${pageSize}&name=${name}`); // const { data, total } = response return response; } catch (error) { @@ -300,8 +300,38 @@ export const deleteChatApi = (chatId) => { * @param id flow_id chat_id - . * @returns {Promise} his data. */ -export async function getChatHistory(flowId: string, chatId: string, pageSize: number, id?: number): Promise { - return await axios.get(`/api/v1/chat/history?flow_id=${flowId}&chat_id=${chatId}&page_size=${pageSize}&id=${id || ''}`); +export interface MessageDB { + /** 场景 */ + category: string; + chat_id: string; + create_time: string; + extra: string; + /** 文件列表 */ + files: string; + flow_id: string; + id: number; + /** 日志 */ + intermediate_steps: string; + /** 机器人回复 */ + is_bot: boolean; + /** 已点赞 */ + liked: number; + /** 消息内容 */ + message: string; + receiver: null; + remark: null; + sender: string; + solved: number; + /** 有溯源 */ + source: number; + type: string; + update_time: string; + user_id: number; + flow_type: string; +} + +export async function getChatHistory(flowId: string, chatId: string, pageSize: number, id?: number, flow_type: string): Promise { + return await axios.get(`/api/v1/chat/history?flow_id=${flowId}&chat_id=${chatId}&page_size=${pageSize}&id=${id || ''}&flow_type=${flow_type}`); } /** @@ -335,9 +365,11 @@ export async function getVersion() { * */ export async function getBuildStatus( - flowId: string + flowId: string, + versionId?: number ): Promise { - return await axios.get(`/api/v1/build/${flowId}/status`); + const qstr = versionId ? `?version_id=${versionId}` : ""; + return await axios.get(`/api/v1/build/${flowId}/status${qstr}`); } //docs for postbuildinit @@ -347,11 +379,14 @@ export async function getBuildStatus( * @returns {Promise} A promise that resolves to an AxiosResponse containing the build status. * */ -export async function postBuildInit( - flow: FlowType, +export async function postBuildInit(data: { + flow: FlowType chatId?: string -): Promise { - return await axios.post(`/api/v1/build/init/${flow.id}`, chatId ? { chat_id: chatId } : flow); + versionId?: number +}): Promise { + const { flow, chatId, versionId } = data; + const qstr = versionId ? `?version_id=${versionId}` : '' + return await axios.post(`/api/v1/build/init/${flow.id}${qstr}`, chatId ? { chat_id: chatId } : flow); } // fetch(`/upload/${id}`, { diff --git a/src/controllers/request.ts b/src/controllers/request.ts index 04390f7..4cf45c9 100644 --- a/src/controllers/request.ts +++ b/src/controllers/request.ts @@ -1,7 +1,7 @@ +import { toast } from "@/components/bs-ui/toast/use-toast"; import axios from "axios"; - +import i18next from "i18next"; axios.defaults.withCredentials = true; - const customAxios = axios.create({ // 配置 }); @@ -23,7 +23,12 @@ customAxios.interceptors.response.use(function (response) { return Promise.reject(error); } // app 弹窗 - window.errorAlerts([error.message]) + toast({ + title: `${i18next.t('prompt')}`, + variant: 'error', + description: error.message + }) + // window.errorAlerts([error.message]) return Promise.reject(null); }) @@ -38,7 +43,11 @@ export function captureAndAlertRequestErrorHoc(apiFunc, iocFunc?) { console.log('error :>> ', error); iocFunc?.(error) // 弹窗 - window.errorAlerts([error]) + toast({ + title: `${i18next.t('prompt')}`, + variant: 'error', + description: typeof error === 'string' ? error : JSON.stringify(error) + }) console.error('逻辑异常 :>> ', error); return false }) diff --git a/src/layout/MainLayout.tsx b/src/layout/MainLayout.tsx index edb72a5..905ec43 100755 --- a/src/layout/MainLayout.tsx +++ b/src/layout/MainLayout.tsx @@ -29,7 +29,7 @@ export default function MainLayout() { }) } return
-
+
{/*

{t('title')}

*/}
-
+
window.location.href = window.location.href} FallbackComponent={CrashErrorComponent} diff --git a/src/pages/ChatAppPage/chatShare.tsx b/src/pages/ChatAppPage/chatShare.tsx index d679f60..cb6a27c 100644 --- a/src/pages/ChatAppPage/chatShare.tsx +++ b/src/pages/ChatAppPage/chatShare.tsx @@ -77,21 +77,35 @@ export default function chatShare() { setChatId(generateUUID(32)) }) }, [flowId]) - // select chat - const handleSelectChat = useDebounce(async (chat) => { - if (chat.chat_id === chatId) return + // select chat + const handleSelectChat = useDebounce(async (chat) => { + if (chat.chat_id === chatId) return - const flow = initFlow?.id === chat.flow_id ? initFlow : await getFlowApi(chat.flow_id) + const flow = initFlow?.id === chat.flow_id ? initFlow : await getFlowApi(chat.flow_id) - // if (!flow) { - // setInputState({ lock: true, errorCode: '1004' }) - // clearHistory() - // return setFace(false) - // } + // if (!flow) { + // setInputState({ lock: true, errorCode: '1004' }) + // clearHistory() + // return setFace(false) + // } + + setFlow(flow) + setChatId(chat.chat_id) + }, 100, false) + + const wsUrl = useMemo(() => { + const params = []; + + if (libId) params.push(`knowledge_id=${libId}`); + if (tweak) params.push(`tweak=${tweak}`); + + const paramStr = params.length > 0 ? `${params.join('&')}` : ''; + + return `/api/v2/chat/ws/${flowId}?type=L1&${paramStr}` + }, [libId, tweak]) + + const [data] = useState({ id: flowId, chatId: generateUUID(32), type: 'flow' }) - setFlow(flow) - setChatId(chat.chat_id) -}, 100, false) if (!flowId) return
请选择技能
return
@@ -127,13 +141,14 @@ export default function chatShare() {
*/} {/* chat */} - {flow + {/* {flow ?
{flow && }
:

{t('chat.selectChat')}

-
} +
} */} +
{/* {flow ? : null} */} {/* 选择对话技能 */} diff --git a/src/pages/ChatAppPage/components/ChatMessage.tsx b/src/pages/ChatAppPage/components/ChatMessage.tsx index 6ab58cd..ec45f12 100644 --- a/src/pages/ChatAppPage/components/ChatMessage.tsx +++ b/src/pages/ChatAppPage/components/ChatMessage.tsx @@ -235,23 +235,24 @@ export const ChatMessage = ({ chat, userName, disabledReSend, showSearch, onSour // if (chat.isSend) return chat.files.length ? <> // 发送消息 if (chat.isSend) return
-
-

{userName}

+
+
+
+ {chat.category === 'loading' && } + {chat.message[chat.chatKey]} +
+ +
+ {!disabledReSend && !disabledReSend && onEdit(chat.message[chat.chatKey])} className="w-[28px] cursor-pointer" alt=""/>} + {!disabledReSend && !disabledReSend && onReSend(chat.message[chat.chatKey])} className="w-[28px] cursor-pointer" alt=""/>} + {/* */} + {/* {!showSearch && onSearch(chat.message[chat.chatKey])}>} */} +
+
+ {/*

{userName}

*/}
-
-
- {chat.category === 'loading' && } - {chat.message[chat.chatKey]} -
- -
- {!disabledReSend && !disabledReSend && onEdit(chat.message[chat.chatKey])} className="w-[28px] cursor-pointer" alt=""/>} - {!disabledReSend && !disabledReSend && onReSend(chat.message[chat.chatKey])} className="w-[28px] cursor-pointer" alt=""/>} - {/* */} - {/* {!showSearch && onSearch(chat.message[chat.chatKey])}>} */} -
-
+
{/* 文件 */ } //
@@ -275,11 +276,12 @@ export const ChatMessage = ({ chat, userName, disabledReSend, showSearch, onSour {/*
*/} -
+
{(chat.flow_id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || chat.flow_id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } {chat.flow_id == "ca214b41-2b73-4585-b172-bf1e546cf6ec" && } {(chat.flow_id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && chat.flow_id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && chat.flow_id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && }

{userName}

+
{chat.sender &&
{chat.sender}
} handleDownloadFile(chat.files[0])}> @@ -295,33 +297,34 @@ export const ChatMessage = ({ chat, userName, disabledReSend, showSearch, onSour {/*
*/} -
+
{(chat.flow_id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || chat.flow_id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } {chat.flow_id == "ca214b41-2b73-4585-b172-bf1e546cf6ec" && } {(chat.flow_id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && chat.flow_id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && chat.flow_id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && } -

{userName}

+ {/*

{userName}

*/} +
+
+ {chat.message.toString() ? mkdown : } + {/* @user */} + {chat.receiver &&

@ {chat.receiver.user_name}

} + {/* 光标 */} + {chat.message.toString() && !chat.end &&
} +
+ + {/* 赞 踩 */} + {!!chat.id && chat.end && + // className={`absolute w-full left-0 bottom-[8px] justify-end pr-5`}> + } +
{/* {chat.sender &&
{chat.sender}
} */} -
-
- {chat.message.toString() ? mkdown : } - {/* @user */} - {chat.receiver &&

@ {chat.receiver.user_name}

} - {/* 光标 */} - {chat.message.toString() && !chat.end &&
} -
- - {/* 赞 踩 */} - {!!chat.id && chat.end && - // className={`absolute w-full left-0 bottom-[8px] justify-end pr-5`}> - } -
+ {chat.source !== SourceType.NONE && chat.end && sourceContent(chat.source)}
}; diff --git a/src/pages/ChatAppPage/components/ChatPanne.tsx b/src/pages/ChatAppPage/components/ChatPanne.tsx index cc28781..267a4d1 100644 --- a/src/pages/ChatAppPage/components/ChatPanne.tsx +++ b/src/pages/ChatAppPage/components/ChatPanne.tsx @@ -7,7 +7,7 @@ import { Button } from "../../../components/ui/button"; import { alertContext } from "../../../contexts/alertContext"; import { TabsContext } from "../../../contexts/tabsContext"; import { getChatHistory, postBuildInit, postValidatePrompt } from "../../../controllers/API"; -import { Variable } from "../../../controllers/API/flow"; +import { Variable, getFlowApi } from "../../../controllers/API/flow"; import { sendAllProps } from "../../../types/api"; import { ChatMessageType } from "../../../types/chat"; import { FlowType, NodeType } from "../../../types/flow"; @@ -25,208 +25,412 @@ import DialogueDetails from "./dialogueDetails"; import robot from "../../../assets/robot.png"; import robot2 from "../../../assets/robot2.png"; import robot3 from "../../../assets/robot3.png"; -import duihuaGengduo from "../../../assets/chat/duihua-gengduo.png"; -import duihuaSend from "../../../assets/chat/duihua-send.png"; +import xinjian1 from "../../../assets/chat/xinjian1.png"; +import xinjian2 from "../../../assets/chat/xinjian2.png"; +import npcIcon from "../../../assets/npc/npcIcon.png"; +import nengliIcon from "../../../assets/npc/nengliIcon.png"; -interface Iprops { - chatId: string - flow: FlowType - queryString?: string - version?: string -} +import { TitleIconBg } from "@/components/bs-comp/cardComponent"; +import ChatComponent from "@/components/bs-comp/chatComponent"; +import { useMessageStore } from "@/components/bs-comp/chatComponent/messageStore"; +import { AssistantIcon } from "@/components/bs-icons/assistant"; +import { NewApplicationIcon } from "@/components/bs-icons/newApplication"; +import { useToast } from "@/components/bs-ui/toast/use-toast"; +import { useAssistantStore } from "@/store/assistantStore"; -export default forwardRef(function ChatPanne({ chatId, flow, queryString, version = 'v1' }: Iprops,ref) { +export default function ChatPanne({ customWsHost = '', data }) { + const { id, chatId, type } = data const { t } = useTranslation() - const { tabsState } = useContext(TabsContext); - - const { isRoom, isForm, isReport, checkPrompt } = useFlowState(flow) + // const { tabsState } = useContext(TabsContext); + // const { isRoom, isForm, isReport, checkPrompt } = useFlowState(flow) + + const [flow, setFlow] = useState(null) + const flowRef = useRef(null) + const [assistant, setAssistant] = useState(null) + const { assistantState, loadAssistantState, destroy } = useAssistantStore() // build - const build = useBuild(flow, chatId) + // const build = useBuild(flow, chatId) + const build = useBuild() // 消息列表 - const { messages, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll } = useMessages(chatId, flow) - // ws通信 - const { stop, connectWS, begin: chating, checkReLinkWs, sendAll } = useWebsocket(chatId, flow, setChatHistory, queryString, version) - // 停止状态 - const [isStop, setIsStop] = useState(true) - // 输入框状态 - const { inputState, inputEmpty, inputDisabled, inputRef, - formShow, setFormShow, - setInputState, setInputEmpty, handleTextAreaHeight } = useInputState({ flow, chatId, chating, messages, isForm, isReport }) - - const { appConfig } = useContext(locationContext) - - // npc信息 - const [isNpcInfo, setIsNpcInfo] = useState(false) - - // 知识库引用信息 - const [isQuote, setIsQuote] = useState(false) - - // 完整对话记录 - const [isCompleteRecords, setIsCompleteRecords] = useState(false) - - // 数据内容 - const [isDataContent, setIsDataContent] = useState(false) - - // 对话详情 - const [isDialogueDetails, setIsDialogueDetails] = useState(false) - - // 开始构建&切换初始化会话 - const initChat = async () => { - await checkPrompt(flow) - await build() - const historyData = version === 'v1' ? await loadHistory() : (initGuide(), []) - await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) - setInputState({ lock: false, errorMsg: '' }); - // 第一条消息,用来初始化会话 - sendAll({ - chatHistory: messages, - name: flow.name, - description: flow.description, - inputs: {}, - flow_id: flow.id, - chat_id: chatId - }) - - changeHistoryByScroll.current = false - // 自动聚焦 - if (inputRef.current) inputRef.current.value = '' - setTimeout(() => { - inputRef.current?.focus() - }, 500); - - const isNewChat = historyData.length === 0 || historyData[0].id === 9999 - setFormShow(isNewChat && isForm) + // const { messages, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll } = useMessages(chatId, flow) + const { messages, loadHistoryMsg, loadMoreHistoryMsg, changeChatId } = useMessageStore() + useEffect(() => { + return destroy + }, []) + console.log(type) + const init = async () => { + if (type === 'flow') { + setAssistant(null) + const _flow = await getFlowApi(id) + await build(_flow, chatId) + loadHistoryMsg(_flow.id, chatId, type) + flowRef.current = _flow + setFlow(_flow) + changeChatId(chatId) // ws + } else { + flowRef.current = null + setFlow(null) + const _assistant = await loadAssistantState(id) + loadHistoryMsg(_assistant.id, chatId, type) + setAssistant(_assistant) + changeChatId(chatId) // ws + } } useEffect(() => { - initChat() - }, [flow]) + if (!id) { + flowRef.current = null + setFlow(null) + setAssistant(null) + return + } + init() + }, [data]) + + // ws 请求数据包装 + const { tabsState } = useContext(TabsContext); + // 依赖 chatId更新闭包,不依赖 flow + const getWsParamData = (action, msg) => { + if (type === 'flow') { + const _flow = flowRef.current + let inputs = tabsState[_flow.id].formKeysData.input_keys; + const input = inputs.find((el: any) => !el.type) + const inputKey = input ? Object.keys(input)[0] : ''; + const msgData = { + chatHistory: messages, + flow_id: _flow.id, + chat_id: chatId, + name: _flow.name, + description: _flow.description, + inputs: {} + } as any + if (msg) msgData.inputs = { ...input, [inputKey]: msg } + if (formDataRef.current?.length) { + msgData.inputs.data = formDataRef.current + formDataRef.current = null + } + if (action === 'continue') msgData.action = action + return [msgData, inputKey] + } else { + const inputKey = 'input'; + const msgData = { + chatHistory: messages, + flow_id: '', + chat_id: chatId, + name: assistant.name, + description: assistant.desc, + inputs: {} + } as any + if (msg) msgData.inputs = { [inputKey]: msg } + if (data) msgData.inputs.data = data + if (action === 'continue') msgData.action = action + return [msgData, inputKey] + } + } + + // 应用链接 + const { appConfig } = useContext(locationContext) + const token = localStorage.getItem("ws_token") || ''; + let wsUrl = type === 'flow' ? `${appConfig.websocketHost}/api/v1/chat/${flowRef.current?.id}?type=L1&t=${token}` : + `${location.host}/api/v1/assistant/chat/${assistant?.id}?t=${token}` + + if (customWsHost) { + wsUrl = `${appConfig.websocketHost}${customWsHost}&t=${token}` + } // sendmsg user name const sendUserName = useMemo(() => { + if (!flow) return '' const node = flow.data.nodes.find(el => el.data.type === 'AutoGenUser') return node?.data.node.template['name'].value || '' }, [flow]) - const handleSend = async () => { - const msg = inputRef.current?.value - setTimeout(() => { - if (inputRef.current) { - inputRef.current.value = '' - inputRef.current.style.height = 'auto' - } - setInputEmpty(true) - }, 100); + const flowSate = useMemo(() => { + if (!flow) return { isRoom: false, isForm: false, isReport: false } + // 是否群聊 + const isRoom = !!flow.data?.nodes.find(node => node.data.type === "AutoGenChain") + // 是否展示表单 + const isForm = !!flow.data?.nodes.find(node => ["VariableNode", "InputFileNode"].includes(node.data.type)) + // 是否报表 + const isReport = !!flow.data?.nodes.find(node => "Report" === node.data.type) + return { isRoom, isForm, isReport } + }, [flow]) - if (msg.trim() === '') return - - setInputState({ lock: true, errorMsg: '' }); - let inputs = tabsState[flow.id].formKeysData.input_keys; - const input = inputs.find((el: any) => !el.type) - const inputKey = input ? Object.keys(input)[0] : ''; - setChatHistory((old) => { - let newChat = cloneDeep(old); - newChat.push({ - isSend: true, - message: { ...input, [inputKey]: msg }, - chatKey: inputKey, - thought: '', - category: '', - files: [], - end: false, - user_name: "" - }) - return newChat - }); - - await checkReLinkWs(async () => { - // await build() - await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) - }) - - const chatInfo = { - chat_id: chatId, - flow_id: flow.id, - inputs: { ...input, [inputKey]: msg } - } - // @ts-ignore - isRoom && chating ? sendAll({ action: "continue", ...chatInfo }) - : sendAll({ - chatHistory: messages, - name: flow.name, - description: flow.description, - ...chatInfo - }); - } - - - // 报表请求 + // 发送表单 (提交-》event触发发送-》getWsParamData获取参数时追加 data) + const formDataRef = useRef(null) const sendReport = (items: Variable[], str) => { - let inputs = tabsState[flow.id].formKeysData.input_keys; - const input = inputs.find((el: any) => !el.type) - const inputKey = input ? Object.keys(input)[0] : ''; - setChatHistory((old) => { - let newChat = cloneDeep(old); - newChat.push({ - isSend: true, - message: { ...input, [inputKey]: str }, - chatKey: inputKey, - thought: '', - category: '', - files: [], - end: false, - user_name: "" - }) - return newChat - }); - const data = items.map(item => ({ + formDataRef.current = items.map(item => ({ id: item.nodeId, name: item.name, file_path: item.type === 'file' ? item.value : '', value: item.type === 'file' ? '' : item.value })) - setIsStop(false) - setFormShow(false) - - sendAll({ - inputs: { - ...input, - [inputKey]: str, - data - }, - chatHistory: messages, - name: flow.name, - description: flow.description, - chat_id: chatId, - flow_id: flow.id, + const myEvent = new CustomEvent('userResendMsgEvent', { + detail: { + send: true, + message: str + } }); + document.dispatchEvent(myEvent); } + // // ws通信 + // const { stop, connectWS, begin: chating, checkReLinkWs, sendAll } = useWebsocket(chatId, flow, setChatHistory, queryString, version) + // // 停止状态 + // const [isStop, setIsStop] = useState(true) + // // 输入框状态 + // const { inputState, inputEmpty, inputDisabled, inputRef, + // formShow, setFormShow, + // setInputState, setInputEmpty, handleTextAreaHeight } = useInputState({ flow, chatId, chating, messages, isForm, isReport }) - // 溯源 - const [souce, setSouce] = useState(null) + // const { appConfig } = useContext(locationContext) - const thumbRef = useRef(null) + // npc信息 + // const [isNpcInfo, setIsNpcInfo] = useState(false) - return
-
+ // // 知识库引用信息 + // const [isQuote, setIsQuote] = useState(false) + + // // 完整对话记录 + // const [isCompleteRecords, setIsCompleteRecords] = useState(false) + + // // 数据内容 + // const [isDataContent, setIsDataContent] = useState(false) + + // // 对话详情 + // const [isDialogueDetails, setIsDialogueDetails] = useState(false) + + // // 开始构建&切换初始化会话 + // const initChat = async () => { + // await checkPrompt(flow) + // await build() + // const historyData = version === 'v1' ? await loadHistory() : (initGuide(), []) + // await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) + // setInputState({ lock: false, errorMsg: '' }); + // // 第一条消息,用来初始化会话 + // sendAll({ + // chatHistory: messages, + // name: flow.name, + // description: flow.description, + // inputs: {}, + // flow_id: flow.id, + // chat_id: chatId + // }) + + // changeHistoryByScroll.current = false + // // 自动聚焦 + // if (inputRef.current) inputRef.current.value = '' + // setTimeout(() => { + // inputRef.current?.focus() + // }, 500); + + // const isNewChat = historyData.length === 0 || historyData[0].id === 9999 + // setFormShow(isNewChat && isForm) + // } + // useEffect(() => { + // initChat() + // }, [flow]) + + // // sendmsg user name + // const sendUserName = useMemo(() => { + // const node = flow.data.nodes.find(el => el.data.type === 'AutoGenUser') + // return node?.data.node.template['name'].value || '' + // }, [flow]) + + // const handleSend = async () => { + // const msg = inputRef.current?.value + // setTimeout(() => { + // if (inputRef.current) { + // inputRef.current.value = '' + // inputRef.current.style.height = 'auto' + // } + // setInputEmpty(true) + // }, 100); + + // if (msg.trim() === '') return + + // setInputState({ lock: true, errorMsg: '' }); + // let inputs = tabsState[flow.id].formKeysData.input_keys; + // const input = inputs.find((el: any) => !el.type) + // const inputKey = input ? Object.keys(input)[0] : ''; + // setChatHistory((old) => { + // let newChat = cloneDeep(old); + // newChat.push({ + // isSend: true, + // message: { ...input, [inputKey]: msg }, + // chatKey: inputKey, + // thought: '', + // category: '', + // files: [], + // end: false, + // user_name: "" + // }) + // return newChat + // }); + + // await checkReLinkWs(async () => { + // // await build() + // await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) + // }) + + // const chatInfo = { + // chat_id: chatId, + // flow_id: flow.id, + // inputs: { ...input, [inputKey]: msg } + // } + // // @ts-ignore + // isRoom && chating ? sendAll({ action: "continue", ...chatInfo }) + // : sendAll({ + // chatHistory: messages, + // name: flow.name, + // description: flow.description, + // ...chatInfo + // }); + // } + + + // // 报表请求 + // const sendReport = (items: Variable[], str) => { + // let inputs = tabsState[flow.id].formKeysData.input_keys; + // const input = inputs.find((el: any) => !el.type) + // const inputKey = input ? Object.keys(input)[0] : ''; + // setChatHistory((old) => { + // let newChat = cloneDeep(old); + // newChat.push({ + // isSend: true, + // message: { ...input, [inputKey]: str }, + // chatKey: inputKey, + // thought: '', + // category: '', + // files: [], + // end: false, + // user_name: "" + // }) + // return newChat + // }); + + // const data = items.map(item => ({ + // id: item.nodeId, + // name: item.name, + // file_path: item.type === 'file' ? item.value : '', + // value: item.type === 'file' ? '' : item.value + // })) + + // setIsStop(false) + // setFormShow(false) + + // sendAll({ + // inputs: { + // ...input, + // [inputKey]: str, + // data + // }, + // chatHistory: messages, + // name: flow.name, + // description: flow.description, + // chat_id: chatId, + // flow_id: flow.id, + // }); + // } + + // // 溯源 + // const [souce, setSouce] = useState(null) + + // const thumbRef = useRef(null) + if (!(flow || assistant)) return
+ +

选择一个 NPC 或 能力,开始对话吧 ~

+ { + !customWsHost &&
{ + document.getElementById('newchat')?.click() + }}> + + {/* */} + {t('chat.newChat')} +
+ } +
+ + return
+
+ {flow ? : } {/* */} - {(flow.id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || flow.id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } + {/* {(flow.id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || flow.id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } {flow.id == "ca214b41-2b73-4585-b172-bf1e546cf6ec" && } - {(flow.id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && flow.id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && flow.id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && } -

{flow.name}

+ {(flow.id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && flow.id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && flow.id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && } */} +

{flow ? flow.name : assistant.name}

{/*
3条记录
*/} {/*
模型列表
*/}
-
setIsNpcInfo(!isNpcInfo)}> - {/* */} -
+ {/*
setIsNpcInfo(!isNpcInfo)}> + +
*/}
-
+
+ {/* 技能会话 */} + { + flow &&
+ {/* {flow && } */} + {/*
+ + {flow.name} +
*/} + loadMoreHistoryMsg(flow.id)} + inputForm={flowSate.isForm ? : null} + /> + {/*
+ { + messages.map((c, i) => setSouce(c)} + onDislike={(chatId) => { thumbRef.current?.openModal(chatId) }} + onReSend={(msg) => { + inputRef.current.value = msg + handleSend() + }} + onEdit={(msg) => { inputRef.current.value = msg; setInputEmpty(!msg) }} + onSearch={(msg) => window.open(appConfig.dialogQuickSearch + encodeURIComponent(msg))} + >) + } +
*/} +
+ } + {/* 助手会话 */} + { + assistant &&
+ {/* {flow && } */} + {/*
+ + {assistant.name} +
*/} + item)} + guideWord={assistantState.guide_word} + wsUrl={wsUrl} + onBeforSend={getWsParamData} + loadMore={() => loadMoreHistoryMsg(assistant.id)} + inputForm={null} + /> +
+ } {/* 会话记录 */} -
+ {/*
{ messages.map((c, i) => window.open(appConfig.dialogQuickSearch + encodeURIComponent(msg))} >) } -
+
*/} {/* 输入框 */} - {version != "v3" &&
- {/*
*/} + {/* {version != "v3" &&
- {/* - - */}
@@ -270,591 +469,47 @@ export default forwardRef(function ChatPanne({ chatId, flow, queryString, versio {inputState.errorMsg &&
{inputState.errorMsg}
}

{appConfig.dialogTips}

-
} +
} */}
- {(isRoom || isReport) &&
+ {/* {(isRoom || isReport) &&
-
} +
} */} {/* 源文件类型 */} - setSouce(null)}> + {/* setSouce(null)}> */} {/* 表单 */} - {isForm && formShow && } + {/* {isForm && formShow && } */} {/* 踩 反馈 */} - + {/* */} - + {/* */} - + {/* */} - + {/* */} - + {/* */} - + {/* */}
-}); -/** - * 输入框状态 - * 分析 flow状态 - * return 该技能含有表单、有报表、群聊 - * @returns - */ -const useInputState = ({ flow, chatId, chating, messages, isForm, isReport }) => { - const { tabsState } = useContext(TabsContext); +}; - const [inputState, setInputState] = useState({ - lock: false, - errorMsg: '' - }) - // 输入问答 - const inputRef = useRef(null) - useEffect(() => { - !chating && setTimeout(() => { - // 对话结束自动聚焦 - inputRef.current?.focus() - }, 1000); - }, [chating]) - // input 滚动 - const [inputEmpty, setInputEmpty] = useState(true) - useEffect(() => { - setInputEmpty(true) - if (inputRef.current) inputRef.current.value = '' - }, [chatId]) - - // 获取上传file input - const fileInputs = useMemo(() => { - return tabsState[flow.id]?.formKeysData?.input_keys?.filter((input: any) => input.type === 'file') - }, [tabsState, flow]) - - const handleTextAreaHeight = (e) => { - const textarea = e.target - textarea.style.height = 'auto' - textarea.style.height = textarea.scrollHeight + 'px' - setInputEmpty(textarea.value.trim() === '') - } - // input disabled - const inputDisabled = useMemo(() => { - return inputState.lock - // 表单 && 没回话或只有一个引导词 - || (isForm && (messages.length === 0 || (messages.length === 1 && messages[0].id === 9999))) - || isReport - }, [inputState, fileInputs, isReport]) - - // 表单收起 - const [formShow, setFormShow] = useState(true) - return { - inputState, inputEmpty, inputDisabled, inputRef, - formShow, setFormShow, - setInputState, setInputEmpty, handleTextAreaHeight - } -} - -/** - * flow state - * 分析 flow状态 - * return 该技能含有表单、有报表、群聊 - * @returns - */ -const useFlowState = (flow: FlowType) => { - const flowSate = useMemo(() => { - // 是否群聊 - const isRoom = !!flow.data?.nodes.find(node => node.data.type === "AutoGenChain") - // 是否展示表单 - const isForm = !!flow.data?.nodes.find(node => ["VariableNode", "InputFileNode"].includes(node.data.type)) - // 是否报表 - const isReport = !!flow.data?.nodes.find(node => "Report" === node.data.type) - return { isRoom, isForm, isReport } - }, [flow]) - - // propmt类型补充自定义字段 - const checkPrompt = async (_flow) => { - const params = _flow.data.nodes.map(node => { - const temps = [] - const temp = node.data.node.template - Object.keys(temp).map(key => { - const { type, value } = temp[key] - if (type === 'prompt' && !!value) !temps.length && temps.push({ name: key, template: value, data: node.data }) - }) - return temps - }).flat() - - const promises = params.map(param => { - return postValidatePrompt(param.name, param.template, param.data.node).then(res => { - if (res) param.data.node = res.frontend_node - }) - }) - return Promise.all(promises) - } - - return { ...flowSate, checkPrompt } -} - -/** - * 消息列表模块 - * 翻页、追加、历史 - * @returns - */ -const useMessages = (chatId, flow) => { - const [chatHistory, setChatHistory] = useState([]); - const lastIdRef = useRef(0) - // 控制开启自动随消息滚动(临时方案) - const changeHistoryByScroll = useRef(false) - - const loadIdRef = useRef('') // 记录最后一个加载的 chatId - // 获取聊天记录 - const loadHistory = async (lastId?: number) => { - loadIdRef.current = chatId - - const res = await getChatHistory(flow.id, chatId, lastId ? 10 : 30, lastId) - const hisData = res.map(item => { - // let count = 0 - let { message, files, is_bot, intermediate_steps, ...other } = item - try { - message = message && message[0] === '{' ? JSON.parse(message.replace(/([\t\n"])/g, '\\$1').replace(/'/g, '"')) : message || '' - } catch (e) { - // 未考虑的情况暂不处理 - } - return { - ...other, - chatKey: typeof message === 'string' ? undefined : Object.keys(message)[0], - end: true, - files: files ? JSON.parse(files) : [], - isSend: !is_bot, - message, - thought: intermediate_steps, - noAccess: true - } - }) - lastIdRef.current = hisData[hisData.length - 1]?.id || lastIdRef.current || 0 // 记录最后一个id - - let historyData = [] - if (lastId) { - historyData = [...hisData.reverse(), ...chatHistory] - } else if (loadIdRef.current === chatId) { // 保证同一会话 - historyData = hisData.reverse() - } - setChatHistory(historyData) - const pageSize = historyData.length < 30 ? 30 : 10 // 先偷懒 - if (hisData.length < pageSize) initGuide() - return historyData - } - - const loadLock = useRef(false) - const currentIdRef = useRef(0) - const loadNextPage = async () => { - if (loadLock.current) return - if (currentIdRef.current === lastIdRef.current) return // 最后一个相同表示聊天记录已到顶 - loadLock.current = true - currentIdRef.current = lastIdRef.current - changeHistoryByScroll.current = true - await loadHistory(currentIdRef.current) - loadLock.current = false - // 滚动 hack TODO 滚动翻页设计 - setTimeout(() => { - changeHistoryByScroll.current = false - }, 500); - } - - const initGuide = () => { - const guideMsg = { - "category": "system", - "chat_id": chatId, - "end": true, - "create_time": "", - "extra": "{}", - "files": [], - "flow_id": flow.id, - "id": 9999, - "thought": flow.guide_word, - "is_bot": true, - "liked": 0, - "message": '', - "receiver": null, - "remark": null, - "sender": "", - "solved": 0, - isSend: false, - "source": 0, - "type": "end", - "update_time": "", - noAccess: true, - "user_id": 0 - } - flow.guide_word && setChatHistory((chatHistory) => - chatHistory[0]?.id === 9999 ? chatHistory : [guideMsg, ...chatHistory] - ) - } - - // 消息滚动 - const messagesRef = useRef(null); - useEffect(() => { - if (messagesRef.current) { // 滚动加载不触发 - // if (messagesRef.current && !changeHistoryByScroll.current) { // 滚动加载不触发 - console.log(1,messagesRef,changeHistoryByScroll) - setTimeout(() => { - messagesRef.current.scrollTop = messagesRef.current.scrollHeight; - }, 100); - } - }, [chatHistory, changeHistoryByScroll]); - - // 消息滚动加载 - useEffect(() => { - function handleScroll() { - if (messagesRef.current.scrollTop <= 30) { - loadNextPage() - } - } - - messagesRef.current?.addEventListener('scroll', handleScroll); - return () => messagesRef.current?.removeEventListener('scroll', handleScroll) - }, [messagesRef.current, chatHistory, chatId]); - - return { - messages: chatHistory, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll - } -} - -/** - * websocket 通信 - * 建立连接、重连、断开、接收、发送 - * @returns - */ -const useWebsocket = (chatId, flow, setChatHistory, queryString, version) => { - const ws = useRef(null); - // 接收ws状态 - const [begin, setBegin] = useState(false) - const { setErrorData } = useContext(alertContext); - const { t } = useTranslation() - - const { appConfig } = useContext(locationContext) - - const chatIdRef = useRef(chatId); - useEffect(() => { - chatIdRef.current = chatId; - }, [chatId]) - - function heartbeat() { - if (!ws.current) return; - if (ws.current.readyState !== 1) return; - ws.current.send("heartbeat"); - setTimeout(heartbeat, 30000); - } - - function getWebSocketUrl(flowId, isDevelopment = false) { - const token = localStorage.getItem("ws_token") || ''; - - const isSecureProtocol = window.location.protocol === "https:"; - const webSocketProtocol = isSecureProtocol ? "wss" : "ws"; - const host = appConfig.websocketHost || window.location.host // isDevelopment ? "localhost:7860" : window.location.host; - const chatEndpoint = version === 'v1' ? `/api/v1/chat/${flowId}?type=L1&chat_id=${chatId}&t=${token}` - : `/api/v2/chat/ws/${flowId}?type=L1&chat_id=${chatId}${queryString}&t=${token}` - - return `${webSocketProtocol}://${host}${chatEndpoint}`; - } - - const newChatStart = useRef(false) // 处理当前会话上下文丢失,阻止上一次打字机效果 - // 自动重连次数 - const tryReLinkCount = useRef(0) - const reConnect = (params) => { - if (tryReLinkCount.current <= 3) { - connectWS(params) - tryReLinkCount.current++ - } else { - console.warn('超过最大重试次数 :>> '); - } - } - useEffect(() => { - tryReLinkCount.current = 0 - newChatStart.current = true - }, [chatId]) - - function connectWS(params) { - const { setInputState, setIsStop, changeHistoryByScroll } = params - if (ws.current) return Promise.resolve('ok'); - - // 连接断开重链接 - return new Promise((res, rej) => { - try { - const urlWs = getWebSocketUrl( - flow.id, - process.env.NODE_ENV === "development" - ); - const newWs = new WebSocket(urlWs); - newWs.onopen = () => { - console.log("WebSocket connection established!"); - res('ok') - // heartbeat() - }; - newWs.onmessage = (event) => { - const data = JSON.parse(event.data); - if (data.chat_id !== chatIdRef.current) return - console.log('newChatStart.current :>> ', newChatStart.current); - - const errorMsg = data.category === 'error' ? data.intermediate_steps : '' - - if (newChatStart.current) { - if (data.type === 'close') { - newChatStart.current = false - return setInputState({ lock: false, errorMsg }) - } else { - return setInputState({ lock: true, errorMsg }) - } - } - // 异常类型处理,提示 - if (errorMsg) return setInputState({ lock: true, errorMsg }) - - handleWsMessage({ data, setIsStop, setInputState, changeHistoryByScroll }); - // get chat history - // 群聊@自己时,开启input - if (data.type === 'end' && data.receiver?.is_self) { - setInputState({ lock: false, errorMsg: '' }) - } - }; - newWs.onclose = (event) => { - ws.current = null - - handleOnClose({ event, setIsStop, setInputState }); - // reConnect(params) - }; - newWs.onerror = (ev) => { - ws.current = null - - console.error('链接异常error', ev); - setIsStop(true) - - setErrorData({ - title: `${t('chat.networkError')}:`, - list: [ - t('chat.networkErrorList1'), - t('chat.networkErrorList2'), - t('chat.networkErrorList3') - ], - }); - reConnect(params) - }; - ws.current = newWs; - console.log('newWs :>> ', newWs); - } catch (error) { - console.error('创建链接异常', error); - rej(error) - } - }) - } - - var isStream = false; - function handleWsMessage({ data, setIsStop, setInputState, changeHistoryByScroll }) { - if (Array.isArray(data) && data.length) return - if (data.type === "begin") { - setBegin(true) - setIsStop(false) - changeHistoryByScroll.current = false - } - if (data.type === "close") { - setBegin(false) - setIsStop(true) - setInputState({ lock: false, errorMsg: '' }); - changeHistoryByScroll.current = true - } - if (data.type === "start") { - setChatHistory((old) => { - let newChat = cloneDeep(old); - newChat.push({ - isSend: false, - message: '', - chatKey: '', - thought: data.intermediate_steps || '', - category: data.category || '', - files: [], - end: false - }) - return newChat - }); - isStream = true; - } - if (data.type === "stream" && isStream) { - updateLastMessage({ str: data.message, thought: data.intermediate_steps }); - } - if (data.type === "end") { - updateLastMessage({ - ...data, - str: data.message, - files: data.files || null, - end: true, - thought: data.intermediate_steps || '', - cate: data.category || '', - messageId: data.message_id, - noAccess: false, - liked: 0 - }); - - isStream = false; - } - } - - function updateLastMessage({ str, thought = '', end = false, files = [], cate = '', messageId = 0, source = false, noAccess = false, ...data }: { - str: string; - messageId?: number - thought?: string; - cate?: string; - end?: boolean; - files?: Array; - source?: boolean - noAccess?: boolean - }) { - setChatHistory((old) => { - const newChats = [...old] - // console.log('newchats :>> ', newChats); - let chatsLen = newChats.length - const prevChat = newChats[chatsLen - 2] - // hack 过滤重复最后消息 - if (end - && str - && chatsLen > 1 - && str === prevChat.message - // && data.sender === prevChat.sender - && !prevChat.thought) { - newChats.splice(chatsLen - 2, 1) // 删上一条 - chatsLen = newChats.length - } - // 更新 - const lastChat = newChats[chatsLen - 1] - const newLastChat = { - ...newChats[chatsLen - 1], - ...data, - id: messageId, - message: lastChat.message + str, - thought: lastChat.thought + (thought ? `${thought}\n` : ''), - files, - category: cate, - source, - noAccess, - end - } - newChats[chatsLen - 1] = newLastChat - // start - end 之间没有内容删除load - if (end && !(newLastChat.files.length || newLastChat.thought || newLastChat.message)) { - newChats.pop() - } - return newChats; - }); - } - - // 发送ws - async function sendAll(data: sendAllProps) { - try { - if (ws.current) { - if (JSON.stringify(data.inputs) !== '{}') { - newChatStart.current = false - } - ws.current.send(JSON.stringify(data)); - } - } catch (error) { - setErrorData({ - title: "There was an error sending the message", - list: [error.message], - }); - } - } - - // 处理主动断开 - function handleOnClose({ event, setIsStop, setInputState }) { - console.error('链接手动断开 event :>> ', event); - setIsStop(true) - setBegin(false) - - if ([1005, 1008].includes(event.code)) { - console.warn('即将废弃 :>> '); - setInputState({ lock: true, errorMsg: event.reason }); - } else { - if (event.reason) { - setErrorData({ title: event.reason }); - // setChatHistory((old) => { - // let newChat = cloneDeep(old); - // if (newChat.length) { - // newChat[newChat.length - 1].end = true; - // } - // newChat.push({ end: true, message: `${t('chat.connectionbreakTip')}${event.reason}`, isSend: false, chatKey: '', files: [] }); - // return newChat - // }) - } - setInputState({ lock: false, errorMsg: '' }); - } - } - - useEffect(() => { - // destory - return () => { - // close prev connection - if (ws.current) { - switch (ws.current.readyState) { - case WebSocket.OPEN: - console.warn('前端主动关闭1') - ws.current.close() - ; break; - case WebSocket.CONNECTING: - ws.current.onopen = () => { - console.warn('前端主动关闭2') - ws.current.close() - }; - } - ws.current = null - } - } - }, []) - - // 检测并重连 - const checkReLinkWs = async (reConnect) => { - if (ws.current) return true - // 重连 - // 上一条加loading - setChatHistory((old) => { - let newChat = [...old]; - newChat[newChat.length - 1].category = 'loading'; - return newChat; - }); - await reConnect() - // 链接成功 - // 上一条去loading - setChatHistory((old) => { - let newChat = [...old]; - newChat[newChat.length - 1].category = ''; - return newChat; - }); - } - - const handleStop = () => { - try { - if (ws) { - ws.current.send(JSON.stringify({ - "action": "stop" - })); - } - } catch (error) { - setErrorData({ - title: "There was an error stop the message", - list: [error.message], - }); - } - } - - return { begin, stop: handleStop, checkReLinkWs, sendAll, connectWS } -} /** * build flow * 校验每个节点,展示进度及结果;返回input_keys;end_of_stream断开链接 * 主要校验节点并设置更新setTabsState的 formKeysData - * @returns */ -const useBuild = (flow: FlowType, chatId: string) => { - const { setErrorData } = useContext(alertContext); + +const useBuild = () => { + const { toast } = useToast() const { setTabsState } = useContext(TabsContext); const { t } = useTranslation() // SSE 服务端推送 async function streamNodeData(flow: FlowType, chatId: string) { // Step 1: Make a POST request to send the flow data and receive a unique session ID - const { flowId } = await postBuildInit(flow, chatId); + console.log(flow,chatId) + const { flowId } = await postBuildInit({ flow, chatId }); // Step 2: Use the session ID to establish an SSE connection using EventSource let validationResults = []; let finished = false; @@ -897,7 +552,11 @@ const useBuild = (flow: FlowType, chatId: string) => { eventSource.close(); if (error.data) { const parsedData = JSON.parse(error.data); - setErrorData({ title: parsedData.error }); + toast({ + title: parsedData.error, + variant: 'error', + description: '' + }); } }; // Step 3: Wait for the stream to finish @@ -922,15 +581,15 @@ const useBuild = (flow: FlowType, chatId: string) => { } } - async function handleBuild() { + async function handleBuild(flow: FlowType, chatId: string) { try { const errors = flow.data.nodes.flatMap((n: NodeType) => validateNode(n, flow.data.edges)) if (errors.length > 0) { - setErrorData({ + return toast({ title: t('chat.buildError'), - list: errors, + variant: 'error', + description: errors }); - return; } const minimumLoadingTime = 200; // in milliseconds diff --git a/src/pages/ChatAppPage/components/ChatPanne1 copy.tsx b/src/pages/ChatAppPage/components/ChatPanne1 copy.tsx new file mode 100644 index 0000000..cc28781 --- /dev/null +++ b/src/pages/ChatAppPage/components/ChatPanne1 copy.tsx @@ -0,0 +1,948 @@ +import cloneDeep from "lodash-es/cloneDeep"; +import { ClipboardList, FileInput, FileText, Send, StopCircle } from "lucide-react"; +import { forwardRef, useContext, useEffect, useMemo, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import ShadTooltip from "../../../components/ShadTooltipComponent"; +import { Button } from "../../../components/ui/button"; +import { alertContext } from "../../../contexts/alertContext"; +import { TabsContext } from "../../../contexts/tabsContext"; +import { getChatHistory, postBuildInit, postValidatePrompt } from "../../../controllers/API"; +import { Variable } from "../../../controllers/API/flow"; +import { sendAllProps } from "../../../types/api"; +import { ChatMessageType } from "../../../types/chat"; +import { FlowType, NodeType } from "../../../types/flow"; +import { validateNode } from "../../../utils"; +import { ChatMessage } from "./ChatMessage"; +import ChatReportForm from "./ChatReportForm"; +import ResouceModal from "./ResouceModal"; +import ThumbsMessage from "./ThumbsMessage"; +import NpcInfo from "./NpcInfo"; +import Quote from "./quote"; +import { locationContext } from "../../../contexts/locationContext"; +import CompleteRecords from "./completeRecords"; +import DataContent from "./dataContent"; +import DialogueDetails from "./dialogueDetails"; +import robot from "../../../assets/robot.png"; +import robot2 from "../../../assets/robot2.png"; +import robot3 from "../../../assets/robot3.png"; +import duihuaGengduo from "../../../assets/chat/duihua-gengduo.png"; +import duihuaSend from "../../../assets/chat/duihua-send.png"; + +interface Iprops { + chatId: string + flow: FlowType + queryString?: string + version?: string +} + +export default forwardRef(function ChatPanne({ chatId, flow, queryString, version = 'v1' }: Iprops,ref) { + const { t } = useTranslation() + const { tabsState } = useContext(TabsContext); + + const { isRoom, isForm, isReport, checkPrompt } = useFlowState(flow) + + // build + const build = useBuild(flow, chatId) + // 消息列表 + const { messages, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll } = useMessages(chatId, flow) + // ws通信 + const { stop, connectWS, begin: chating, checkReLinkWs, sendAll } = useWebsocket(chatId, flow, setChatHistory, queryString, version) + // 停止状态 + const [isStop, setIsStop] = useState(true) + // 输入框状态 + const { inputState, inputEmpty, inputDisabled, inputRef, + formShow, setFormShow, + setInputState, setInputEmpty, handleTextAreaHeight } = useInputState({ flow, chatId, chating, messages, isForm, isReport }) + + const { appConfig } = useContext(locationContext) + + // npc信息 + const [isNpcInfo, setIsNpcInfo] = useState(false) + + // 知识库引用信息 + const [isQuote, setIsQuote] = useState(false) + + // 完整对话记录 + const [isCompleteRecords, setIsCompleteRecords] = useState(false) + + // 数据内容 + const [isDataContent, setIsDataContent] = useState(false) + + // 对话详情 + const [isDialogueDetails, setIsDialogueDetails] = useState(false) + + // 开始构建&切换初始化会话 + const initChat = async () => { + await checkPrompt(flow) + await build() + const historyData = version === 'v1' ? await loadHistory() : (initGuide(), []) + await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) + setInputState({ lock: false, errorMsg: '' }); + // 第一条消息,用来初始化会话 + sendAll({ + chatHistory: messages, + name: flow.name, + description: flow.description, + inputs: {}, + flow_id: flow.id, + chat_id: chatId + }) + + changeHistoryByScroll.current = false + // 自动聚焦 + if (inputRef.current) inputRef.current.value = '' + setTimeout(() => { + inputRef.current?.focus() + }, 500); + + const isNewChat = historyData.length === 0 || historyData[0].id === 9999 + setFormShow(isNewChat && isForm) + } + useEffect(() => { + initChat() + }, [flow]) + + // sendmsg user name + const sendUserName = useMemo(() => { + const node = flow.data.nodes.find(el => el.data.type === 'AutoGenUser') + return node?.data.node.template['name'].value || '' + }, [flow]) + + const handleSend = async () => { + const msg = inputRef.current?.value + setTimeout(() => { + if (inputRef.current) { + inputRef.current.value = '' + inputRef.current.style.height = 'auto' + } + setInputEmpty(true) + }, 100); + + if (msg.trim() === '') return + + setInputState({ lock: true, errorMsg: '' }); + let inputs = tabsState[flow.id].formKeysData.input_keys; + const input = inputs.find((el: any) => !el.type) + const inputKey = input ? Object.keys(input)[0] : ''; + setChatHistory((old) => { + let newChat = cloneDeep(old); + newChat.push({ + isSend: true, + message: { ...input, [inputKey]: msg }, + chatKey: inputKey, + thought: '', + category: '', + files: [], + end: false, + user_name: "" + }) + return newChat + }); + + await checkReLinkWs(async () => { + // await build() + await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) + }) + + const chatInfo = { + chat_id: chatId, + flow_id: flow.id, + inputs: { ...input, [inputKey]: msg } + } + // @ts-ignore + isRoom && chating ? sendAll({ action: "continue", ...chatInfo }) + : sendAll({ + chatHistory: messages, + name: flow.name, + description: flow.description, + ...chatInfo + }); + } + + + // 报表请求 + const sendReport = (items: Variable[], str) => { + let inputs = tabsState[flow.id].formKeysData.input_keys; + const input = inputs.find((el: any) => !el.type) + const inputKey = input ? Object.keys(input)[0] : ''; + setChatHistory((old) => { + let newChat = cloneDeep(old); + newChat.push({ + isSend: true, + message: { ...input, [inputKey]: str }, + chatKey: inputKey, + thought: '', + category: '', + files: [], + end: false, + user_name: "" + }) + return newChat + }); + + const data = items.map(item => ({ + id: item.nodeId, + name: item.name, + file_path: item.type === 'file' ? item.value : '', + value: item.type === 'file' ? '' : item.value + })) + + setIsStop(false) + setFormShow(false) + + sendAll({ + inputs: { + ...input, + [inputKey]: str, + data + }, + chatHistory: messages, + name: flow.name, + description: flow.description, + chat_id: chatId, + flow_id: flow.id, + }); + } + + // 溯源 + const [souce, setSouce] = useState(null) + + const thumbRef = useRef(null) + + return
+
+
+ {/* */} + {(flow.id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || flow.id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } + {flow.id == "ca214b41-2b73-4585-b172-bf1e546cf6ec" && } + {(flow.id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && flow.id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && flow.id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && } +

{flow.name}

+ {/*
3条记录
*/} + {/*
模型列表
*/} +
+
setIsNpcInfo(!isNpcInfo)}> + {/* */} +
+
+
+ {/* 会话记录 */} +
+ { + messages.map((c, i) => setSouce(c)} + onDislike={(chatId) => { thumbRef.current?.openModal(chatId) }} + onReSend={(msg) => { + inputRef.current.value = msg + handleSend() + }} + onEdit={(msg) => { inputRef.current.value = msg; setInputEmpty(!msg) }} + onSearch={(msg) => window.open(appConfig.dialogQuickSearch + encodeURIComponent(msg))} + >) + } +
+ {/* 输入框 */} + {version != "v3" &&
+ {/*
*/} +
+ +
+ {/* + + */} +
+ +
+
+ {inputState.errorMsg &&
{inputState.errorMsg}
} +
+

{appConfig.dialogTips}

+
} +
+ {(isRoom || isReport) &&
+ +
} + {/* 源文件类型 */} + setSouce(null)}> + {/* 表单 */} + {isForm && formShow && } + {/* 踩 反馈 */} + + + + + + + + + + + +
+}); +/** + * 输入框状态 + * 分析 flow状态 + * return 该技能含有表单、有报表、群聊 + * @returns + */ +const useInputState = ({ flow, chatId, chating, messages, isForm, isReport }) => { + const { tabsState } = useContext(TabsContext); + + const [inputState, setInputState] = useState({ + lock: false, + errorMsg: '' + }) + // 输入问答 + const inputRef = useRef(null) + useEffect(() => { + !chating && setTimeout(() => { + // 对话结束自动聚焦 + inputRef.current?.focus() + }, 1000); + }, [chating]) + // input 滚动 + const [inputEmpty, setInputEmpty] = useState(true) + useEffect(() => { + setInputEmpty(true) + if (inputRef.current) inputRef.current.value = '' + }, [chatId]) + + // 获取上传file input + const fileInputs = useMemo(() => { + return tabsState[flow.id]?.formKeysData?.input_keys?.filter((input: any) => input.type === 'file') + }, [tabsState, flow]) + + const handleTextAreaHeight = (e) => { + const textarea = e.target + textarea.style.height = 'auto' + textarea.style.height = textarea.scrollHeight + 'px' + setInputEmpty(textarea.value.trim() === '') + } + // input disabled + const inputDisabled = useMemo(() => { + return inputState.lock + // 表单 && 没回话或只有一个引导词 + || (isForm && (messages.length === 0 || (messages.length === 1 && messages[0].id === 9999))) + || isReport + }, [inputState, fileInputs, isReport]) + + // 表单收起 + const [formShow, setFormShow] = useState(true) + return { + inputState, inputEmpty, inputDisabled, inputRef, + formShow, setFormShow, + setInputState, setInputEmpty, handleTextAreaHeight + } +} + +/** + * flow state + * 分析 flow状态 + * return 该技能含有表单、有报表、群聊 + * @returns + */ +const useFlowState = (flow: FlowType) => { + const flowSate = useMemo(() => { + // 是否群聊 + const isRoom = !!flow.data?.nodes.find(node => node.data.type === "AutoGenChain") + // 是否展示表单 + const isForm = !!flow.data?.nodes.find(node => ["VariableNode", "InputFileNode"].includes(node.data.type)) + // 是否报表 + const isReport = !!flow.data?.nodes.find(node => "Report" === node.data.type) + return { isRoom, isForm, isReport } + }, [flow]) + + // propmt类型补充自定义字段 + const checkPrompt = async (_flow) => { + const params = _flow.data.nodes.map(node => { + const temps = [] + const temp = node.data.node.template + Object.keys(temp).map(key => { + const { type, value } = temp[key] + if (type === 'prompt' && !!value) !temps.length && temps.push({ name: key, template: value, data: node.data }) + }) + return temps + }).flat() + + const promises = params.map(param => { + return postValidatePrompt(param.name, param.template, param.data.node).then(res => { + if (res) param.data.node = res.frontend_node + }) + }) + return Promise.all(promises) + } + + return { ...flowSate, checkPrompt } +} + +/** + * 消息列表模块 + * 翻页、追加、历史 + * @returns + */ +const useMessages = (chatId, flow) => { + const [chatHistory, setChatHistory] = useState([]); + const lastIdRef = useRef(0) + // 控制开启自动随消息滚动(临时方案) + const changeHistoryByScroll = useRef(false) + + const loadIdRef = useRef('') // 记录最后一个加载的 chatId + // 获取聊天记录 + const loadHistory = async (lastId?: number) => { + loadIdRef.current = chatId + + const res = await getChatHistory(flow.id, chatId, lastId ? 10 : 30, lastId) + const hisData = res.map(item => { + // let count = 0 + let { message, files, is_bot, intermediate_steps, ...other } = item + try { + message = message && message[0] === '{' ? JSON.parse(message.replace(/([\t\n"])/g, '\\$1').replace(/'/g, '"')) : message || '' + } catch (e) { + // 未考虑的情况暂不处理 + } + return { + ...other, + chatKey: typeof message === 'string' ? undefined : Object.keys(message)[0], + end: true, + files: files ? JSON.parse(files) : [], + isSend: !is_bot, + message, + thought: intermediate_steps, + noAccess: true + } + }) + lastIdRef.current = hisData[hisData.length - 1]?.id || lastIdRef.current || 0 // 记录最后一个id + + let historyData = [] + if (lastId) { + historyData = [...hisData.reverse(), ...chatHistory] + } else if (loadIdRef.current === chatId) { // 保证同一会话 + historyData = hisData.reverse() + } + setChatHistory(historyData) + const pageSize = historyData.length < 30 ? 30 : 10 // 先偷懒 + if (hisData.length < pageSize) initGuide() + return historyData + } + + const loadLock = useRef(false) + const currentIdRef = useRef(0) + const loadNextPage = async () => { + if (loadLock.current) return + if (currentIdRef.current === lastIdRef.current) return // 最后一个相同表示聊天记录已到顶 + loadLock.current = true + currentIdRef.current = lastIdRef.current + changeHistoryByScroll.current = true + await loadHistory(currentIdRef.current) + loadLock.current = false + // 滚动 hack TODO 滚动翻页设计 + setTimeout(() => { + changeHistoryByScroll.current = false + }, 500); + } + + const initGuide = () => { + const guideMsg = { + "category": "system", + "chat_id": chatId, + "end": true, + "create_time": "", + "extra": "{}", + "files": [], + "flow_id": flow.id, + "id": 9999, + "thought": flow.guide_word, + "is_bot": true, + "liked": 0, + "message": '', + "receiver": null, + "remark": null, + "sender": "", + "solved": 0, + isSend: false, + "source": 0, + "type": "end", + "update_time": "", + noAccess: true, + "user_id": 0 + } + flow.guide_word && setChatHistory((chatHistory) => + chatHistory[0]?.id === 9999 ? chatHistory : [guideMsg, ...chatHistory] + ) + } + + // 消息滚动 + const messagesRef = useRef(null); + useEffect(() => { + if (messagesRef.current) { // 滚动加载不触发 + // if (messagesRef.current && !changeHistoryByScroll.current) { // 滚动加载不触发 + console.log(1,messagesRef,changeHistoryByScroll) + setTimeout(() => { + messagesRef.current.scrollTop = messagesRef.current.scrollHeight; + }, 100); + } + }, [chatHistory, changeHistoryByScroll]); + + // 消息滚动加载 + useEffect(() => { + function handleScroll() { + if (messagesRef.current.scrollTop <= 30) { + loadNextPage() + } + } + + messagesRef.current?.addEventListener('scroll', handleScroll); + return () => messagesRef.current?.removeEventListener('scroll', handleScroll) + }, [messagesRef.current, chatHistory, chatId]); + + return { + messages: chatHistory, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll + } +} + +/** + * websocket 通信 + * 建立连接、重连、断开、接收、发送 + * @returns + */ +const useWebsocket = (chatId, flow, setChatHistory, queryString, version) => { + const ws = useRef(null); + // 接收ws状态 + const [begin, setBegin] = useState(false) + const { setErrorData } = useContext(alertContext); + const { t } = useTranslation() + + const { appConfig } = useContext(locationContext) + + const chatIdRef = useRef(chatId); + useEffect(() => { + chatIdRef.current = chatId; + }, [chatId]) + + function heartbeat() { + if (!ws.current) return; + if (ws.current.readyState !== 1) return; + ws.current.send("heartbeat"); + setTimeout(heartbeat, 30000); + } + + function getWebSocketUrl(flowId, isDevelopment = false) { + const token = localStorage.getItem("ws_token") || ''; + + const isSecureProtocol = window.location.protocol === "https:"; + const webSocketProtocol = isSecureProtocol ? "wss" : "ws"; + const host = appConfig.websocketHost || window.location.host // isDevelopment ? "localhost:7860" : window.location.host; + const chatEndpoint = version === 'v1' ? `/api/v1/chat/${flowId}?type=L1&chat_id=${chatId}&t=${token}` + : `/api/v2/chat/ws/${flowId}?type=L1&chat_id=${chatId}${queryString}&t=${token}` + + return `${webSocketProtocol}://${host}${chatEndpoint}`; + } + + const newChatStart = useRef(false) // 处理当前会话上下文丢失,阻止上一次打字机效果 + // 自动重连次数 + const tryReLinkCount = useRef(0) + const reConnect = (params) => { + if (tryReLinkCount.current <= 3) { + connectWS(params) + tryReLinkCount.current++ + } else { + console.warn('超过最大重试次数 :>> '); + } + } + useEffect(() => { + tryReLinkCount.current = 0 + newChatStart.current = true + }, [chatId]) + + function connectWS(params) { + const { setInputState, setIsStop, changeHistoryByScroll } = params + if (ws.current) return Promise.resolve('ok'); + + // 连接断开重链接 + return new Promise((res, rej) => { + try { + const urlWs = getWebSocketUrl( + flow.id, + process.env.NODE_ENV === "development" + ); + const newWs = new WebSocket(urlWs); + newWs.onopen = () => { + console.log("WebSocket connection established!"); + res('ok') + // heartbeat() + }; + newWs.onmessage = (event) => { + const data = JSON.parse(event.data); + if (data.chat_id !== chatIdRef.current) return + console.log('newChatStart.current :>> ', newChatStart.current); + + const errorMsg = data.category === 'error' ? data.intermediate_steps : '' + + if (newChatStart.current) { + if (data.type === 'close') { + newChatStart.current = false + return setInputState({ lock: false, errorMsg }) + } else { + return setInputState({ lock: true, errorMsg }) + } + } + // 异常类型处理,提示 + if (errorMsg) return setInputState({ lock: true, errorMsg }) + + handleWsMessage({ data, setIsStop, setInputState, changeHistoryByScroll }); + // get chat history + // 群聊@自己时,开启input + if (data.type === 'end' && data.receiver?.is_self) { + setInputState({ lock: false, errorMsg: '' }) + } + }; + newWs.onclose = (event) => { + ws.current = null + + handleOnClose({ event, setIsStop, setInputState }); + // reConnect(params) + }; + newWs.onerror = (ev) => { + ws.current = null + + console.error('链接异常error', ev); + setIsStop(true) + + setErrorData({ + title: `${t('chat.networkError')}:`, + list: [ + t('chat.networkErrorList1'), + t('chat.networkErrorList2'), + t('chat.networkErrorList3') + ], + }); + reConnect(params) + }; + ws.current = newWs; + console.log('newWs :>> ', newWs); + } catch (error) { + console.error('创建链接异常', error); + rej(error) + } + }) + } + + var isStream = false; + function handleWsMessage({ data, setIsStop, setInputState, changeHistoryByScroll }) { + if (Array.isArray(data) && data.length) return + if (data.type === "begin") { + setBegin(true) + setIsStop(false) + changeHistoryByScroll.current = false + } + if (data.type === "close") { + setBegin(false) + setIsStop(true) + setInputState({ lock: false, errorMsg: '' }); + changeHistoryByScroll.current = true + } + if (data.type === "start") { + setChatHistory((old) => { + let newChat = cloneDeep(old); + newChat.push({ + isSend: false, + message: '', + chatKey: '', + thought: data.intermediate_steps || '', + category: data.category || '', + files: [], + end: false + }) + return newChat + }); + isStream = true; + } + if (data.type === "stream" && isStream) { + updateLastMessage({ str: data.message, thought: data.intermediate_steps }); + } + if (data.type === "end") { + updateLastMessage({ + ...data, + str: data.message, + files: data.files || null, + end: true, + thought: data.intermediate_steps || '', + cate: data.category || '', + messageId: data.message_id, + noAccess: false, + liked: 0 + }); + + isStream = false; + } + } + + function updateLastMessage({ str, thought = '', end = false, files = [], cate = '', messageId = 0, source = false, noAccess = false, ...data }: { + str: string; + messageId?: number + thought?: string; + cate?: string; + end?: boolean; + files?: Array; + source?: boolean + noAccess?: boolean + }) { + setChatHistory((old) => { + const newChats = [...old] + // console.log('newchats :>> ', newChats); + let chatsLen = newChats.length + const prevChat = newChats[chatsLen - 2] + // hack 过滤重复最后消息 + if (end + && str + && chatsLen > 1 + && str === prevChat.message + // && data.sender === prevChat.sender + && !prevChat.thought) { + newChats.splice(chatsLen - 2, 1) // 删上一条 + chatsLen = newChats.length + } + // 更新 + const lastChat = newChats[chatsLen - 1] + const newLastChat = { + ...newChats[chatsLen - 1], + ...data, + id: messageId, + message: lastChat.message + str, + thought: lastChat.thought + (thought ? `${thought}\n` : ''), + files, + category: cate, + source, + noAccess, + end + } + newChats[chatsLen - 1] = newLastChat + // start - end 之间没有内容删除load + if (end && !(newLastChat.files.length || newLastChat.thought || newLastChat.message)) { + newChats.pop() + } + return newChats; + }); + } + + // 发送ws + async function sendAll(data: sendAllProps) { + try { + if (ws.current) { + if (JSON.stringify(data.inputs) !== '{}') { + newChatStart.current = false + } + ws.current.send(JSON.stringify(data)); + } + } catch (error) { + setErrorData({ + title: "There was an error sending the message", + list: [error.message], + }); + } + } + + // 处理主动断开 + function handleOnClose({ event, setIsStop, setInputState }) { + console.error('链接手动断开 event :>> ', event); + setIsStop(true) + setBegin(false) + + if ([1005, 1008].includes(event.code)) { + console.warn('即将废弃 :>> '); + setInputState({ lock: true, errorMsg: event.reason }); + } else { + if (event.reason) { + setErrorData({ title: event.reason }); + // setChatHistory((old) => { + // let newChat = cloneDeep(old); + // if (newChat.length) { + // newChat[newChat.length - 1].end = true; + // } + // newChat.push({ end: true, message: `${t('chat.connectionbreakTip')}${event.reason}`, isSend: false, chatKey: '', files: [] }); + // return newChat + // }) + } + setInputState({ lock: false, errorMsg: '' }); + } + } + + useEffect(() => { + // destory + return () => { + // close prev connection + if (ws.current) { + switch (ws.current.readyState) { + case WebSocket.OPEN: + console.warn('前端主动关闭1') + ws.current.close() + ; break; + case WebSocket.CONNECTING: + ws.current.onopen = () => { + console.warn('前端主动关闭2') + ws.current.close() + }; + } + ws.current = null + } + } + }, []) + + // 检测并重连 + const checkReLinkWs = async (reConnect) => { + if (ws.current) return true + // 重连 + // 上一条加loading + setChatHistory((old) => { + let newChat = [...old]; + newChat[newChat.length - 1].category = 'loading'; + return newChat; + }); + await reConnect() + // 链接成功 + // 上一条去loading + setChatHistory((old) => { + let newChat = [...old]; + newChat[newChat.length - 1].category = ''; + return newChat; + }); + } + + const handleStop = () => { + try { + if (ws) { + ws.current.send(JSON.stringify({ + "action": "stop" + })); + } + } catch (error) { + setErrorData({ + title: "There was an error stop the message", + list: [error.message], + }); + } + } + + return { begin, stop: handleStop, checkReLinkWs, sendAll, connectWS } +} + +/** + * build flow + * 校验每个节点,展示进度及结果;返回input_keys;end_of_stream断开链接 + * 主要校验节点并设置更新setTabsState的 formKeysData + * @returns + */ +const useBuild = (flow: FlowType, chatId: string) => { + const { setErrorData } = useContext(alertContext); + const { setTabsState } = useContext(TabsContext); + const { t } = useTranslation() + + // SSE 服务端推送 + async function streamNodeData(flow: FlowType, chatId: string) { + // Step 1: Make a POST request to send the flow data and receive a unique session ID + const { flowId } = await postBuildInit(flow, chatId); + // Step 2: Use the session ID to establish an SSE connection using EventSource + let validationResults = []; + let finished = false; + let buildEnd = false + const apiUrl = `/api/v1/build/stream/${flowId}?chat_id=${chatId}`; + const eventSource = new EventSource(apiUrl); + + eventSource.onmessage = (event) => { + // If the event is parseable, return + if (!event.data) { + return; + } + const parsedData = JSON.parse(event.data); + // if the event is the end of the stream, close the connection + if (parsedData.end_of_stream) { + eventSource.close(); // 结束关闭链接 + buildEnd = true + return; + } else if (parsedData.log) { + // If the event is a log, log it + // setSuccessData({ title: parsedData.log }); + } else if (parsedData.input_keys) { + setTabsState((old) => { + return { + ...old, + [flowId]: { + ...old[flowId], + formKeysData: parsedData, + }, + }; + }); + } else { + // setProgress(parsedData.progress); + validationResults.push(parsedData.valid); + } + }; + + eventSource.onerror = (error: any) => { + console.error("EventSource failed:", error); + eventSource.close(); + if (error.data) { + const parsedData = JSON.parse(error.data); + setErrorData({ title: parsedData.error }); + } + }; + // Step 3: Wait for the stream to finish + while (!finished) { + await new Promise((resolve) => setTimeout(resolve, 100)); + finished = buildEnd // validationResults.length === flow.data.nodes.length; + } + // Step 4: Return true if all nodes are valid, false otherwise + return validationResults.every((result) => result); + } + + // 延时器 + async function enforceMinimumLoadingTime( + startTime: number, + minimumLoadingTime: number + ) { + const elapsedTime = Date.now() - startTime; + const remainingTime = minimumLoadingTime - elapsedTime; + + if (remainingTime > 0) { + return new Promise((resolve) => setTimeout(resolve, remainingTime)); + } + } + + async function handleBuild() { + try { + const errors = flow.data.nodes.flatMap((n: NodeType) => validateNode(n, flow.data.edges)) + if (errors.length > 0) { + setErrorData({ + title: t('chat.buildError'), + list: errors, + }); + return; + } + + const minimumLoadingTime = 200; // in milliseconds + const startTime = Date.now(); + + await streamNodeData(flow, chatId); + await enforceMinimumLoadingTime(startTime, minimumLoadingTime); // 至少等200ms, 再继续(强制最小load时间) + } catch (error) { + console.error("Error:", error); + } finally { + } + } + + return handleBuild +} \ No newline at end of file diff --git a/src/pages/ChatAppPage/components/ChatReportForm.tsx b/src/pages/ChatAppPage/components/ChatReportForm.tsx index 88520dc..0961be4 100644 --- a/src/pages/ChatAppPage/components/ChatReportForm.tsx +++ b/src/pages/ChatAppPage/components/ChatReportForm.tsx @@ -1,6 +1,6 @@ -import { useContext, useEffect, useRef, useState } from "react"; +import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/bs-ui/select"; +import { forwardRef, useContext, useEffect, useImperativeHandle, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; -import Dropdown from "../../../components/dropdownComponent"; import InputComponent from "../../../components/inputComponent"; import InputFileComponent from "../../../components/inputFileComponent"; import { Button } from "../../../components/ui/button"; @@ -12,14 +12,23 @@ import { Variable, VariableType, getVariablesApi } from "../../../controllers/AP * @description * 表单项数据由组件的参数信息和单独接口获取的必填信息及排序信息而来。 */ -export default function ChatReportForm({ flow, onStart }) { +const ChatReportForm = forwardRef(({ type = 'chat', vid = 0, flow, onStart }, ref) => { const { setErrorData } = useContext(alertContext); const { t } = useTranslation() + useImperativeHandle(ref, () => ({ + submit: () => { + handleStart() + } + })); + // 从 api中获取 const [items, setItems] = useState([]) useEffect(() => { - getVariablesApi({ flow_id: flow.id }).then( + // chat -》L1; diff -> 对比测试 + type === 'chat' ? getVariablesApi({ flow_id: flow.flow_id || flow.id }).then( + res => setItems(res) + ) : getVariablesApi({ version_id: vid, flow_id: flow.flow_id || flow.id }).then( res => setItems(res) ) }, []) @@ -56,9 +65,9 @@ export default function ChatReportForm({ flow, onStart }) { onStart(obj, str) } - return
+ return
- {items.map((item, i) =>
+ {items.map((item, i) =>
{item.name} {item.required ? " *" : ""}
@@ -68,11 +77,18 @@ export default function ChatReportForm({ flow, onStart }) { onChange={(val) => handleChange(i, val)} /> : item.type === VariableType.Select ? - e.value)} - onSelect={(val) => handleChange(i, val)} - value={item.value} - > : + : item.type === VariableType.File ? )}
- + {type === 'chat' && }
-}; +}); + +export default ChatReportForm \ No newline at end of file diff --git a/src/pages/ChatAppPage/index.tsx b/src/pages/ChatAppPage/index.tsx index 702bbd9..ab1acda 100755 --- a/src/pages/ChatAppPage/index.tsx +++ b/src/pages/ChatAppPage/index.tsx @@ -18,6 +18,10 @@ import robot3 from "../../assets/robot3.png"; import duihuaItemTop from "../../assets/chat/duihua-item-top.png"; import duihuaItemJia from "../../assets/chat/duihua-item-+.png"; import duihuaItemGuan from "../../assets/chat/duihua-item-x.png"; +import SkillChatSheet from "@/components/bs-comp/sheets/SkillChatSheet"; +import { TitleIconBg } from "@/components/bs-comp/cardComponent"; +import npcIcon from "../../assets/npc/npcIcon.png"; +import nengliIcon from "../../assets/npc/nengliIcon.png"; export default function SkillChatPage() { @@ -25,6 +29,9 @@ export default function SkillChatPage() { const [face, setFace] = useState(true); const { t } = useTranslation() + const [selectChat, setSelelctChat] = useState({ + id: '', chatId: '', type: '' + }) const { flow: initFlow } = useContext(TabsContext); const [flow, setFlow] = useState(null) @@ -39,45 +46,33 @@ export default function SkillChatPage() { ); // 对话列表 const { chatList, chatId, chatsRef, setChatId, addChat, deleteChat } = useChatList() - const chatIdRef = useRef('') // select flow - const handlerSelectFlow = async (node: FlowType) => { + const handlerSelectFlow = async (card) => { // 会话ID - chatIdRef.current = generateUUID(32) - setOpen(false) + const _chatId = generateUUID(32) + // setOpen(false) // add list addChat({ - "flow_name": node.name, - "flow_description": node.description, - "flow_id": node.id, - "chat_id": chatIdRef.current, + "flow_name": card.name, + "flow_description": card.desc, + "flow_id": card.id, + "chat_id": _chatId, "create_time": "-", - "update_time": "-" + "update_time": "-", + "flow_type": card.flow_type }) - const flow = await getFlowApi(node.id) - setFlow(flow) - setChatId(chatIdRef.current) - setFace(false) + setSelelctChat({ id: card.id, chatId: _chatId, type: card.flow_type }) + setChatId(_chatId) } // select chat const handleSelectChat = useDebounce(async (chat) => { + console.log('chat.id :>> ', chat); if (chat.chat_id === chatId) return - - chatIdRef.current = chat.chat_id - const flow = initFlow?.id === chat.flow_id ? initFlow : await getFlowApi(chat.flow_id) - - // if (!flow) { - // setInputState({ lock: true, errorCode: '1004' }) - // clearHistory() - // return setFace(false) - // } - - setFlow(flow) + setSelelctChat({ id: chat.flow_id, chatId: chat.chat_id, type: chat.flow_type }) setChatId(chat.chat_id) - setFace(false) }, 100, false) @@ -88,7 +83,7 @@ export default function SkillChatPage() { desc: t('chat.confirmDeleteChat'), onOk(next) { deleteChat(id); - setFace(true) + setSelelctChat({ id: '', chatId: '', type: '' }) next() } }) @@ -96,9 +91,16 @@ export default function SkillChatPage() { return
-
+
-
setOpen(true)}>{t('chat.newChat')}
+ +
+ {/* */} + {/* */} + {t('chat.newChat')} +
+
+ {/*
setOpen(true)}>{t('chat.newChat')}
*/} {/*
*/} @@ -110,9 +112,10 @@ export default function SkillChatPage() { className={` group item xinDuiHua-list-item relative hover:xinDuiHua-list-active cursor-pointer dark:hover:xinDuiHua-list-active ${chatId === chat.chat_id && 'xinDuiHua-list-active dark:xinDuiHua-list-active'}`} onClick={() => handleSelectChat(chat)}>
- {(chat.flow_id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || chat.flow_id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } + {/* {(chat.flow_id == "06b1d374-ba97-46e6-8782-c56dec8dcc17" || chat.flow_id == "ed8e21f6-9757-43d0-b076-8c6e81bb0580") && } {chat.flow_id == "ca214b41-2b73-4585-b172-bf1e546cf6ec" && } - {(chat.flow_id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && chat.flow_id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && chat.flow_id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && } + {(chat.flow_id != "06b1d374-ba97-46e6-8782-c56dec8dcc17" && chat.flow_id != "ed8e21f6-9757-43d0-b076-8c6e81bb0580" && chat.flow_id != "ca214b41-2b73-4585-b172-bf1e546cf6ec") && } */} + {/* */}

{chat.flow_name}

@@ -132,13 +135,7 @@ export default function SkillChatPage() {
{/* chat */} - {face - ?
-

{t('chat.selectChat')}

-
- :
- {flow && } -
} + {/* 选择对话技能 */} // 发送消息 if (chat.isSend) return
-
-

{userName}

+
+
+
+ {chat.category === 'loading' && } + {chat.message[chat.chatKey]} +
+ +
+ {!disabledReSend && !disabledReSend && onEdit(chat.message[chat.chatKey])} className="w-[20px] ml-[10px] cursor-pointer" alt=""/>} + {!disabledReSend && !disabledReSend && onReSend(chat.message[chat.chatKey])} className="w-[20px] ml-[10px] cursor-pointer" alt=""/>} + {/* */} + {/* {!showSearch && onSearch(chat.message[chat.chatKey])}>} */} +
+
+ {/*

{userName}

*/}
-
-
- {chat.category === 'loading' && } - {chat.message[chat.chatKey]} -
- -
- {!disabledReSend && !disabledReSend && onEdit(chat.message[chat.chatKey])} className="w-[20px] ml-[10px] cursor-pointer" alt=""/>} - {!disabledReSend && !disabledReSend && onReSend(chat.message[chat.chatKey])} className="w-[20px] ml-[10px] cursor-pointer" alt=""/>} - {/* */} - {/* {!showSearch && onSearch(chat.message[chat.chatKey])}>} */} -
-
{/* 文件 */ } //
@@ -286,31 +286,31 @@ export const ChatMessage = ({ chat, userName, disabledReSend, showSearch, onSour {/*
*/} -
+
-

{userName}

+ {/*

{userName}

*/} +
+
+ {chat.message.toString() ? mkdown : } + {/* @user */} + {chat.receiver &&

@ {chat.receiver.user_name}

} + {/* 光标 */} + {chat.message.toString() && !chat.end &&
} +
+ + {/* 赞 踩 */} + {!!chat.id && chat.end && + // className={`absolute w-full left-0 bottom-[8px] justify-end pr-5`}> + } +
{/* {chat.sender &&
{chat.sender}
} */} -
-
- {chat.message.toString() ? mkdown : } - {/* @user */} - {chat.receiver &&

@ {chat.receiver.user_name}

} - {/* 光标 */} - {chat.message.toString() && !chat.end &&
} -
- - {/* 赞 踩 */} - {!!chat.id && chat.end && - // className={`absolute w-full left-0 bottom-[8px] justify-end pr-5`}> - } -
{chat.source !== SourceType.NONE && chat.end && sourceContent(chat.source)}
}; diff --git a/src/pages/ChatAppPage/mobile/ChatPanneM copy.tsx b/src/pages/ChatAppPage/mobile/ChatPanneM copy.tsx new file mode 100644 index 0000000..8a7efbd --- /dev/null +++ b/src/pages/ChatAppPage/mobile/ChatPanneM copy.tsx @@ -0,0 +1,942 @@ +import cloneDeep from "lodash-es/cloneDeep"; +import { ClipboardList, FileInput, FileText, Send, StopCircle } from "lucide-react"; +import { forwardRef, useContext, useEffect, useMemo, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import ShadTooltip from "../../../components/ShadTooltipComponent"; +import { Button } from "../../../components/ui/button"; +import { alertContext } from "../../../contexts/alertContext"; +import { TabsContext } from "../../../contexts/tabsContext"; +import { getChatHistory, postBuildInit, postValidatePrompt } from "../../../controllers/API"; +import { Variable } from "../../../controllers/API/flow"; +import { sendAllProps } from "../../../types/api"; +import { ChatMessageType } from "../../../types/chat"; +import { FlowType, NodeType } from "../../../types/flow"; +import { validateNode } from "../../../utils"; +import { ChatMessage } from "./ChatMessageM"; +import ChatReportForm from "../components/ChatReportForm"; +import ResouceModal from "../components/ResouceModal"; +import ThumbsMessage from "../components/ThumbsMessage"; +import NpcInfo from "./NpcInfoM"; +import DuiHua from "./DuiHuaM"; +import PopUp from "./popUp"; +import Quote from "./quote"; +import { locationContext } from "../../../contexts/locationContext"; +import titIconL from "../../../assets/chatM/tit-icon-l.png"; +import titIconR from "../../../assets/chatM/tit-icon-r.png"; +import duihuaSend from "../../../assets/chat/duihua-send.png"; + +interface Iprops { + chatId: string + flow: FlowType + queryString?: string + version?: string +} + +export default forwardRef(function ChatPanne({ chatId, flow, queryString, version = 'v1' }: Iprops,ref) { + const { t } = useTranslation() + const { tabsState } = useContext(TabsContext); + + const { isRoom, isForm, isReport, checkPrompt } = useFlowState(flow) + + // build + const build = useBuild(flow, chatId) + // 消息列表 + const { messages, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll } = useMessages(chatId, flow) + // ws通信 + const { stop, connectWS, begin: chating, checkReLinkWs, sendAll } = useWebsocket(chatId, flow, setChatHistory, queryString, version) + // 停止状态 + const [isStop, setIsStop] = useState(true) + // 输入框状态 + const { inputState, inputEmpty, inputDisabled, inputRef, + formShow, setFormShow, + setInputState, setInputEmpty, handleTextAreaHeight } = useInputState({ flow, chatId, chating, messages, isForm, isReport }) + + const { appConfig } = useContext(locationContext) + + // npc信息 + const [isNpcInfo, setIsNpcInfo] = useState(false) + // 对话信息 + const [isDuiHua, setIsDuiHua] = useState(false) + // 弹窗信息 + const [isPopUp, setIsPopUp] = useState(false) + // 引用弹窗信息 + const [isQuote, setIsQuote] = useState(false) + // 开始构建&切换初始化会话 + const initChat = async () => { + await checkPrompt(flow) + await build() + const historyData = version === 'v1' ? await loadHistory() : (initGuide(), []) + await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) + setInputState({ lock: false, errorMsg: '' }); + // 第一条消息,用来初始化会话 + sendAll({ + chatHistory: messages, + name: flow.name, + description: flow.description, + inputs: {}, + flow_id: flow.id, + chat_id: chatId + }) + + changeHistoryByScroll.current = false + // 自动聚焦 + if (inputRef.current) inputRef.current.value = '' + setTimeout(() => { + inputRef.current?.focus() + }, 500); + + const isNewChat = historyData.length === 0 || historyData[0].id === 9999 + setFormShow(isNewChat && isForm) + } + useEffect(() => { + initChat() + }, [flow]) + // document.documentElement.addEventListener( + // 'touchstart', + // function (event) { + // if (event.touches.length > 1) { + // event.preventDefault(); + // } + // }, + // { + // passive: false, + // }, + // ); + // sendmsg user name + const sendUserName = useMemo(() => { + const node = flow.data.nodes.find(el => el.data.type === 'AutoGenUser') + return node?.data.node.template['name'].value || '' + }, [flow]) + + const handleSend = async () => { + const msg = inputRef.current?.value + setTimeout(() => { + if (inputRef.current) { + inputRef.current.value = '' + inputRef.current.style.height = 'auto' + } + setInputEmpty(true) + }, 100); + + if (msg.trim() === '') return + + setInputState({ lock: true, errorMsg: '' }); + let inputs = tabsState[flow.id].formKeysData.input_keys; + const input = inputs.find((el: any) => !el.type) + const inputKey = input ? Object.keys(input)[0] : ''; + setChatHistory((old) => { + let newChat = cloneDeep(old); + newChat.push({ + isSend: true, + message: { ...input, [inputKey]: msg }, + chatKey: inputKey, + thought: '', + category: '', + files: [], + end: false, + user_name: "" + }) + return newChat + }); + + await checkReLinkWs(async () => { + // await build() + await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) + }) + + const chatInfo = { + chat_id: chatId, + flow_id: flow.id, + inputs: { ...input, [inputKey]: msg } + } + // @ts-ignore + isRoom && chating ? sendAll({ action: "continue", ...chatInfo }) + : sendAll({ + chatHistory: messages, + name: flow.name, + description: flow.description, + ...chatInfo + }); + } + + + // 报表请求 + const sendReport = (items: Variable[], str) => { + let inputs = tabsState[flow.id].formKeysData.input_keys; + const input = inputs.find((el: any) => !el.type) + const inputKey = input ? Object.keys(input)[0] : ''; + setChatHistory((old) => { + let newChat = cloneDeep(old); + newChat.push({ + isSend: true, + message: { ...input, [inputKey]: str }, + chatKey: inputKey, + thought: '', + category: '', + files: [], + end: false, + user_name: "" + }) + return newChat + }); + + const data = items.map(item => ({ + id: item.nodeId, + name: item.name, + file_path: item.type === 'file' ? item.value : '', + value: item.type === 'file' ? '' : item.value + })) + + setIsStop(false) + setFormShow(false) + + sendAll({ + inputs: { + ...input, + [inputKey]: str, + data + }, + chatHistory: messages, + name: flow.name, + description: flow.description, + chat_id: chatId, + flow_id: flow.id, + }); + } + + // 溯源 + const [souce, setSouce] = useState(null) + + const thumbRef = useRef(null) + + return
+ +
+
+ {/*
setIsDuiHua(!isDuiHua)}> + +
*/} +

{flow.name}

+ {/*
setIsNpcInfo(!isNpcInfo)}> + +
*/} +
+
+
+ {/* 会话记录 */} +
+ { + messages.map((c, i) => setSouce(c)} + onDislike={(chatId) => { thumbRef.current?.openModal(chatId) }} + onReSend={(msg) => { + inputRef.current.value = msg + handleSend() + }} + onEdit={(msg) => { inputRef.current.value = msg; setInputEmpty(!msg) }} + onSearch={(msg) => window.open(appConfig.dialogQuickSearch + encodeURIComponent(msg))} + >) + } +
+ {/* 输入框 */} +
+ {/*
*/} +
+ +
+ {/* + + */} +
+ +
+
+ {/* {inputState.errorMsg &&
{inputState.errorMsg}
} */} + {inputState.errorMsg &&
{inputState.errorMsg}
} +
+

{appConfig.dialogTips}

+
+
+ {(isRoom || isReport) &&
+ +
} + {/* 源文件类型 */} + setSouce(null)}> + {/* 表单 */} + {isForm && formShow && } + {/* 踩 反馈 */} + + + + + + + + + + +
+}); +/** + * 输入框状态 + * 分析 flow状态 + * return 该技能含有表单、有报表、群聊 + * @returns + */ +const useInputState = ({ flow, chatId, chating, messages, isForm, isReport }) => { + const { tabsState } = useContext(TabsContext); + + const [inputState, setInputState] = useState({ + lock: false, + errorMsg: '' + }) + // 输入问答 + const inputRef = useRef(null) + useEffect(() => { + !chating && setTimeout(() => { + // 对话结束自动聚焦 + inputRef.current?.focus() + }, 1000); + }, [chating]) + // input 滚动 + const [inputEmpty, setInputEmpty] = useState(true) + useEffect(() => { + setInputEmpty(true) + if (inputRef.current) inputRef.current.value = '' + }, [chatId]) + + // 获取上传file input + const fileInputs = useMemo(() => { + return tabsState[flow.id]?.formKeysData?.input_keys?.filter((input: any) => input.type === 'file') + }, [tabsState, flow]) + + const handleTextAreaHeight = (e) => { + const textarea = e.target + textarea.style.height = 'auto' + textarea.style.height = textarea.scrollHeight + 'px' + setInputEmpty(textarea.value.trim() === '') + } + // input disabled + const inputDisabled = useMemo(() => { + return inputState.lock + // 表单 && 没回话或只有一个引导词 + || (isForm && (messages.length === 0 || (messages.length === 1 && messages[0].id === 9999))) + || isReport + }, [inputState, fileInputs, isReport]) + + // 表单收起 + const [formShow, setFormShow] = useState(true) + return { + inputState, inputEmpty, inputDisabled, inputRef, + formShow, setFormShow, + setInputState, setInputEmpty, handleTextAreaHeight + } +} + +/** + * flow state + * 分析 flow状态 + * return 该技能含有表单、有报表、群聊 + * @returns + */ +const useFlowState = (flow: FlowType) => { + const flowSate = useMemo(() => { + // 是否群聊 + const isRoom = !!flow.data?.nodes.find(node => node.data.type === "AutoGenChain") + // 是否展示表单 + const isForm = !!flow.data?.nodes.find(node => ["VariableNode", "InputFileNode"].includes(node.data.type)) + // 是否报表 + const isReport = !!flow.data?.nodes.find(node => "Report" === node.data.type) + return { isRoom, isForm, isReport } + }, [flow]) + + // propmt类型补充自定义字段 + const checkPrompt = async (_flow) => { + const params = _flow.data.nodes.map(node => { + const temps = [] + const temp = node.data.node.template + Object.keys(temp).map(key => { + const { type, value } = temp[key] + if (type === 'prompt' && !!value) !temps.length && temps.push({ name: key, template: value, data: node.data }) + }) + return temps + }).flat() + + const promises = params.map(param => { + return postValidatePrompt(param.name, param.template, param.data.node).then(res => { + if (res) param.data.node = res.frontend_node + }) + }) + return Promise.all(promises) + } + + return { ...flowSate, checkPrompt } +} + +/** + * 消息列表模块 + * 翻页、追加、历史 + * @returns + */ +const useMessages = (chatId, flow) => { + const [chatHistory, setChatHistory] = useState([]); + const lastIdRef = useRef(0) + // 控制开启自动随消息滚动(临时方案) + const changeHistoryByScroll = useRef(false) + + const loadIdRef = useRef('') // 记录最后一个加载的 chatId + // 获取聊天记录 + const loadHistory = async (lastId?: number) => { + loadIdRef.current = chatId + + const res = await getChatHistory(flow.id, chatId, lastId ? 10 : 30, lastId) + const hisData = res.map(item => { + // let count = 0 + let { message, files, is_bot, intermediate_steps, ...other } = item + try { + message = message && message[0] === '{' ? JSON.parse(message.replace(/([\t\n"])/g, '\\$1').replace(/'/g, '"')) : message || '' + } catch (e) { + // 未考虑的情况暂不处理 + } + return { + ...other, + chatKey: typeof message === 'string' ? undefined : Object.keys(message)[0], + end: true, + files: files ? JSON.parse(files) : [], + isSend: !is_bot, + message, + thought: intermediate_steps, + noAccess: true + } + }) + lastIdRef.current = hisData[hisData.length - 1]?.id || lastIdRef.current || 0 // 记录最后一个id + + let historyData = [] + if (lastId) { + historyData = [...hisData.reverse(), ...chatHistory] + } else if (loadIdRef.current === chatId) { // 保证同一会话 + historyData = hisData.reverse() + } + setChatHistory(historyData) + const pageSize = historyData.length < 30 ? 30 : 10 // 先偷懒 + if (hisData.length < pageSize) initGuide() + return historyData + } + + const loadLock = useRef(false) + const currentIdRef = useRef(0) + const loadNextPage = async () => { + if (loadLock.current) return + if (currentIdRef.current === lastIdRef.current) return // 最后一个相同表示聊天记录已到顶 + loadLock.current = true + currentIdRef.current = lastIdRef.current + changeHistoryByScroll.current = true + await loadHistory(currentIdRef.current) + loadLock.current = false + // 滚动 hack TODO 滚动翻页设计 + setTimeout(() => { + changeHistoryByScroll.current = false + }, 500); + } + + const initGuide = () => { + const guideMsg = { + "category": "system", + "chat_id": chatId, + "end": true, + "create_time": "", + "extra": "{}", + "files": [], + "flow_id": flow.id, + "id": 9999, + "thought": flow.guide_word, + "is_bot": true, + "liked": 0, + "message": '', + "receiver": null, + "remark": null, + "sender": "", + "solved": 0, + isSend: false, + "source": 0, + "type": "end", + "update_time": "", + noAccess: true, + "user_id": 0 + } + flow.guide_word && setChatHistory((chatHistory) => + chatHistory[0]?.id === 9999 ? chatHistory : [guideMsg, ...chatHistory] + ) + } + + // 消息滚动 + const messagesRef = useRef(null); + useEffect(() => { + if (messagesRef.current && !changeHistoryByScroll.current) { // 滚动加载不触发 + messagesRef.current.scrollTop = messagesRef.current.scrollHeight; + } + }, [chatHistory, changeHistoryByScroll]); + + // 消息滚动加载 + useEffect(() => { + function handleScroll() { + if (messagesRef.current.scrollTop <= 30) { + loadNextPage() + } + } + + messagesRef.current?.addEventListener('scroll', handleScroll); + return () => messagesRef.current?.removeEventListener('scroll', handleScroll) + }, [messagesRef.current, chatHistory, chatId]); + + return { + messages: chatHistory, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll + } +} + +/** + * websocket 通信 + * 建立连接、重连、断开、接收、发送 + * @returns + */ +const useWebsocket = (chatId, flow, setChatHistory, queryString, version) => { + const ws = useRef(null); + // 接收ws状态 + const [begin, setBegin] = useState(false) + const { setErrorData } = useContext(alertContext); + const { t } = useTranslation() + + const { appConfig } = useContext(locationContext) + + const chatIdRef = useRef(chatId); + useEffect(() => { + chatIdRef.current = chatId; + }, [chatId]) + + function heartbeat() { + if (!ws.current) return; + if (ws.current.readyState !== 1) return; + ws.current.send("heartbeat"); + setTimeout(heartbeat, 30000); + } + + function getWebSocketUrl(flowId, isDevelopment = false) { + const token = localStorage.getItem("ws_token") || ''; + + const isSecureProtocol = window.location.protocol === "https:"; + const webSocketProtocol = isSecureProtocol ? "wss" : "ws"; + const host = appConfig.websocketHost || window.location.host // isDevelopment ? "localhost:7860" : window.location.host; + const chatEndpoint = version === 'v1' ? `/api/v1/chat/${flowId}?type=L1&chat_id=${chatId}&t=${token}` + : `/api/v2/chat/ws/${flowId}?type=L1&chat_id=${chatId}${queryString}&t=${token}` + + return `${webSocketProtocol}://${host}${chatEndpoint}`; + } + + const newChatStart = useRef(false) // 处理当前会话上下文丢失,阻止上一次打字机效果 + // 自动重连次数 + const tryReLinkCount = useRef(0) + const reConnect = (params) => { + if (tryReLinkCount.current <= 3) { + connectWS(params) + tryReLinkCount.current++ + } else { + console.warn('超过最大重试次数 :>> '); + } + } + useEffect(() => { + tryReLinkCount.current = 0 + newChatStart.current = true + }, [chatId]) + + function connectWS(params) { + const { setInputState, setIsStop, changeHistoryByScroll } = params + if (ws.current) return Promise.resolve('ok'); + + // 连接断开重链接 + return new Promise((res, rej) => { + try { + const urlWs = getWebSocketUrl( + flow.id, + process.env.NODE_ENV === "development" + ); + const newWs = new WebSocket(urlWs); + newWs.onopen = () => { + console.log("WebSocket connection established!"); + res('ok') + // heartbeat() + }; + newWs.onmessage = (event) => { + const data = JSON.parse(event.data); + if (data.chat_id !== chatIdRef.current) return + console.log('newChatStart.current :>> ', newChatStart.current); + + const errorMsg = data.category === 'error' ? data.intermediate_steps : '' + + if (newChatStart.current) { + if (data.type === 'close') { + newChatStart.current = false + return setInputState({ lock: false, errorMsg }) + } else { + return setInputState({ lock: true, errorMsg }) + } + } + // 异常类型处理,提示 + if (errorMsg) return setInputState({ lock: true, errorMsg }) + + handleWsMessage({ data, setIsStop, setInputState, changeHistoryByScroll }); + // get chat history + // 群聊@自己时,开启input + if (data.type === 'end' && data.receiver?.is_self) { + setInputState({ lock: false, errorMsg: '' }) + } + }; + newWs.onclose = (event) => { + ws.current = null + + handleOnClose({ event, setIsStop, setInputState }); + // reConnect(params) + }; + newWs.onerror = (ev) => { + ws.current = null + + console.error('链接异常error', ev); + setIsStop(true) + + setErrorData({ + title: `${t('chat.networkError')}:`, + list: [ + t('chat.networkErrorList1'), + t('chat.networkErrorList2'), + t('chat.networkErrorList3') + ], + }); + reConnect(params) + }; + ws.current = newWs; + console.log('newWs :>> ', newWs); + } catch (error) { + console.error('创建链接异常', error); + rej(error) + } + }) + } + + var isStream = false; + function handleWsMessage({ data, setIsStop, setInputState, changeHistoryByScroll }) { + if (Array.isArray(data) && data.length) return + if (data.type === "begin") { + setBegin(true) + setIsStop(false) + changeHistoryByScroll.current = false + } + if (data.type === "close") { + setBegin(false) + setIsStop(true) + setInputState({ lock: false, errorMsg: '' }); + changeHistoryByScroll.current = true + } + if (data.type === "start") { + setChatHistory((old) => { + let newChat = cloneDeep(old); + newChat.push({ + isSend: false, + message: '', + chatKey: '', + thought: data.intermediate_steps || '', + category: data.category || '', + files: [], + end: false + }) + return newChat + }); + isStream = true; + } + if (data.type === "stream" && isStream) { + updateLastMessage({ str: data.message, thought: data.intermediate_steps }); + } + if (data.type === "end") { + updateLastMessage({ + ...data, + str: data.message, + files: data.files || null, + end: true, + thought: data.intermediate_steps || '', + cate: data.category || '', + messageId: data.message_id, + noAccess: false, + liked: 0 + }); + + isStream = false; + } + } + + function updateLastMessage({ str, thought = '', end = false, files = [], cate = '', messageId = 0, source = false, noAccess = false, ...data }: { + str: string; + messageId?: number + thought?: string; + cate?: string; + end?: boolean; + files?: Array; + source?: boolean + noAccess?: boolean + }) { + setChatHistory((old) => { + const newChats = [...old] + // console.log('newchats :>> ', newChats); + let chatsLen = newChats.length + const prevChat = newChats[chatsLen - 2] + // hack 过滤重复最后消息 + if (end + && str + && chatsLen > 1 + && str === prevChat.message + // && data.sender === prevChat.sender + && !prevChat.thought) { + newChats.splice(chatsLen - 2, 1) // 删上一条 + chatsLen = newChats.length + } + // 更新 + const lastChat = newChats[chatsLen - 1] + const newLastChat = { + ...newChats[chatsLen - 1], + ...data, + id: messageId, + message: lastChat.message + str, + thought: lastChat.thought + (thought ? `${thought}\n` : ''), + files, + category: cate, + source, + noAccess, + end + } + newChats[chatsLen - 1] = newLastChat + // start - end 之间没有内容删除load + if (end && !(newLastChat.files.length || newLastChat.thought || newLastChat.message)) { + newChats.pop() + } + return newChats; + }); + } + + // 发送ws + async function sendAll(data: sendAllProps) { + try { + if (ws.current) { + if (JSON.stringify(data.inputs) !== '{}') { + newChatStart.current = false + } + ws.current.send(JSON.stringify(data)); + } + } catch (error) { + setErrorData({ + title: "There was an error sending the message", + list: [error.message], + }); + } + } + + // 处理主动断开 + function handleOnClose({ event, setIsStop, setInputState }) { + console.error('链接手动断开 event :>> ', event); + setIsStop(true) + setBegin(false) + + if ([1005, 1008].includes(event.code)) { + console.warn('即将废弃 :>> '); + setInputState({ lock: true, errorMsg: event.reason }); + } else { + if (event.reason) { + setErrorData({ title: event.reason }); + // setChatHistory((old) => { + // let newChat = cloneDeep(old); + // if (newChat.length) { + // newChat[newChat.length - 1].end = true; + // } + // newChat.push({ end: true, message: `${t('chat.connectionbreakTip')}${event.reason}`, isSend: false, chatKey: '', files: [] }); + // return newChat + // }) + } + setInputState({ lock: false, errorMsg: '' }); + } + } + + useEffect(() => { + // destory + return () => { + // close prev connection + if (ws.current) { + switch (ws.current.readyState) { + case WebSocket.OPEN: + console.warn('前端主动关闭1') + ws.current.close() + ; break; + case WebSocket.CONNECTING: + ws.current.onopen = () => { + console.warn('前端主动关闭2') + ws.current.close() + }; + } + ws.current = null + } + } + }, []) + + // 检测并重连 + const checkReLinkWs = async (reConnect) => { + if (ws.current) return true + // 重连 + // 上一条加loading + setChatHistory((old) => { + let newChat = [...old]; + newChat[newChat.length - 1].category = 'loading'; + return newChat; + }); + await reConnect() + // 链接成功 + // 上一条去loading + setChatHistory((old) => { + let newChat = [...old]; + newChat[newChat.length - 1].category = ''; + return newChat; + }); + } + + const handleStop = () => { + try { + if (ws) { + ws.current.send(JSON.stringify({ + "action": "stop" + })); + } + } catch (error) { + setErrorData({ + title: "There was an error stop the message", + list: [error.message], + }); + } + } + + return { begin, stop: handleStop, checkReLinkWs, sendAll, connectWS } +} + +/** + * build flow + * 校验每个节点,展示进度及结果;返回input_keys;end_of_stream断开链接 + * 主要校验节点并设置更新setTabsState的 formKeysData + * @returns + */ +const useBuild = (flow: FlowType, chatId: string) => { + const { setErrorData } = useContext(alertContext); + const { setTabsState } = useContext(TabsContext); + const { t } = useTranslation() + + // SSE 服务端推送 + async function streamNodeData(flow: FlowType, chatId: string) { + // Step 1: Make a POST request to send the flow data and receive a unique session ID + const { flowId } = await postBuildInit(flow, chatId); + // Step 2: Use the session ID to establish an SSE connection using EventSource + let validationResults = []; + let finished = false; + let buildEnd = false + const apiUrl = `/api/v1/build/stream/${flowId}?chat_id=${chatId}`; + const eventSource = new EventSource(apiUrl); + + eventSource.onmessage = (event) => { + // If the event is parseable, return + if (!event.data) { + return; + } + const parsedData = JSON.parse(event.data); + // if the event is the end of the stream, close the connection + if (parsedData.end_of_stream) { + eventSource.close(); // 结束关闭链接 + buildEnd = true + return; + } else if (parsedData.log) { + // If the event is a log, log it + // setSuccessData({ title: parsedData.log }); + } else if (parsedData.input_keys) { + setTabsState((old) => { + return { + ...old, + [flowId]: { + ...old[flowId], + formKeysData: parsedData, + }, + }; + }); + } else { + // setProgress(parsedData.progress); + validationResults.push(parsedData.valid); + } + }; + + eventSource.onerror = (error: any) => { + console.error("EventSource failed:", error); + eventSource.close(); + if (error.data) { + const parsedData = JSON.parse(error.data); + setErrorData({ title: parsedData.error }); + } + }; + // Step 3: Wait for the stream to finish + while (!finished) { + await new Promise((resolve) => setTimeout(resolve, 100)); + finished = buildEnd // validationResults.length === flow.data.nodes.length; + } + // Step 4: Return true if all nodes are valid, false otherwise + return validationResults.every((result) => result); + } + + // 延时器 + async function enforceMinimumLoadingTime( + startTime: number, + minimumLoadingTime: number + ) { + const elapsedTime = Date.now() - startTime; + const remainingTime = minimumLoadingTime - elapsedTime; + + if (remainingTime > 0) { + return new Promise((resolve) => setTimeout(resolve, remainingTime)); + } + } + + async function handleBuild() { + try { + const errors = flow.data.nodes.flatMap((n: NodeType) => validateNode(n, flow.data.edges)) + if (errors.length > 0) { + setErrorData({ + title: t('chat.buildError'), + list: errors, + }); + return; + } + + const minimumLoadingTime = 200; // in milliseconds + const startTime = Date.now(); + + await streamNodeData(flow, chatId); + await enforceMinimumLoadingTime(startTime, minimumLoadingTime); // 至少等200ms, 再继续(强制最小load时间) + } catch (error) { + console.error("Error:", error); + } finally { + } + } + + return handleBuild +} \ No newline at end of file diff --git a/src/pages/ChatAppPage/mobile/ChatPanneM.tsx b/src/pages/ChatAppPage/mobile/ChatPanneM.tsx index 8a7efbd..41c8f3a 100644 --- a/src/pages/ChatAppPage/mobile/ChatPanneM.tsx +++ b/src/pages/ChatAppPage/mobile/ChatPanneM.tsx @@ -7,7 +7,7 @@ import { Button } from "../../../components/ui/button"; import { alertContext } from "../../../contexts/alertContext"; import { TabsContext } from "../../../contexts/tabsContext"; import { getChatHistory, postBuildInit, postValidatePrompt } from "../../../controllers/API"; -import { Variable } from "../../../controllers/API/flow"; +import { Variable, getFlowApi } from "../../../controllers/API/flow"; import { sendAllProps } from "../../../types/api"; import { ChatMessageType } from "../../../types/chat"; import { FlowType, NodeType } from "../../../types/flow"; @@ -24,6 +24,10 @@ import { locationContext } from "../../../contexts/locationContext"; import titIconL from "../../../assets/chatM/tit-icon-l.png"; import titIconR from "../../../assets/chatM/tit-icon-r.png"; import duihuaSend from "../../../assets/chat/duihua-send.png"; +import { useAssistantStore } from "@/store/assistantStore"; +import ChatComponent from "@/components/bs-comp/chatComponent"; +import { useToast } from "@/components/bs-ui/toast/use-toast"; +import { useMessageStore } from "@/components/bs-comp/chatComponent/messageStore"; interface Iprops { chatId: string @@ -32,329 +36,110 @@ interface Iprops { version?: string } -export default forwardRef(function ChatPanne({ chatId, flow, queryString, version = 'v1' }: Iprops,ref) { +export default function ChatPanne({ customWsHost = '', data }) { + const { id, chatId, type } = data const { t } = useTranslation() - const { tabsState } = useContext(TabsContext); - - const { isRoom, isForm, isReport, checkPrompt } = useFlowState(flow) + const [flow, setFlow] = useState(null) + const flowRef = useRef(null) + const [assistant, setAssistant] = useState(null) + const { assistantState, loadAssistantState, destroy } = useAssistantStore() // build - const build = useBuild(flow, chatId) - // 消息列表 - const { messages, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll } = useMessages(chatId, flow) - // ws通信 - const { stop, connectWS, begin: chating, checkReLinkWs, sendAll } = useWebsocket(chatId, flow, setChatHistory, queryString, version) - // 停止状态 - const [isStop, setIsStop] = useState(true) - // 输入框状态 - const { inputState, inputEmpty, inputDisabled, inputRef, - formShow, setFormShow, - setInputState, setInputEmpty, handleTextAreaHeight } = useInputState({ flow, chatId, chating, messages, isForm, isReport }) + // const build = useBuild(flow, chatId) + const build = useBuild() + const { messages, loadHistoryMsg, loadMoreHistoryMsg, changeChatId } = useMessageStore() + useEffect(() => { + return destroy + }, []) - const { appConfig } = useContext(locationContext) - - // npc信息 - const [isNpcInfo, setIsNpcInfo] = useState(false) - // 对话信息 - const [isDuiHua, setIsDuiHua] = useState(false) - // 弹窗信息 - const [isPopUp, setIsPopUp] = useState(false) - // 引用弹窗信息 - const [isQuote, setIsQuote] = useState(false) - // 开始构建&切换初始化会话 - const initChat = async () => { - await checkPrompt(flow) - await build() - const historyData = version === 'v1' ? await loadHistory() : (initGuide(), []) - await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) - setInputState({ lock: false, errorMsg: '' }); - // 第一条消息,用来初始化会话 - sendAll({ - chatHistory: messages, - name: flow.name, - description: flow.description, - inputs: {}, - flow_id: flow.id, - chat_id: chatId - }) - - changeHistoryByScroll.current = false - // 自动聚焦 - if (inputRef.current) inputRef.current.value = '' - setTimeout(() => { - inputRef.current?.focus() - }, 500); - - const isNewChat = historyData.length === 0 || historyData[0].id === 9999 - setFormShow(isNewChat && isForm) + const init = async () => { + if (type === 'flow') { + setAssistant(null) + const _flow = await getFlowApi(id) + await build(_flow, chatId) + loadHistoryMsg(_flow.id, chatId) + flowRef.current = _flow + setFlow(_flow) + changeChatId(chatId) // ws + } else { + flowRef.current = null + setFlow(null) + const _assistant = await loadAssistantState(id) + loadHistoryMsg(_assistant.id, chatId) + setAssistant(_assistant) + changeChatId(chatId) // ws + } } useEffect(() => { - initChat() - }, [flow]) - // document.documentElement.addEventListener( - // 'touchstart', - // function (event) { - // if (event.touches.length > 1) { - // event.preventDefault(); - // } - // }, - // { - // passive: false, - // }, - // ); + if (!id) { + flowRef.current = null + setFlow(null) + setAssistant(null) + return + } + init() + }, [data]) + + // ws 请求数据包装 + const { tabsState } = useContext(TabsContext); + // 依赖 chatId更新闭包,不依赖 flow + const getWsParamData = (action, msg) => { + if (type === 'flow') { + const _flow = flowRef.current + let inputs = tabsState[_flow.id].formKeysData.input_keys; + const input = inputs.find((el: any) => !el.type) + const inputKey = input ? Object.keys(input)[0] : ''; + const msgData = { + chatHistory: messages, + flow_id: _flow.id, + chat_id: chatId, + name: _flow.name, + description: _flow.description, + inputs: {} + } as any + if (msg) msgData.inputs = { ...input, [inputKey]: msg } + if (formDataRef.current?.length) { + msgData.inputs.data = formDataRef.current + formDataRef.current = null + } + if (action === 'continue') msgData.action = action + return [msgData, inputKey] + } else { + const inputKey = 'input'; + const msgData = { + chatHistory: messages, + flow_id: '', + chat_id: chatId, + name: assistant.name, + description: assistant.desc, + inputs: {} + } as any + if (msg) msgData.inputs = { [inputKey]: msg } + if (data) msgData.inputs.data = data + if (action === 'continue') msgData.action = action + return [msgData, inputKey] + } + } + + // 应用链接 + const { appConfig } = useContext(locationContext) + const token = localStorage.getItem("ws_token") || ''; + let wsUrl = type === 'flow' ? `${appConfig.websocketHost}/api/v1/chat/${flowRef.current?.id}?type=L1&t=${token}` : + `${location.host}/api/v1/assistant/chat/${assistant?.id}?t=${token}` + + if (customWsHost) { + wsUrl = `${appConfig.websocketHost}${customWsHost}&t=${token}` + } + // sendmsg user name const sendUserName = useMemo(() => { + if (!flow) return '' const node = flow.data.nodes.find(el => el.data.type === 'AutoGenUser') return node?.data.node.template['name'].value || '' }, [flow]) - const handleSend = async () => { - const msg = inputRef.current?.value - setTimeout(() => { - if (inputRef.current) { - inputRef.current.value = '' - inputRef.current.style.height = 'auto' - } - setInputEmpty(true) - }, 100); - - if (msg.trim() === '') return - - setInputState({ lock: true, errorMsg: '' }); - let inputs = tabsState[flow.id].formKeysData.input_keys; - const input = inputs.find((el: any) => !el.type) - const inputKey = input ? Object.keys(input)[0] : ''; - setChatHistory((old) => { - let newChat = cloneDeep(old); - newChat.push({ - isSend: true, - message: { ...input, [inputKey]: msg }, - chatKey: inputKey, - thought: '', - category: '', - files: [], - end: false, - user_name: "" - }) - return newChat - }); - - await checkReLinkWs(async () => { - // await build() - await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) - }) - - const chatInfo = { - chat_id: chatId, - flow_id: flow.id, - inputs: { ...input, [inputKey]: msg } - } - // @ts-ignore - isRoom && chating ? sendAll({ action: "continue", ...chatInfo }) - : sendAll({ - chatHistory: messages, - name: flow.name, - description: flow.description, - ...chatInfo - }); - } - - - // 报表请求 - const sendReport = (items: Variable[], str) => { - let inputs = tabsState[flow.id].formKeysData.input_keys; - const input = inputs.find((el: any) => !el.type) - const inputKey = input ? Object.keys(input)[0] : ''; - setChatHistory((old) => { - let newChat = cloneDeep(old); - newChat.push({ - isSend: true, - message: { ...input, [inputKey]: str }, - chatKey: inputKey, - thought: '', - category: '', - files: [], - end: false, - user_name: "" - }) - return newChat - }); - - const data = items.map(item => ({ - id: item.nodeId, - name: item.name, - file_path: item.type === 'file' ? item.value : '', - value: item.type === 'file' ? '' : item.value - })) - - setIsStop(false) - setFormShow(false) - - sendAll({ - inputs: { - ...input, - [inputKey]: str, - data - }, - chatHistory: messages, - name: flow.name, - description: flow.description, - chat_id: chatId, - flow_id: flow.id, - }); - } - - // 溯源 - const [souce, setSouce] = useState(null) - - const thumbRef = useRef(null) - - return
- -
-
- {/*
setIsDuiHua(!isDuiHua)}> - -
*/} -

{flow.name}

- {/*
setIsNpcInfo(!isNpcInfo)}> - -
*/} -
-
-
- {/* 会话记录 */} -
- { - messages.map((c, i) => setSouce(c)} - onDislike={(chatId) => { thumbRef.current?.openModal(chatId) }} - onReSend={(msg) => { - inputRef.current.value = msg - handleSend() - }} - onEdit={(msg) => { inputRef.current.value = msg; setInputEmpty(!msg) }} - onSearch={(msg) => window.open(appConfig.dialogQuickSearch + encodeURIComponent(msg))} - >) - } -
- {/* 输入框 */} -
- {/*
*/} -
- -
- {/* - - */} -
- -
-
- {/* {inputState.errorMsg &&
{inputState.errorMsg}
} */} - {inputState.errorMsg &&
{inputState.errorMsg}
} -
-

{appConfig.dialogTips}

-
-
- {(isRoom || isReport) &&
- -
} - {/* 源文件类型 */} - setSouce(null)}> - {/* 表单 */} - {isForm && formShow && } - {/* 踩 反馈 */} - - - - - - - - - - -
-}); -/** - * 输入框状态 - * 分析 flow状态 - * return 该技能含有表单、有报表、群聊 - * @returns - */ -const useInputState = ({ flow, chatId, chating, messages, isForm, isReport }) => { - const { tabsState } = useContext(TabsContext); - - const [inputState, setInputState] = useState({ - lock: false, - errorMsg: '' - }) - // 输入问答 - const inputRef = useRef(null) - useEffect(() => { - !chating && setTimeout(() => { - // 对话结束自动聚焦 - inputRef.current?.focus() - }, 1000); - }, [chating]) - // input 滚动 - const [inputEmpty, setInputEmpty] = useState(true) - useEffect(() => { - setInputEmpty(true) - if (inputRef.current) inputRef.current.value = '' - }, [chatId]) - - // 获取上传file input - const fileInputs = useMemo(() => { - return tabsState[flow.id]?.formKeysData?.input_keys?.filter((input: any) => input.type === 'file') - }, [tabsState, flow]) - - const handleTextAreaHeight = (e) => { - const textarea = e.target - textarea.style.height = 'auto' - textarea.style.height = textarea.scrollHeight + 'px' - setInputEmpty(textarea.value.trim() === '') - } - // input disabled - const inputDisabled = useMemo(() => { - return inputState.lock - // 表单 && 没回话或只有一个引导词 - || (isForm && (messages.length === 0 || (messages.length === 1 && messages[0].id === 9999))) - || isReport - }, [inputState, fileInputs, isReport]) - - // 表单收起 - const [formShow, setFormShow] = useState(true) - return { - inputState, inputEmpty, inputDisabled, inputRef, - formShow, setFormShow, - setInputState, setInputEmpty, handleTextAreaHeight - } -} - -/** - * flow state - * 分析 flow状态 - * return 该技能含有表单、有报表、群聊 - * @returns - */ -const useFlowState = (flow: FlowType) => { const flowSate = useMemo(() => { + if (!flow) return { isRoom: false, isForm: false, isReport: false } // 是否群聊 const isRoom = !!flow.data?.nodes.find(node => node.data.type === "AutoGenChain") // 是否展示表单 @@ -364,491 +149,290 @@ const useFlowState = (flow: FlowType) => { return { isRoom, isForm, isReport } }, [flow]) - // propmt类型补充自定义字段 - const checkPrompt = async (_flow) => { - const params = _flow.data.nodes.map(node => { - const temps = [] - const temp = node.data.node.template - Object.keys(temp).map(key => { - const { type, value } = temp[key] - if (type === 'prompt' && !!value) !temps.length && temps.push({ name: key, template: value, data: node.data }) - }) - return temps - }).flat() + // 发送表单 (提交-》event触发发送-》getWsParamData获取参数时追加 data) + const formDataRef = useRef(null) + const sendReport = (items: Variable[], str) => { - const promises = params.map(param => { - return postValidatePrompt(param.name, param.template, param.data.node).then(res => { - if (res) param.data.node = res.frontend_node - }) - }) - return Promise.all(promises) - } + formDataRef.current = items.map(item => ({ + id: item.nodeId, + name: item.name, + file_path: item.type === 'file' ? item.value : '', + value: item.type === 'file' ? '' : item.value + })) - return { ...flowSate, checkPrompt } -} - -/** - * 消息列表模块 - * 翻页、追加、历史 - * @returns - */ -const useMessages = (chatId, flow) => { - const [chatHistory, setChatHistory] = useState([]); - const lastIdRef = useRef(0) - // 控制开启自动随消息滚动(临时方案) - const changeHistoryByScroll = useRef(false) - - const loadIdRef = useRef('') // 记录最后一个加载的 chatId - // 获取聊天记录 - const loadHistory = async (lastId?: number) => { - loadIdRef.current = chatId - - const res = await getChatHistory(flow.id, chatId, lastId ? 10 : 30, lastId) - const hisData = res.map(item => { - // let count = 0 - let { message, files, is_bot, intermediate_steps, ...other } = item - try { - message = message && message[0] === '{' ? JSON.parse(message.replace(/([\t\n"])/g, '\\$1').replace(/'/g, '"')) : message || '' - } catch (e) { - // 未考虑的情况暂不处理 + const myEvent = new CustomEvent('userResendMsgEvent', { + detail: { + send: true, + message: str } - return { - ...other, - chatKey: typeof message === 'string' ? undefined : Object.keys(message)[0], - end: true, - files: files ? JSON.parse(files) : [], - isSend: !is_bot, - message, - thought: intermediate_steps, - noAccess: true - } - }) - lastIdRef.current = hisData[hisData.length - 1]?.id || lastIdRef.current || 0 // 记录最后一个id - - let historyData = [] - if (lastId) { - historyData = [...hisData.reverse(), ...chatHistory] - } else if (loadIdRef.current === chatId) { // 保证同一会话 - historyData = hisData.reverse() - } - setChatHistory(historyData) - const pageSize = historyData.length < 30 ? 30 : 10 // 先偷懒 - if (hisData.length < pageSize) initGuide() - return historyData + }); + document.dispatchEvent(myEvent); } + // const { tabsState } = useContext(TabsContext); - const loadLock = useRef(false) - const currentIdRef = useRef(0) - const loadNextPage = async () => { - if (loadLock.current) return - if (currentIdRef.current === lastIdRef.current) return // 最后一个相同表示聊天记录已到顶 - loadLock.current = true - currentIdRef.current = lastIdRef.current - changeHistoryByScroll.current = true - await loadHistory(currentIdRef.current) - loadLock.current = false - // 滚动 hack TODO 滚动翻页设计 - setTimeout(() => { - changeHistoryByScroll.current = false - }, 500); - } + // const { isRoom, isForm, isReport, checkPrompt } = useFlowState(flow) - const initGuide = () => { - const guideMsg = { - "category": "system", - "chat_id": chatId, - "end": true, - "create_time": "", - "extra": "{}", - "files": [], - "flow_id": flow.id, - "id": 9999, - "thought": flow.guide_word, - "is_bot": true, - "liked": 0, - "message": '', - "receiver": null, - "remark": null, - "sender": "", - "solved": 0, - isSend: false, - "source": 0, - "type": "end", - "update_time": "", - noAccess: true, - "user_id": 0 - } - flow.guide_word && setChatHistory((chatHistory) => - chatHistory[0]?.id === 9999 ? chatHistory : [guideMsg, ...chatHistory] - ) - } + // // build + // const build = useBuild(flow, chatId) + // // 消息列表 + // const { messages, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll } = useMessages(chatId, flow) + // // ws通信 + // const { stop, connectWS, begin: chating, checkReLinkWs, sendAll } = useWebsocket(chatId, flow, setChatHistory, queryString, version) + // // 停止状态 + // const [isStop, setIsStop] = useState(true) + // // 输入框状态 + // const { inputState, inputEmpty, inputDisabled, inputRef, + // formShow, setFormShow, + // setInputState, setInputEmpty, handleTextAreaHeight } = useInputState({ flow, chatId, chating, messages, isForm, isReport }) - // 消息滚动 - const messagesRef = useRef(null); - useEffect(() => { - if (messagesRef.current && !changeHistoryByScroll.current) { // 滚动加载不触发 - messagesRef.current.scrollTop = messagesRef.current.scrollHeight; - } - }, [chatHistory, changeHistoryByScroll]); + // const { appConfig } = useContext(locationContext) - // 消息滚动加载 - useEffect(() => { - function handleScroll() { - if (messagesRef.current.scrollTop <= 30) { - loadNextPage() - } - } + // // npc信息 + // const [isNpcInfo, setIsNpcInfo] = useState(false) + // // 对话信息 + // const [isDuiHua, setIsDuiHua] = useState(false) + // // 弹窗信息 + // const [isPopUp, setIsPopUp] = useState(false) + // // 引用弹窗信息 + // const [isQuote, setIsQuote] = useState(false) + // // 开始构建&切换初始化会话 + // const initChat = async () => { + // await checkPrompt(flow) + // await build() + // const historyData = version === 'v1' ? await loadHistory() : (initGuide(), []) + // await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) + // setInputState({ lock: false, errorMsg: '' }); + // // 第一条消息,用来初始化会话 + // sendAll({ + // chatHistory: messages, + // name: flow.name, + // description: flow.description, + // inputs: {}, + // flow_id: flow.id, + // chat_id: chatId + // }) - messagesRef.current?.addEventListener('scroll', handleScroll); - return () => messagesRef.current?.removeEventListener('scroll', handleScroll) - }, [messagesRef.current, chatHistory, chatId]); + // changeHistoryByScroll.current = false + // // 自动聚焦 + // if (inputRef.current) inputRef.current.value = '' + // setTimeout(() => { + // inputRef.current?.focus() + // }, 500); - return { - messages: chatHistory, messagesRef, loadHistory, setChatHistory, initGuide, changeHistoryByScroll - } -} + // const isNewChat = historyData.length === 0 || historyData[0].id === 9999 + // setFormShow(isNewChat && isForm) + // } + // useEffect(() => { + // initChat() + // }, [flow]) + // // document.documentElement.addEventListener( + // // 'touchstart', + // // function (event) { + // // if (event.touches.length > 1) { + // // event.preventDefault(); + // // } + // // }, + // // { + // // passive: false, + // // }, + // // ); + // // sendmsg user name + // const sendUserName = useMemo(() => { + // const node = flow.data.nodes.find(el => el.data.type === 'AutoGenUser') + // return node?.data.node.template['name'].value || '' + // }, [flow]) -/** - * websocket 通信 - * 建立连接、重连、断开、接收、发送 - * @returns - */ -const useWebsocket = (chatId, flow, setChatHistory, queryString, version) => { - const ws = useRef(null); - // 接收ws状态 - const [begin, setBegin] = useState(false) - const { setErrorData } = useContext(alertContext); - const { t } = useTranslation() + // const handleSend = async () => { + // const msg = inputRef.current?.value + // setTimeout(() => { + // if (inputRef.current) { + // inputRef.current.value = '' + // inputRef.current.style.height = 'auto' + // } + // setInputEmpty(true) + // }, 100); - const { appConfig } = useContext(locationContext) + // if (msg.trim() === '') return - const chatIdRef = useRef(chatId); - useEffect(() => { - chatIdRef.current = chatId; - }, [chatId]) + // setInputState({ lock: true, errorMsg: '' }); + // let inputs = tabsState[flow.id].formKeysData.input_keys; + // const input = inputs.find((el: any) => !el.type) + // const inputKey = input ? Object.keys(input)[0] : ''; + // setChatHistory((old) => { + // let newChat = cloneDeep(old); + // newChat.push({ + // isSend: true, + // message: { ...input, [inputKey]: msg }, + // chatKey: inputKey, + // thought: '', + // category: '', + // files: [], + // end: false, + // user_name: "" + // }) + // return newChat + // }); - function heartbeat() { - if (!ws.current) return; - if (ws.current.readyState !== 1) return; - ws.current.send("heartbeat"); - setTimeout(heartbeat, 30000); - } + // await checkReLinkWs(async () => { + // // await build() + // await connectWS({ setInputState, setIsStop, changeHistoryByScroll }) + // }) - function getWebSocketUrl(flowId, isDevelopment = false) { - const token = localStorage.getItem("ws_token") || ''; + // const chatInfo = { + // chat_id: chatId, + // flow_id: flow.id, + // inputs: { ...input, [inputKey]: msg } + // } + // // @ts-ignore + // isRoom && chating ? sendAll({ action: "continue", ...chatInfo }) + // : sendAll({ + // chatHistory: messages, + // name: flow.name, + // description: flow.description, + // ...chatInfo + // }); + // } - const isSecureProtocol = window.location.protocol === "https:"; - const webSocketProtocol = isSecureProtocol ? "wss" : "ws"; - const host = appConfig.websocketHost || window.location.host // isDevelopment ? "localhost:7860" : window.location.host; - const chatEndpoint = version === 'v1' ? `/api/v1/chat/${flowId}?type=L1&chat_id=${chatId}&t=${token}` - : `/api/v2/chat/ws/${flowId}?type=L1&chat_id=${chatId}${queryString}&t=${token}` - return `${webSocketProtocol}://${host}${chatEndpoint}`; - } + // // 报表请求 + // const sendReport = (items: Variable[], str) => { + // let inputs = tabsState[flow.id].formKeysData.input_keys; + // const input = inputs.find((el: any) => !el.type) + // const inputKey = input ? Object.keys(input)[0] : ''; + // setChatHistory((old) => { + // let newChat = cloneDeep(old); + // newChat.push({ + // isSend: true, + // message: { ...input, [inputKey]: str }, + // chatKey: inputKey, + // thought: '', + // category: '', + // files: [], + // end: false, + // user_name: "" + // }) + // return newChat + // }); - const newChatStart = useRef(false) // 处理当前会话上下文丢失,阻止上一次打字机效果 - // 自动重连次数 - const tryReLinkCount = useRef(0) - const reConnect = (params) => { - if (tryReLinkCount.current <= 3) { - connectWS(params) - tryReLinkCount.current++ - } else { - console.warn('超过最大重试次数 :>> '); - } - } - useEffect(() => { - tryReLinkCount.current = 0 - newChatStart.current = true - }, [chatId]) + // const data = items.map(item => ({ + // id: item.nodeId, + // name: item.name, + // file_path: item.type === 'file' ? item.value : '', + // value: item.type === 'file' ? '' : item.value + // })) - function connectWS(params) { - const { setInputState, setIsStop, changeHistoryByScroll } = params - if (ws.current) return Promise.resolve('ok'); + // setIsStop(false) + // setFormShow(false) - // 连接断开重链接 - return new Promise((res, rej) => { - try { - const urlWs = getWebSocketUrl( - flow.id, - process.env.NODE_ENV === "development" - ); - const newWs = new WebSocket(urlWs); - newWs.onopen = () => { - console.log("WebSocket connection established!"); - res('ok') - // heartbeat() - }; - newWs.onmessage = (event) => { - const data = JSON.parse(event.data); - if (data.chat_id !== chatIdRef.current) return - console.log('newChatStart.current :>> ', newChatStart.current); + // sendAll({ + // inputs: { + // ...input, + // [inputKey]: str, + // data + // }, + // chatHistory: messages, + // name: flow.name, + // description: flow.description, + // chat_id: chatId, + // flow_id: flow.id, + // }); + // } - const errorMsg = data.category === 'error' ? data.intermediate_steps : '' + // // 溯源 + // const [souce, setSouce] = useState(null) - if (newChatStart.current) { - if (data.type === 'close') { - newChatStart.current = false - return setInputState({ lock: false, errorMsg }) - } else { - return setInputState({ lock: true, errorMsg }) + // const thumbRef = useRef(null) + + return
+ +
+
+ {/*
setIsDuiHua(!isDuiHua)}> + +
*/} +

{flow && flow.name}

+ {/*
setIsNpcInfo(!isNpcInfo)}> + +
*/} +
+
+
+ { + flow &&
+ {/* {flow && } */} + {/*
+ + {flow.name} +
*/} + loadMoreHistoryMsg(flow.id)} + inputForm={flowSate.isForm ? : null} + /> + {/*
+ { + messages.map((c, i) => setSouce(c)} + onDislike={(chatId) => { thumbRef.current?.openModal(chatId) }} + onReSend={(msg) => { + inputRef.current.value = msg + handleSend() + }} + onEdit={(msg) => { inputRef.current.value = msg; setInputEmpty(!msg) }} + onSearch={(msg) => window.open(appConfig.dialogQuickSearch + encodeURIComponent(msg))} + >) } - } - // 异常类型处理,提示 - if (errorMsg) return setInputState({ lock: true, errorMsg }) - - handleWsMessage({ data, setIsStop, setInputState, changeHistoryByScroll }); - // get chat history - // 群聊@自己时,开启input - if (data.type === 'end' && data.receiver?.is_self) { - setInputState({ lock: false, errorMsg: '' }) - } - }; - newWs.onclose = (event) => { - ws.current = null - - handleOnClose({ event, setIsStop, setInputState }); - // reConnect(params) - }; - newWs.onerror = (ev) => { - ws.current = null - - console.error('链接异常error', ev); - setIsStop(true) - - setErrorData({ - title: `${t('chat.networkError')}:`, - list: [ - t('chat.networkErrorList1'), - t('chat.networkErrorList2'), - t('chat.networkErrorList3') - ], - }); - reConnect(params) - }; - ws.current = newWs; - console.log('newWs :>> ', newWs); - } catch (error) { - console.error('创建链接异常', error); - rej(error) +
*/} +
} - }) - } +
+ {/* {(isRoom || isReport) &&
+ +
} */} + {/* 源文件类型 */} + {/* setSouce(null)}> */} + {/* 表单 */} + {/* {isForm && formShow && } */} + {/* 踩 反馈 */} + {/* - var isStream = false; - function handleWsMessage({ data, setIsStop, setInputState, changeHistoryByScroll }) { - if (Array.isArray(data) && data.length) return - if (data.type === "begin") { - setBegin(true) - setIsStop(false) - changeHistoryByScroll.current = false - } - if (data.type === "close") { - setBegin(false) - setIsStop(true) - setInputState({ lock: false, errorMsg: '' }); - changeHistoryByScroll.current = true - } - if (data.type === "start") { - setChatHistory((old) => { - let newChat = cloneDeep(old); - newChat.push({ - isSend: false, - message: '', - chatKey: '', - thought: data.intermediate_steps || '', - category: data.category || '', - files: [], - end: false - }) - return newChat - }); - isStream = true; - } - if (data.type === "stream" && isStream) { - updateLastMessage({ str: data.message, thought: data.intermediate_steps }); - } - if (data.type === "end") { - updateLastMessage({ - ...data, - str: data.message, - files: data.files || null, - end: true, - thought: data.intermediate_steps || '', - cate: data.category || '', - messageId: data.message_id, - noAccess: false, - liked: 0 - }); + - isStream = false; - } - } + - function updateLastMessage({ str, thought = '', end = false, files = [], cate = '', messageId = 0, source = false, noAccess = false, ...data }: { - str: string; - messageId?: number - thought?: string; - cate?: string; - end?: boolean; - files?: Array; - source?: boolean - noAccess?: boolean - }) { - setChatHistory((old) => { - const newChats = [...old] - // console.log('newchats :>> ', newChats); - let chatsLen = newChats.length - const prevChat = newChats[chatsLen - 2] - // hack 过滤重复最后消息 - if (end - && str - && chatsLen > 1 - && str === prevChat.message - // && data.sender === prevChat.sender - && !prevChat.thought) { - newChats.splice(chatsLen - 2, 1) // 删上一条 - chatsLen = newChats.length - } - // 更新 - const lastChat = newChats[chatsLen - 1] - const newLastChat = { - ...newChats[chatsLen - 1], - ...data, - id: messageId, - message: lastChat.message + str, - thought: lastChat.thought + (thought ? `${thought}\n` : ''), - files, - category: cate, - source, - noAccess, - end - } - newChats[chatsLen - 1] = newLastChat - // start - end 之间没有内容删除load - if (end && !(newLastChat.files.length || newLastChat.thought || newLastChat.message)) { - newChats.pop() - } - return newChats; - }); - } + - // 发送ws - async function sendAll(data: sendAllProps) { - try { - if (ws.current) { - if (JSON.stringify(data.inputs) !== '{}') { - newChatStart.current = false - } - ws.current.send(JSON.stringify(data)); - } - } catch (error) { - setErrorData({ - title: "There was an error sending the message", - list: [error.message], - }); - } - } + */} - // 处理主动断开 - function handleOnClose({ event, setIsStop, setInputState }) { - console.error('链接手动断开 event :>> ', event); - setIsStop(true) - setBegin(false) +
+}; - if ([1005, 1008].includes(event.code)) { - console.warn('即将废弃 :>> '); - setInputState({ lock: true, errorMsg: event.reason }); - } else { - if (event.reason) { - setErrorData({ title: event.reason }); - // setChatHistory((old) => { - // let newChat = cloneDeep(old); - // if (newChat.length) { - // newChat[newChat.length - 1].end = true; - // } - // newChat.push({ end: true, message: `${t('chat.connectionbreakTip')}${event.reason}`, isSend: false, chatKey: '', files: [] }); - // return newChat - // }) - } - setInputState({ lock: false, errorMsg: '' }); - } - } - - useEffect(() => { - // destory - return () => { - // close prev connection - if (ws.current) { - switch (ws.current.readyState) { - case WebSocket.OPEN: - console.warn('前端主动关闭1') - ws.current.close() - ; break; - case WebSocket.CONNECTING: - ws.current.onopen = () => { - console.warn('前端主动关闭2') - ws.current.close() - }; - } - ws.current = null - } - } - }, []) - - // 检测并重连 - const checkReLinkWs = async (reConnect) => { - if (ws.current) return true - // 重连 - // 上一条加loading - setChatHistory((old) => { - let newChat = [...old]; - newChat[newChat.length - 1].category = 'loading'; - return newChat; - }); - await reConnect() - // 链接成功 - // 上一条去loading - setChatHistory((old) => { - let newChat = [...old]; - newChat[newChat.length - 1].category = ''; - return newChat; - }); - } - - const handleStop = () => { - try { - if (ws) { - ws.current.send(JSON.stringify({ - "action": "stop" - })); - } - } catch (error) { - setErrorData({ - title: "There was an error stop the message", - list: [error.message], - }); - } - } - - return { begin, stop: handleStop, checkReLinkWs, sendAll, connectWS } -} /** * build flow * 校验每个节点,展示进度及结果;返回input_keys;end_of_stream断开链接 * 主要校验节点并设置更新setTabsState的 formKeysData - * @returns */ -const useBuild = (flow: FlowType, chatId: string) => { - const { setErrorData } = useContext(alertContext); + +const useBuild = () => { + const { toast } = useToast() const { setTabsState } = useContext(TabsContext); const { t } = useTranslation() // SSE 服务端推送 async function streamNodeData(flow: FlowType, chatId: string) { // Step 1: Make a POST request to send the flow data and receive a unique session ID - const { flowId } = await postBuildInit(flow, chatId); + console.log(flow,chatId) + const { flowId } = await postBuildInit({ flow, chatId }); // Step 2: Use the session ID to establish an SSE connection using EventSource let validationResults = []; let finished = false; @@ -891,7 +475,11 @@ const useBuild = (flow: FlowType, chatId: string) => { eventSource.close(); if (error.data) { const parsedData = JSON.parse(error.data); - setErrorData({ title: parsedData.error }); + toast({ + title: parsedData.error, + variant: 'error', + description: '' + }); } }; // Step 3: Wait for the stream to finish @@ -916,15 +504,15 @@ const useBuild = (flow: FlowType, chatId: string) => { } } - async function handleBuild() { + async function handleBuild(flow: FlowType, chatId: string) { try { const errors = flow.data.nodes.flatMap((n: NodeType) => validateNode(n, flow.data.edges)) if (errors.length > 0) { - setErrorData({ + return toast({ title: t('chat.buildError'), - list: errors, + variant: 'error', + description: errors }); - return; } const minimumLoadingTime = 200; // in milliseconds diff --git a/src/pages/ChatAppPage/mobile/chatShareM copy.tsx b/src/pages/ChatAppPage/mobile/chatShareM copy.tsx new file mode 100644 index 0000000..d45c66f --- /dev/null +++ b/src/pages/ChatAppPage/mobile/chatShareM copy.tsx @@ -0,0 +1,153 @@ +// 嵌iframe、适配移动端 +import { useEffect, useMemo, useState, useRef, useContext } from "react"; +import { useLocation, useParams } from "react-router-dom"; +import { getFlowApi, readOnlineFlows } from "../../../controllers/API/flow"; +import { FlowType } from "../../../types/flow"; +import { generateUUID } from "../../../utils"; +import ChatPanneM from "./ChatPanneM"; +import { useTranslation } from "react-i18next"; +import { deleteChatApi, getChatsApi } from "../../../controllers/API"; +import { captureAndAlertRequestErrorHoc } from "../../../controllers/request"; +import { useDebounce, useTable } from "../../../util/hook"; +import { TabsContext } from "../../../contexts/tabsContext"; +import SkillTemps from "../../SkillPage/components/SkillTemps"; +import titIconL from "../../../assets/chatM/tit-icon-l.png"; +import titIconR from "../../../assets/chatM/tit-icon-r.png"; + +export default function chatShare() { + const { id: flowId } = useParams() + const location = useLocation(); + const searchParams = new URLSearchParams(location.search); + const libId = searchParams.get('lib') + const tweak = searchParams.get('tweak') + const { t } = useTranslation(); + const [open, setOpen] = useState(false) + // 对话列表 + const { chatList, chatsRef, addChat, deleteChat } = useChatList() + const queryString = useMemo(() => { + const params = []; + + if (libId) params.push(`knowledge_id=${libId}`); + if (tweak) params.push(`tweak=${tweak}`); + + return params.length > 0 ? `&${params.join('&')}` : ''; + }, [libId, tweak]) + const chatIdRef = useRef('') + const handlerSelectFlow = async (node: FlowType) => { + // 会话ID + chatIdRef.current = generateUUID(32) + setOpen(false) + // add list + addChat({ + "flow_name": node.name, + "flow_description": node.description, + "flow_id": node.id, + "chat_id": chatIdRef.current, + "create_time": "-", + "update_time": "-" + }) + + const flow = await getFlowApi(node.id) + setFlow(flow) + setChatId(chatIdRef.current) + // setFace(false) + } + // + const { flow: initFlow } = useContext(TabsContext); + const [flow, setFlow] = useState(null) + const { + data: onlineFlows, + loading, + search, + } = useTable({}, (param) => + readOnlineFlows(param.page, param.keyword).then((res) => { + return res; + }) + ); + const [chatId, setChatId] = useState('') + console.log(flowId,libId,tweak) + useEffect(() => { + flowId && getFlowApi(flowId).then(node => { + // 会话ID + setFlow(node) + setChatId(generateUUID(32)) + }) + }, [flowId]) + // select chat + const handleSelectChat = useDebounce(async (chat) => { + if (chat.chat_id === chatId) return + + const flow = initFlow?.id === chat.flow_id ? initFlow : await getFlowApi(chat.flow_id) + + // if (!flow) { + // setInputState({ lock: true, errorCode: '1004' }) + // clearHistory() + // return setFace(false) + // } + + setFlow(flow) + setChatId(chat.chat_id) + }, 100, false) + + const wsUrl = useMemo(() => { + const params = []; + + if (libId) params.push(`knowledge_id=${libId}`); + if (tweak) params.push(`tweak=${tweak}`); + + const paramStr = params.length > 0 ? `${params.join('&')}` : ''; + + return `/api/v2/chat/ws/${flowId}?type=L1&${paramStr}` + }, [libId, tweak]) + + const [data] = useState({ id: flowId, chatId: generateUUID(32), type: 'flow' }) + + if (!flowId) return
请选择技能
+ + return
+ {/*
+ +

对话名称

+ +
*/} + {/* {flow + ?
+ {flow && } +
+ :
+

{t('chat.selectChat')}

+
} */} + +
+ // flow ? : null +}; +/** + * 本地对话列表 + */ +const useChatList = () => { + const [chatList, setChatList] = useState([]) + const chatsRef = useRef(null) + + useEffect(() => { + getChatsApi().then(setChatList) + }, []) + + return { + chatList, + chatsRef, + addChat: (chat) => { + const newList = [chat, ...chatList] + // localStorage.setItem(ITEM_KEY, JSON.stringify(newList)) + setChatList(newList) + setTimeout(() => { + chatsRef.current.scrollTop = 1 + }, 0); + }, + deleteChat: (id: string) => { + // api + captureAndAlertRequestErrorHoc(deleteChatApi(id).then(res => { + setChatList(oldList => oldList.filter(item => item.chat_id !== id)) + })) + } + } +} \ No newline at end of file diff --git a/src/pages/ChatAppPage/mobile/chatShareM.tsx b/src/pages/ChatAppPage/mobile/chatShareM.tsx index f6e8605..d45c66f 100644 --- a/src/pages/ChatAppPage/mobile/chatShareM.tsx +++ b/src/pages/ChatAppPage/mobile/chatShareM.tsx @@ -73,21 +73,35 @@ export default function chatShare() { setChatId(generateUUID(32)) }) }, [flowId]) - // select chat - const handleSelectChat = useDebounce(async (chat) => { - if (chat.chat_id === chatId) return + // select chat + const handleSelectChat = useDebounce(async (chat) => { + if (chat.chat_id === chatId) return - const flow = initFlow?.id === chat.flow_id ? initFlow : await getFlowApi(chat.flow_id) + const flow = initFlow?.id === chat.flow_id ? initFlow : await getFlowApi(chat.flow_id) - // if (!flow) { - // setInputState({ lock: true, errorCode: '1004' }) - // clearHistory() - // return setFace(false) - // } + // if (!flow) { + // setInputState({ lock: true, errorCode: '1004' }) + // clearHistory() + // return setFace(false) + // } + + setFlow(flow) + setChatId(chat.chat_id) + }, 100, false) + + const wsUrl = useMemo(() => { + const params = []; + + if (libId) params.push(`knowledge_id=${libId}`); + if (tweak) params.push(`tweak=${tweak}`); + + const paramStr = params.length > 0 ? `${params.join('&')}` : ''; + + return `/api/v2/chat/ws/${flowId}?type=L1&${paramStr}` + }, [libId, tweak]) + + const [data] = useState({ id: flowId, chatId: generateUUID(32), type: 'flow' }) - setFlow(flow) - setChatId(chat.chat_id) -}, 100, false) if (!flowId) return
请选择技能
return
@@ -96,13 +110,14 @@ export default function chatShare() {

对话名称

*/} - {flow + {/* {flow ?
{flow && }
:

{t('chat.selectChat')}

-
} +
} */} +
// flow ? : null }; diff --git a/src/pages/FileLibPage/files.tsx b/src/pages/FileLibPage/files.tsx index c4d55c3..254f475 100755 --- a/src/pages/FileLibPage/files.tsx +++ b/src/pages/FileLibPage/files.tsx @@ -46,7 +46,7 @@ export default function FilesPage() { }) ) // loadData(); - setTimeout(() => reload(), 5000); + // setTimeout(() => reload(), 5000); const [hasPermission, setHasPermission] = useState(true) const { appConfig } = useContext(locationContext) diff --git a/src/pages/SkillPage/components/CardSelectVersion.tsx b/src/pages/SkillPage/components/CardSelectVersion.tsx index 8922f18..a7cad03 100644 --- a/src/pages/SkillPage/components/CardSelectVersion.tsx +++ b/src/pages/SkillPage/components/CardSelectVersion.tsx @@ -13,7 +13,7 @@ const SelectComp = ({ value, onChange = (id) => { }, data, disabled = false }) = } return diff --git a/src/pages/SkillPage/components/EditTool.tsx b/src/pages/SkillPage/components/EditTool.tsx index 667ecc5..b460842 100644 --- a/src/pages/SkillPage/components/EditTool.tsx +++ b/src/pages/SkillPage/components/EditTool.tsx @@ -14,6 +14,7 @@ import { captureAndAlertRequestErrorHoc } from "@/controllers/request" import { PlusIcon } from "@radix-ui/react-icons" import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react" import { useTranslation } from "react-i18next" +import borderR from "../../../assets/npc/border-r.png"; const TestDialog = forwardRef((props: any, ref) => { const {t} = useTranslation() @@ -116,7 +117,7 @@ const TestDialog = forwardRef((props: any, ref) => {
- - +
{/* 自动配置 */} @@ -190,7 +190,7 @@ export default function AutoPromptDialog({ onOpenChange }) { {/* 开场白 */}
{t('build.openingRemarks')}{LoadType.GuideWord === loading && }
- +
{/* 引导词 */} @@ -198,7 +198,7 @@ export default function AutoPromptDialog({ onOpenChange }) {
{t('build.guidingQuestions')}{LoadType.GuideQuestion === loading && }
{ question.map(qs => ( -

{qs}

+

{qs}

)) } diff --git a/src/pages/SkillPage/components/editAssistant/EditAssistantDialog.tsx b/src/pages/SkillPage/components/editAssistant/EditAssistantDialog.tsx index ba7c157..d111148 100644 --- a/src/pages/SkillPage/components/editAssistant/EditAssistantDialog.tsx +++ b/src/pages/SkillPage/components/editAssistant/EditAssistantDialog.tsx @@ -1,20 +1,23 @@ +import { TitleIconBg } from "@/components/bs-comp/cardComponent"; import { Button } from "@/components/bs-ui/button"; import { DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/bs-ui/dialog"; import { Input, Textarea } from "@/components/bs-ui/input"; import { useToast } from "@/components/bs-ui/toast/use-toast"; import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; +import npcIcon from "../../../../assets/npc/npcIcon.png"; +import huifumoren from "../../../../assets/npc/huifumoren.png"; +import { uploadNpcHeaderLibFileWithProgress } from "@/modals/UploadModal/upload"; -export default function EditAssistantDialog({ name, desc, onSave }) { +export default function EditAssistantDialog({ name, desc, avatar_img, avatar_color, onSave }) { const { t } = useTranslation() // State for form fields - const [formData, setFormData] = useState({ name: '', desc: '' }); - + const [formData, setFormData] = useState({ name: '', desc: '', avatar_img: '', avatar_color: '' }); useEffect(() => { - setFormData({ name, desc }) - }, [name, desc]) - // console.log(formData, name, desc); + setFormData({ name, desc, avatar_img, avatar_color }) + }, [name, desc, avatar_img, avatar_color]) + console.log(formData, name, desc, avatar_img, avatar_color); // State for errors const [errors, setErrors] = useState({}); @@ -76,27 +79,62 @@ export default function EditAssistantDialog({ name, desc, onSave }) { }; - return + const handleButtonClick = () => { + // Create a file input element + const input = document.createElement("input"); + input.type = "file"; + input.accept = "image/*"; + input.style.display = "none"; // Hidden from view + input.multiple = false; // Allow only one file selection + + input.onchange = (e: Event) => { + // setLoading(true); + // Get the selected file + const file = (e.target as HTMLInputElement).files?.[0]; + // Check if the file type is correct + // Upload the file + uploadNpcHeaderLibFileWithProgress(file, (progress) => { }).then(res => { + // setLoading(false); + setFormData({ name, desc, avatar_img: res, avatar_color }) + }) + }; + // Trigger the file selection dialog + input.click(); + }; + + return - {t('build.editAssistant')} + {t('build.editAssistant')}
-
- - - {errors.name &&

{errors.name}

} +
+ + {/* */} + +
+ +
setFormData({ name, desc, avatar_img: '', avatar_color })}> + + 恢复默认 +
+
- -