update ws error handle

This commit is contained in:
anovazzi1 2023-05-04 19:25:24 -03:00
commit 4c2f3b80dc
3 changed files with 318 additions and 341 deletions

View file

@ -5,7 +5,7 @@ import { PopUpContext } from "../../../contexts/popUpContext";
import { useContext } from "react"; import { useContext } from "react";
import ChatModal from "../../../modals/chatModal"; import ChatModal from "../../../modals/chatModal";
export default function ChatTrigger({open, setOpen,flow}){ export default function ChatTrigger({open, setOpen}){
const {openPopUp} = useContext(PopUpContext) const {openPopUp} = useContext(PopUpContext)
return(<Transition return(<Transition
show={!open} show={!open}

View file

@ -26,7 +26,7 @@ export default function Chat({ flow }: ChatType) {
return ( return (
<> <>
<ChatModal key={flow.id} flow={flow} open={open} setOpen={setOpen} /> <ChatModal key={flow.id} flow={flow} open={open} setOpen={setOpen} />
<ChatTrigger open={open} setOpen={setOpen} flow={flow} /> <ChatTrigger open={open} setOpen={setOpen} />
</> </>
); );
} }

View file

@ -1,13 +1,7 @@
import { Dialog, Transition } from "@headlessui/react"; import { Dialog, Transition } from "@headlessui/react";
import { import { ChatBubbleOvalLeftEllipsisIcon } from "@heroicons/react/24/outline";
ChatBubbleOvalLeftEllipsisIcon,
LockClosedIcon,
PaperAirplaneIcon,
} from "@heroicons/react/24/outline";
import { Fragment, useContext, useEffect, useRef, useState } from "react"; import { Fragment, useContext, useEffect, useRef, useState } from "react";
import { PopUpContext } from "../../contexts/popUpContext";
import { FlowType, NodeType } from "../../types/flow"; import { FlowType, NodeType } from "../../types/flow";
import { TabsContext } from "../../contexts/tabsContext";
import { alertContext } from "../../contexts/alertContext"; import { alertContext } from "../../contexts/alertContext";
import { toNormalCase } from "../../utils"; import { toNormalCase } from "../../utils";
import { typesContext } from "../../contexts/typesContext"; import { typesContext } from "../../contexts/typesContext";
@ -20,356 +14,339 @@ import ChatInput from "./chatInput";
const _ = require("lodash"); const _ = require("lodash");
export default function ChatModal({ export default function ChatModal({
flow, flow,
open, open,
setOpen, setOpen,
}: { }: {
open: boolean; open: boolean;
setOpen: Function; setOpen: Function;
flow: FlowType; flow: FlowType;
}) { }) {
const [chatValue, setChatValue] = useState(""); const [chatValue, setChatValue] = useState("");
const [chatHistory, setChatHistory] = useState<ChatMessageType[]>([]); const [chatHistory, setChatHistory] = useState<ChatMessageType[]>([]);
const { reactFlowInstance } = useContext(typesContext); const { reactFlowInstance } = useContext(typesContext);
const { setErrorData, setNoticeData } = useContext(alertContext); const { setErrorData, setNoticeData } = useContext(alertContext);
const [ws, setWs] = useState<WebSocket | null>(null); const [ws, setWs] = useState<WebSocket | null>(null);
const [lockChat, setLockChat] = useState(false); const [lockChat, setLockChat] = useState(false);
const addChatHistory = ( const addChatHistory = (
message: string, message: string,
isSend: boolean, isSend: boolean,
thought?: string, thought?: string,
files?: Array<any> files?: Array<any>
) => { ) => {
setChatHistory((old) => { setChatHistory((old) => {
let newChat = _.cloneDeep(old); let newChat = _.cloneDeep(old);
if (files) { if (files) {
newChat.push({ message, isSend, files, thought }); newChat.push({ message, isSend, files, thought });
} else if (thought) { } else if (thought) {
newChat.push({ message, isSend, thought }); newChat.push({ message, isSend, thought });
} else { } else {
newChat.push({ message, isSend }); newChat.push({ message, isSend });
} }
return newChat; return newChat;
}); });
}; };
function connectWS() { function connectWS() {
console.log("conectou"); try {
try { const urlWs =
const urlWs = process.env.NODE_ENV === "development"
process.env.NODE_ENV === "development" ? `ws://localhost:7860/chat/${flow.id}`
? `ws://localhost:7860/chat/${flow.id}` : `${window.location.protocol === "https:" ? "wss" : "ws"}://${
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${ window.location.host
window.location.host }/chat/${flow.id}`;
}/chat/${flow.id}`;
const newWs = new WebSocket(urlWs); const newWs = new WebSocket(urlWs);
newWs.onopen = () => { newWs.onopen = () => {
console.log("WebSocket connection established!"); console.log("WebSocket connection established!");
}; };
newWs.onmessage = (event) => { newWs.onmessage = (event) => {
try { setLockChat(false);
setLockChat(false); const data = JSON.parse(event.data);
const data = JSON.parse(event.data); console.log("Received data:", data);
console.log("Received data:", data); //get chat history
//get chat history if (Array.isArray(data)) {
if (Array.isArray(data)) { console.log(data);
console.log(data);
setChatHistory((_) => { setChatHistory((_) => {
let newChatHistory: ChatMessageType[] = []; let newChatHistory: ChatMessageType[] = [];
data.forEach( data.forEach(
(chatItem: { (chatItem: {
intermediate_steps?: "string"; intermediate_steps?: "string";
is_bot: boolean; is_bot: boolean;
message: string; message: string;
type: string; type: string;
files?: Array<any>; files?: Array<any>;
}) => { }) => {
if (chatItem.message) { if (chatItem.message) {
newChatHistory.push( newChatHistory.push(
chatItem.files chatItem.files
? { ? {
isSend: !chatItem.is_bot, isSend: !chatItem.is_bot,
message: chatItem.message, message: chatItem.message,
thought: chatItem.intermediate_steps, thought: chatItem.intermediate_steps,
files: chatItem.files, files: chatItem.files,
} }
: { : {
isSend: !chatItem.is_bot, isSend: !chatItem.is_bot,
message: chatItem.message, message: chatItem.message,
thought: chatItem.intermediate_steps, thought: chatItem.intermediate_steps,
} }
); );
} }
} }
); );
return newChatHistory; return newChatHistory;
}); });
} }
if (data.type === "end") { if (data.type === "end") {
if (data.files) { if (data.files) {
addChatHistory( addChatHistory(
data.message, data.message,
false, false,
data.intermediate_steps, data.intermediate_steps,
data.files data.files
); );
} else { } else {
addChatHistory(data.message, false, data.intermediate_steps); addChatHistory(data.message, false, data.intermediate_steps);
} }
} }
if (data.type == "file") { if (data.type === "file") {
console.log(data); console.log(data);
} }
} catch (error) { };
if (event.data !== "Error: 1005") { newWs.onclose = (_) => {
setErrorData({ title: event.data }); setLockChat(false);
newWs.close(); setTimeout(() => {
connectWS(); connectWS();
} }, 1000);
} };
}; newWs.onerror = (ev) => {
newWs.onclose = (_) => { console.log(ev, "error");
if (open) { };
setLockChat(false); setWs(newWs);
setTimeout(() => {
connectWS();
}, 1000);
}
};
newWs.onerror = (ev) => {
console.log(ev, "error");
};
setWs(newWs);
return newWs; return newWs;
} catch { } catch {
setErrorData({ setErrorData({
title: "There was an error on web connection, please: ", title: "There was an error on web connection, please: ",
list: [ list: [
"refresh the page", "Refresh the page",
"use a new flow tab", "Use a new flow tab",
"check if the backend is up", "Check if the backend is up",
], ],
}); });
} }
} }
useEffect(() => { useEffect(() => {
if (ws && (ws.readyState === ws.CLOSED || ws.readyState === ws.CLOSING)) { let newWs = connectWS();
let newWs = connectWS(); return () => {
return () => { console.log("trigger");
console.log("trigger"); newWs.close();
newWs.close(); };
}; }, []);
}
}, [lockChat]);
useEffect(() => { useEffect(() => {
let newWs = connectWS(); if (ws && (ws.readyState === ws.CLOSED || ws.readyState === ws.CLOSING)) {
return () => { let newWs = connectWS();
console.log("trigger"); return () => {
newWs.close(); console.log("trigger");
}; newWs.close();
}, []); };
}
}, [lockChat]);
async function sendAll(data: sendAllProps) { async function sendAll(data: sendAllProps) {
try { try {
if (ws) { if (ws) {
ws.send(JSON.stringify(data)); ws.send(JSON.stringify(data));
} }
} catch (error) { } catch (error) {
setErrorData({ setErrorData({
title: "There was an erro sending the message", title: "There was an erro sending the message",
list: [error.message], list: [error.message],
}); });
setChatValue(data.message); setChatValue(data.message);
connectWS(); connectWS();
} }
} }
useEffect(() => { useEffect(() => {
if (ref.current) ref.current.scrollIntoView({ behavior: "smooth" }); if (ref.current) ref.current.scrollIntoView({ behavior: "smooth" });
}, [chatHistory]); }, [chatHistory]);
useEffect(() => { useEffect(() => {
if (ws && ws.readyState === ws.CLOSED) { if (ws && ws.readyState === ws.CLOSED) {
setLockChat(false); setLockChat(false);
} }
}, [lockChat]); }, [lockChat]);
function validateNode(n: NodeType): Array<string> { function validateNode(n: NodeType): Array<string> {
if (!n.data?.node?.template || !Object.keys(n.data.node.template)) { if (!n.data?.node?.template || !Object.keys(n.data.node.template)) {
setNoticeData({ setNoticeData({
title: title:
"We've noticed a potential issue with a node in the flow. Please review it and, if necessary, submit a bug report with your exported flow file. Thank you for your help!", "We've noticed a potential issue with a node in the flow. Please review it and, if necessary, submit a bug report with your exported flow file. Thank you for your help!",
}); });
return []; return [];
} }
const { const {
type, type,
node: { template }, node: { template },
} = n.data; } = n.data;
return Object.keys(template).reduce( return Object.keys(template).reduce(
(errors: Array<string>, t) => (errors: Array<string>, t) =>
errors.concat( errors.concat(
template[t].required && template[t].required &&
template[t].show && template[t].show &&
(!template[t].value || template[t].value === "") && (!template[t].value || template[t].value === "") &&
!reactFlowInstance !reactFlowInstance
.getEdges() .getEdges()
.some( .some(
(e) => (e) =>
e.targetHandle.split("|")[1] === t && e.targetHandle.split("|")[1] === t &&
e.targetHandle.split("|")[2] === n.id e.targetHandle.split("|")[2] === n.id
) )
? [ ? [
`${type} is missing ${ `${type} is missing ${
template.display_name template.display_name
? template.display_name ? template.display_name
: toNormalCase(template[t].name) : toNormalCase(template[t].name)
}.`, }.`,
] ]
: [] : []
), ),
[] as string[] [] as string[]
); );
} }
function validateNodes() { function validateNodes() {
return reactFlowInstance return reactFlowInstance
.getNodes() .getNodes()
.flatMap((n: NodeType) => validateNode(n)); .flatMap((n: NodeType) => validateNode(n));
} }
const ref = useRef(null); const ref = useRef(null);
function sendMessage() { function sendMessage() {
if (chatValue !== "") { if (chatValue !== "") {
let nodeValidationErrors = validateNodes(); let nodeValidationErrors = validateNodes();
if (nodeValidationErrors.length === 0) { if (nodeValidationErrors.length === 0) {
setLockChat(true); setLockChat(true);
let message = chatValue; let message = chatValue;
setChatValue(""); setChatValue("");
addChatHistory(message, true); addChatHistory(message, true);
sendAll({ sendAll({
...reactFlowInstance.toObject(), ...reactFlowInstance.toObject(),
message, message,
chatHistory, chatHistory,
name: flow.name, name: flow.name,
description: flow.description, description: flow.description,
}); });
} else { } else {
setErrorData({ setErrorData({
title: "Oops! Looks like you missed some required information:", title: "Oops! Looks like you missed some required information:",
list: nodeValidationErrors, list: nodeValidationErrors,
}); });
} }
} else { } else {
setErrorData({ setErrorData({
title: "Error sending message", title: "Error sending message",
list: ["The message cannot be empty."], list: ["The message cannot be empty."],
}); });
} }
} }
function clearChat() { function clearChat() {
setChatHistory([]); setChatHistory([]);
ws.send(JSON.stringify({ clear_history: true })); ws.send(JSON.stringify({ clear_history: true }));
} }
const { closePopUp } = useContext(PopUpContext); function setModalOpen(x: boolean) {
function setModalOpen(x: boolean) { setOpen(x);
setOpen(x); }
if (x === false) { return (
setTimeout(() => { <Transition.Root show={open} appear={open} as={Fragment}>
closePopUp(); <Dialog
}, 300); as="div"
} className="relative z-10"
} onClose={setModalOpen}
return ( initialFocus={ref}
<Transition.Root show={open} appear={true} as={Fragment}> >
<Dialog <Transition.Child
as="div" as={Fragment}
className="relative z-10" enter="ease-out duration-300"
onClose={setModalOpen} enterFrom="opacity-0"
initialFocus={ref} enterTo="opacity-100"
> leave="ease-in duration-200"
<Transition.Child leaveFrom="opacity-100"
as={Fragment} leaveTo="opacity-0"
enter="ease-out duration-300" >
enterFrom="opacity-0" <div className="fixed inset-0 bg-black backdrop-blur-sm dark:bg-gray-600 dark:bg-opacity-80 bg-opacity-80 transition-opacity" />
enterTo="opacity-100" </Transition.Child>
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black backdrop-blur-sm dark:bg-gray-600 dark:bg-opacity-80 bg-opacity-80 transition-opacity" />
</Transition.Child>
<div className="fixed inset-0 z-10 overflow-y-auto"> <div className="fixed inset-0 z-10 overflow-y-auto">
<div className="flex h-full items-end justify-center p-4 text-center sm:items-center sm:p-0"> <div className="flex h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<Transition.Child <Transition.Child
as={Fragment} as={Fragment}
enter="ease-out duration-300" enter="ease-out duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100" enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200" leave="ease-in duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100" leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
> >
<Dialog.Panel className=" drop-shadow-2xl relative flex flex-col justify-between transform h-[95%] overflow-hidden rounded-lg bg-white dark:bg-gray-800 text-left shadow-xl transition-all sm:my-8 w-[690px]"> <Dialog.Panel className=" drop-shadow-2xl relative flex flex-col justify-between transform h-[95%] overflow-hidden rounded-lg bg-white dark:bg-gray-800 text-left shadow-xl transition-all sm:my-8 w-[690px]">
<div className="relative w-full"> <div className="relative w-full">
<button <button
onClick={() => clearChat()} onClick={() => clearChat()}
className="absolute top-2 right-2 hover:text-red-500" className="absolute top-2 right-2 hover:text-red-500"
> >
<FaEraser className="w-4 h-4" /> <FaEraser className="w-4 h-4" />
</button> </button>
</div> </div>
<div className="w-full h-full bg-white dark:bg-gray-800 border-t dark:border-t-gray-600 flex-col flex items-center overflow-scroll scrollbar-hide"> <div className="w-full h-full bg-white dark:bg-gray-800 border-t dark:border-t-gray-600 flex-col flex items-center overflow-scroll scrollbar-hide">
{chatHistory.length > 0 ? ( {chatHistory.length > 0 ? (
chatHistory.map((c, i) => <ChatMessage chat={c} key={i} />) chatHistory.map((c, i) => <ChatMessage chat={c} key={i} />)
) : ( ) : (
<div className="flex flex-col h-full text-center justify-center w-full items-center align-middle "> <div className="flex flex-col h-full text-center justify-center w-full items-center align-middle ">
<span> <span>
👋{" "} 👋{" "}
<span className="text-gray-600 text-lg"> <span className="text-gray-600 text-lg">
LangFlow Chat LangFlow Chat
</span> </span>
</span> </span>
<br /> <br />
<div className="bg-gray-100 rounded-md w-2/4 px-6 py-8 border border-gray-200"> <div className="bg-gray-100 rounded-md w-2/4 px-6 py-8 border border-gray-200">
<span className="text-base text-gray-500"> <span className="text-base text-gray-500">
Start a conversation and click the agent’s thoughts{" "} Start a conversation and click the agent’s thoughts{" "}
<span> <span>
<ChatBubbleOvalLeftEllipsisIcon className="w-6 h-6 inline animate-bounce " /> <ChatBubbleOvalLeftEllipsisIcon className="w-6 h-6 inline animate-bounce " />
</span>{" "} </span>{" "}
to inspect the chaining process. to inspect the chaining process.
</span> </span>
</div> </div>
</div> </div>
)} )}
<div ref={ref}></div> <div ref={ref}></div>
</div> </div>
<div className="w-full bg-white dark:bg-gray-800 border-t dark:border-t-gray-600 flex-col flex items-center justify-between p-3"> <div className="w-full bg-white dark:bg-gray-800 border-t dark:border-t-gray-600 flex-col flex items-center justify-between p-3">
<div className="relative w-full mt-1 rounded-md shadow-sm"> <div className="relative w-full mt-1 rounded-md shadow-sm">
<ChatInput <ChatInput
chatValue={chatValue} chatValue={chatValue}
lockChat={lockChat} lockChat={lockChat}
sendMessage={sendMessage} sendMessage={sendMessage}
setChatValue={setChatValue} setChatValue={setChatValue}
/> />
</div> </div>
</div> </div>
</Dialog.Panel> </Dialog.Panel>
</Transition.Child> </Transition.Child>
</div> </div>
</div> </div>
</Dialog> </Dialog>
</Transition.Root> </Transition.Root>
); );
} }