Skip to content

Commit

Permalink
feat: without return over 10 seconds (InternLM#146)
Browse files Browse the repository at this point in the history
  • Loading branch information
BetterSnail authored Aug 13, 2024
1 parent d66aa86 commit 1a4fd82
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 134 deletions.
5 changes: 2 additions & 3 deletions frontend/React/src/components/answer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,14 @@ interface IProps {
response: string;
draft: string;
chatIsOver: boolean;
mapWidth: number;
handleHistory: (info: any) => void;
};

const Answer = ({ renderData, isEnd, chatIsOver, response = '', draft = '', mapWidth, handleHistory }: IProps) => {
const Answer = ({ renderData, isEnd, chatIsOver, response = '', draft = '', handleHistory }: IProps) => {
return <div className={styles.answer}>
{
renderData?.length > 0 ? <div className={styles.inner}>
<MindMapGraph isEnd={isEnd} renderData={renderData} handleHistory={handleHistory} mapWidth={mapWidth} />
<MindMapGraph isEnd={isEnd} renderData={renderData} handleHistory={handleHistory} />
</div> : <></>
}
{
Expand Down
8 changes: 5 additions & 3 deletions frontend/React/src/components/chat-right/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ const ChatRight = ({ nodeInfo, stashInfo = null, historyNode = null, toggleRight
};
// 高亮searchList
const highLightSearchList = (ids: any) => {
console.log('high light ids----------', ids);
// console.log('high light ids----------', ids);
const timeout = historyNode ? 0 : 3000;
setCurrentStep(1);
const highlightArr: any = [...searchList];
highlightArr.forEach((item: any) => {
Expand All @@ -59,7 +60,7 @@ const ChatRight = ({ nodeInfo, stashInfo = null, historyNode = null, toggleRight
setSearchList(highlightArr);
setTimeout(() => {
setCurrentStep(2);
}, 3000);
}, timeout);
};

const handleReceiveHistory = () => {
Expand Down Expand Up @@ -106,6 +107,7 @@ const ChatRight = ({ nodeInfo, stashInfo = null, historyNode = null, toggleRight
setThinking(null);
setReading(null);
setConclusion('');
setSubQuestion('');
};

useEffect(() => {
Expand Down Expand Up @@ -146,9 +148,9 @@ const ChatRight = ({ nodeInfo, stashInfo = null, historyNode = null, toggleRight
console.log('node is end------', nodeInfo);
resetStatus();
}
nodeDetail?.content && setSubQuestion(nodeDetail?.content);
if (nodeDetail?.state === 1) {
setThought(nodeDetail.response);
nodeDetail?.content && setSubQuestion(nodeDetail?.content);
// 如果返回thought的时候还没有searchlist,那就是第一步的思考
if (nodeDetail.actions?.[0]?.thought) {
setThinking({
Expand Down
165 changes: 38 additions & 127 deletions frontend/React/src/pages/render/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,33 +16,21 @@ const RenderTest = () => {
const [question, setQuestion] = useState("");
const [stashQuestion, setStashQuestion] = useState("");
const [isEnd, setIsEnd] = useState(false);
// 一组节点的渲染草稿
// 一组节点的思考草稿
const [draft, setDraft] = useState('');
// 一轮完整对话结束
const [chatIsOver, setChatIsOver] = useState(true);
// 一组节点的思考草稿是不是打印结束
const [progressEnd, setProgressEnd] = useState(false);

const [query, setQuery] = useState([]);
const [searchList, setSearchList] = useState([]);
// 整体的渲染树
const [renderData, setRenderData] = useState<any[]>([]);
const [currentNode, setCurrentNode] = useState<any>(null);
const [response, setResponse] = useState("");
const [currentStep, setCurrentStep] = useState(0);
const [mapWidth, setMapWidth] = useState(0);
// 是否展示右侧内容
const [showRight, setShowRight] = useState(true);
const [selectedIds, setSelectedIds] = useState([]);
const [nodeName, setNodeName] = useState('');
const hasHighlight = useRef(false);
const conclusionRender = useRef(false);
const nodeDraftRender = useRef(false);
const [obj, setObj] = useState<any>(null);
const [adjList, setAdjList] = useState([]);
const [historyNode, setHistoryNode] = useState<any>(null);

const TEXT_INTERVAL = 20;
let checkTimeoutId: any = useRef(null);

const toggleRight = () => {
setShowRight(!showRight);
Expand All @@ -66,59 +54,7 @@ const RenderTest = () => {
return node;
});
}

const generateWidth = () => {
const articles = document.querySelectorAll('article');
// 确保至少有两个元素
if (articles?.length) {
let maxRight = 0;
articles.forEach((item, index) => {
if (item.getBoundingClientRect().right > maxRight) {
maxRight = item.getBoundingClientRect().right;
}
})
const firstArticle = articles[0].getBoundingClientRect();
if (maxRight - firstArticle.left + 200 > mapWidth) {
return maxRight - firstArticle.left + 200
} else {
return mapWidth;
}
} else {
return 100;
}
};

// 逐字渲染
// const renderDraft = (str: string, type: string, endCallback: () => void) => {
// // 已经输出的字符数量
// let outputIndex = 0;

// // 输出字符的函数
// const outputText = () => {
// // 给出高亮后draft输出的结束标志
// if (type === 'stepDraft-1' && outputIndex + 3 > str?.length) {
// nodeDraftRender.current = true;
// }
// // 如果还有字符未输出
// if (outputIndex < str?.length) {
// // 获取接下来要输出的1个字符(或剩余字符,如果不足3个)
// let chunk = str.slice(outputIndex, Math.min(outputIndex + 10, str.length));
// // 更新已输出字符的索引
// outputIndex += chunk.length;
// if (type === 'thought') {
// setDraft(str.slice(0, outputIndex));
// }
// } else {
// // 如果没有更多字符需要输出,则清除定时器
// clearInterval(intervalId);
// endCallback && endCallback()
// }
// }

// // 设定定时器ID
// let intervalId = setInterval(outputText, TEXT_INTERVAL);
// }


// 渲染过程中保持渲染文字可见
const keepScrollTop = (divA: any, divB: any) => {
// 获取 divB 的当前高度
Expand All @@ -143,45 +79,30 @@ const RenderTest = () => {
}, [JSON.stringify(adjList)]);

useEffect(() => {
console.log('render data changed-----', renderData);
console.log('graph render data changed-----', renderData);
}, [renderData]);

useEffect(() => {
if (obj?.current_node && obj?.response?.state === 3) {
// 当node节点的数据可以开始渲染时,给currentnode赋值
// update conclusion
if (obj.response.nodes[obj.current_node]?.detail?.actions?.length === 2 &&
obj.response.nodes[obj.current_node]?.detail?.state === 1 &&
obj.response.nodes[obj.current_node]?.detail.response) {
window.localStorage.setItem('nodeRes', obj.response.nodes[obj.current_node]?.detail.response);
}
if (obj.current_node &&
(obj.response.nodes[obj.current_node]?.detail?.state === 1) &&
obj.response.nodes[obj.current_node]?.detail?.actions?.length &&
currentStep === 0 &&
currentNode?.current_node !== obj?.current_node
) {
// 更新当前渲染节点
console.log('update current node----');
setCurrentNode({ ...obj.response.nodes[obj.current_node]?.detail, current_node: obj.current_node });
}

// 设置highlight
if (!selectedIds.length &&
obj.response.nodes[obj.current_node]?.detail?.actions?.[1]?.type === 'BingBrowser.select' &&
(obj.response.nodes[obj.current_node]?.detail?.state === 1)) {
setSelectedIds(obj.response.nodes[obj.current_node]?.detail?.actions?.[1]?.args?.select_ids || []);
// console.log('update current node----');
setCurrentNode({ ...obj.response.nodes[obj.current_node]?.detail, current_node: obj.current_node });
}
}
}, [obj]);

useEffect(() => {
// 当前节点渲染结束
if (nodeName && nodeName !== currentNode?.current_node && progressEnd && !isEnd) {
if (nodeName && nodeName !== currentNode?.current_node && !isEnd) {
resetNode(nodeName);
}
}, [nodeName, currentNode, progressEnd, isEnd]);
}, [nodeName, currentNode, isEnd]);

let responseTimer: any = useRef(null);
useEffect(() => {
Expand Down Expand Up @@ -223,37 +144,28 @@ const RenderTest = () => {

useEffect(() => {
// 设置beforeunload事件监听器
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
// message.warning('离开可能导致SSE重连,确认离开吗?');
const msg = "离开可能导致SSE重连,确认离开吗?";
const msg = "离开可能导致SSE重连,确认离开吗?";
event.preventDefault(); // 大多数现代浏览器会忽略这一行
(event as any).returnValue = msg;
};
};

// 添加事件监听器
window.addEventListener('beforeunload', handleBeforeUnload);
window.addEventListener('beforeunload', handleBeforeUnload);

// 清理函数,确保组件卸载时移除事件监听器
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);

const resetNode = (targetNode: string) => {
if (targetNode === 'response') return; // 如果开始response了,所有节点都渲染完了,不需要reset
// 渲染下一个节点前,初始化状态
const newData = findAndUpdateStatus(renderData, targetNode);
// const newData = findAndUpdateStatus(renderData, targetNode);
console.log('reset node------', targetNode, renderData);
setCurrentStep(0);
setQuery([]);
setSearchList([]);
setProgressEnd(false);
setCurrentNode(null);
setSelectedIds([]);
hasHighlight.current = false;
nodeDraftRender.current = false;
conclusionRender.current = false;
window.localStorage.setItem('nodeRes', '');
};

const formatData = (data: any) => {
Expand All @@ -262,6 +174,7 @@ const RenderTest = () => {
const obj = JSON.parse(data);
if (!obj.current_node && obj.response.state === 0) {
console.log('chat is over end-------');
clearInterval(checkTimeoutId.current);
setChatIsOver(true);
return;
}
Expand All @@ -272,7 +185,7 @@ const RenderTest = () => {
setResponse(replaced);
return;
}
if (!obj.current_node && obj.response.state === 1 && !currentNode) {
if (!obj.current_node && obj.response.state === 1) {
// 有thought,没有node
// setDraftEnd(false);
setDraft(obj.response.response);
Expand All @@ -287,7 +200,7 @@ const RenderTest = () => {
}
}
} catch (err) {
console.log('format error-----', err);
console.log('format error-----', err, 'received data is-------', data);
}
};

Expand All @@ -301,7 +214,6 @@ const RenderTest = () => {
setIsWaiting(true);
// 用来记录最后一次接收消息的时间
let lastReceivedTime = new Date().getTime();
let checkTimeoutId: any = null;

const postData = {
inputs: [
Expand All @@ -318,8 +230,8 @@ const RenderTest = () => {
},
body: JSON.stringify(postData),
async onopen(res) {
// 开始检查超时
// checkTimeoutId = setInterval(checkTimeout, 5000);
// 开始检查超时
checkTimeoutId.current = setInterval(checkTimeout, 6000);
},
onmessage(ev) {
if (stashQuestion) {
Expand All @@ -335,22 +247,22 @@ const RenderTest = () => {
// signal: ctrl.signal,
});

// const checkTimeout = () => {
// const currentTime = new Date().getTime();
// const diff = currentTime - lastReceivedTime;
// // 如果超过10秒没有接收到新消息,则关闭连接
// if (diff > 10000) {
// console.log("No new data received for 10 seconds, closing connection.");
// // eventSource.close();
// message.error('已有10s未收到新的返回数据,继续等待或刷新再试');
// lastReceivedTime = new Date().getTime();
// // setTimeout(() => {
// // location.reload();
// // }, 2000);
// // 清除定时器
// // clearInterval(checkTimeoutId);
// }
// }
const checkTimeout = () => {
const currentTime = new Date().getTime();
const diff = currentTime - lastReceivedTime;
// 如果超过10秒没有接收到新消息,则关闭连接
if (diff > 10000) {
console.warn("-----No new data received over 10 seconds-----");
// eventSource.close();
// message.warning('超过10s未收到新的返回数据,继续等待或刷新再试');
lastReceivedTime = new Date().getTime();
// setTimeout(() => {
// location.reload();
// }, 2000);
// 清除定时器
// clearInterval(checkTimeoutId.current);
}
}
};

const handleHistory = (node: string) => {
Expand All @@ -361,7 +273,7 @@ const RenderTest = () => {
const stashedObj = window.localStorage.getItem('nodesInfo') && JSON.parse(window.localStorage.getItem('nodesInfo') || '{}') || {};
const info = stashedObj[node];
console.log('handleHistory---------------', info);
if(!info) {
if (!info) {
message.error('没有读取到节点的历史记录信息');
}
setHistoryNode(info);
Expand All @@ -386,7 +298,6 @@ const RenderTest = () => {
isEnd={isEnd}
renderData={renderData}
chatIsOver={chatIsOver}
mapWidth={mapWidth}
handleHistory={handleHistory}
/>
}
Expand Down
2 changes: 1 addition & 1 deletion frontend/React/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export default defineConfig({
port: 8080,
proxy: {
// "/solve": {
// target: "...",
// target: "https://mindsearch.openxlab.org.cn",
// changeOrigin: true,
// },
},
Expand Down

0 comments on commit 1a4fd82

Please sign in to comment.