ChatGPT-Next-Web/app/components/chat.tsx

1287 lines
37 KiB
TypeScript
Raw Normal View History

2023-04-22 17:27:15 +00:00
import { useDebouncedCallback } from "use-debounce";
import React, {
useState,
useRef,
useEffect,
useMemo,
2023-06-24 08:37:29 +00:00
useCallback,
2023-07-14 13:15:34 +00:00
Fragment,
} from "react";
2023-04-02 15:05:54 +00:00
import SendWhiteIcon from "../icons/send-white.svg";
import BrainIcon from "../icons/brain.svg";
2023-04-14 18:37:24 +00:00
import RenameIcon from "../icons/rename.svg";
2023-04-09 16:00:36 +00:00
import ExportIcon from "../icons/share.svg";
import ReturnIcon from "../icons/return.svg";
2023-04-02 15:05:54 +00:00
import CopyIcon from "../icons/copy.svg";
import LoadingIcon from "../icons/three-dots.svg";
2023-04-25 18:02:46 +00:00
import PromptIcon from "../icons/prompt.svg";
import MaskIcon from "../icons/mask.svg";
2023-04-09 16:00:36 +00:00
import MaxIcon from "../icons/max.svg";
import MinIcon from "../icons/min.svg";
2023-04-26 17:16:21 +00:00
import ResetIcon from "../icons/reload.svg";
2023-05-20 17:28:09 +00:00
import BreakIcon from "../icons/break.svg";
import SettingsIcon from "../icons/chat-settings.svg";
2023-06-25 15:53:22 +00:00
import DeleteIcon from "../icons/clear.svg";
import PinIcon from "../icons/pin.svg";
import EditIcon from "../icons/rename.svg";
import ConfirmIcon from "../icons/confirm.svg";
import CancelIcon from "../icons/cancel.svg";
2023-04-02 15:05:54 +00:00
import LightIcon from "../icons/light.svg";
import DarkIcon from "../icons/dark.svg";
import AutoIcon from "../icons/auto.svg";
import BottomIcon from "../icons/bottom.svg";
2023-04-16 10:07:43 +00:00
import StopIcon from "../icons/pause.svg";
import RobotIcon from "../icons/robot.svg";
2023-04-05 19:19:33 +00:00
import {
ChatMessage,
2023-04-05 19:19:33 +00:00
SubmitKey,
useChatStore,
BOT_HELLO,
createMessage,
2023-04-09 15:51:12 +00:00
useAccessStore,
Theme,
2023-04-21 16:12:07 +00:00
useAppConfig,
2023-04-22 17:27:15 +00:00
DEFAULT_TOPIC,
ModelType,
2023-04-05 19:19:33 +00:00
} from "../store";
2023-04-02 15:05:54 +00:00
import {
copyToClipboard,
selectOrCopy,
2023-04-07 18:36:02 +00:00
autoGrowTextArea,
2023-04-20 15:20:25 +00:00
useMobileScreen,
2023-04-02 15:05:54 +00:00
} from "../utils";
import dynamic from "next/dynamic";
import { ChatControllerPool } from "../client/controller";
2023-04-02 15:05:54 +00:00
import { Prompt, usePromptStore } from "../store/prompt";
import Locale from "../locales";
import { IconButton } from "./button";
2023-06-25 15:53:22 +00:00
import styles from "./chat.module.scss";
2023-04-02 15:05:54 +00:00
import {
List,
ListItem,
Modal,
Selector,
showConfirm,
showPrompt,
showToast,
} from "./ui-lib";
import { useLocation, useNavigate } from "react-router-dom";
import {
CHAT_PAGE_SIZE,
LAST_INPUT_KEY,
MAX_RENDER_MSG_COUNT,
Path,
REQUEST_TIMEOUT_MS,
} from "../constant";
import { Avatar } from "./emoji";
import { ContextPrompts, MaskAvatar, MaskConfig } from "./mask";
import { useMaskStore } from "../store/mask";
2023-06-24 15:38:11 +00:00
import { ChatCommandPrefix, useChatCommand, useCommand } from "../command";
2023-05-20 11:58:12 +00:00
import { prettyObject } from "../utils/format";
import { ExportMessageModal } from "./exporter";
import { getClientConfig } from "../config/client";
2023-04-22 17:37:47 +00:00
const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
loading: () => <LoadingIcon />,
});
2023-04-02 15:05:54 +00:00
2023-04-22 17:27:15 +00:00
export function SessionConfigModel(props: { onClose: () => void }) {
const chatStore = useChatStore();
const session = chatStore.currentSession();
2023-04-26 17:16:21 +00:00
const maskStore = useMaskStore();
const navigate = useNavigate();
2023-04-22 17:37:47 +00:00
2023-04-22 17:27:15 +00:00
return (
<div className="modal-mask">
<Modal
title={Locale.Context.Edit}
onClose={() => props.onClose()}
actions={[
<IconButton
key="reset"
2023-04-26 17:16:21 +00:00
icon={<ResetIcon />}
2023-04-22 17:27:15 +00:00
bordered
2023-04-26 17:16:21 +00:00
text={Locale.Chat.Config.Reset}
onClick={async () => {
if (await showConfirm(Locale.Memory.ResetConfirm)) {
chatStore.updateCurrentSession(
(session) => (session.memoryPrompt = ""),
);
}
}}
2023-04-22 17:27:15 +00:00
/>,
<IconButton
key="copy"
icon={<CopyIcon />}
bordered
2023-04-26 17:16:21 +00:00
text={Locale.Chat.Config.SaveAs}
onClick={() => {
navigate(Path.Masks);
setTimeout(() => {
maskStore.create(session.mask);
}, 500);
}}
2023-04-22 17:27:15 +00:00
/>,
]}
>
2023-04-24 16:49:27 +00:00
<MaskConfig
mask={session.mask}
updateMask={(updater) => {
const mask = { ...session.mask };
updater(mask);
chatStore.updateCurrentSession((session) => (session.mask = mask));
}}
shouldSyncFromGlobal
2023-04-24 16:49:27 +00:00
extraListItems={
session.mask.modelConfig.sendMemory ? (
<ListItem
title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`}
subTitle={session.memoryPrompt || Locale.Memory.EmptyContent}
></ListItem>
) : (
<></>
)
}
></MaskConfig>
2023-04-22 17:27:15 +00:00
</Modal>
</div>
);
}
function PromptToast(props: {
showToast?: boolean;
showModal?: boolean;
setShowModal: (_: boolean) => void;
}) {
const chatStore = useChatStore();
const session = chatStore.currentSession();
2023-04-24 16:49:27 +00:00
const context = session.mask.context;
2023-04-22 17:27:15 +00:00
return (
2023-06-25 15:53:22 +00:00
<div className={styles["prompt-toast"]} key="prompt-toast">
2023-04-02 18:28:07 +00:00
{props.showToast && (
<div
2023-06-25 15:53:22 +00:00
className={styles["prompt-toast-inner"] + " clickable"}
2023-04-02 18:28:07 +00:00
role="button"
onClick={() => props.setShowModal(true)}
>
<BrainIcon />
2023-06-25 15:53:22 +00:00
<span className={styles["prompt-toast-content"]}>
2023-04-02 18:28:07 +00:00
{Locale.Context.Toast(context.length)}
</span>
</div>
)}
{props.showModal && (
2023-04-22 17:27:15 +00:00
<SessionConfigModel onClose={() => props.setShowModal(false)} />
)}
</div>
);
2023-04-02 15:05:54 +00:00
}
function useSubmitHandler() {
2023-04-21 16:12:07 +00:00
const config = useAppConfig();
2023-04-02 15:05:54 +00:00
const submitKey = config.submitKey;
const isComposing = useRef(false);
useEffect(() => {
const onCompositionStart = () => {
isComposing.current = true;
};
const onCompositionEnd = () => {
isComposing.current = false;
};
window.addEventListener("compositionstart", onCompositionStart);
window.addEventListener("compositionend", onCompositionEnd);
return () => {
window.removeEventListener("compositionstart", onCompositionStart);
window.removeEventListener("compositionend", onCompositionEnd);
};
}, []);
2023-04-02 15:05:54 +00:00
const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key !== "Enter") return false;
if (e.key === "Enter" && (e.nativeEvent.isComposing || isComposing.current))
return false;
2023-04-02 15:05:54 +00:00
return (
(config.submitKey === SubmitKey.AltEnter && e.altKey) ||
(config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
(config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
(config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
(config.submitKey === SubmitKey.Enter &&
!e.altKey &&
!e.ctrlKey &&
!e.shiftKey &&
!e.metaKey)
);
};
return {
submitKey,
shouldSubmit,
};
}
2023-07-09 11:37:42 +00:00
export type RenderPompt = Pick<Prompt, "title" | "content">;
2023-04-02 15:05:54 +00:00
export function PromptHints(props: {
2023-07-09 11:37:42 +00:00
prompts: RenderPompt[];
onPromptSelect: (prompt: RenderPompt) => void;
2023-04-02 15:05:54 +00:00
}) {
const noPrompts = props.prompts.length === 0;
const [selectIndex, setSelectIndex] = useState(0);
const selectedRef = useRef<HTMLDivElement>(null);
2023-04-02 15:05:54 +00:00
useEffect(() => {
setSelectIndex(0);
}, [props.prompts.length]);
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
2023-06-24 15:38:11 +00:00
if (noPrompts || e.metaKey || e.altKey || e.ctrlKey) {
return;
}
// arrow up / down to select prompt
const changeIndex = (delta: number) => {
e.stopPropagation();
e.preventDefault();
const nextIndex = Math.max(
0,
Math.min(props.prompts.length - 1, selectIndex + delta),
);
setSelectIndex(nextIndex);
selectedRef.current?.scrollIntoView({
block: "center",
});
};
if (e.key === "ArrowUp") {
changeIndex(1);
} else if (e.key === "ArrowDown") {
changeIndex(-1);
} else if (e.key === "Enter") {
const selectedPrompt = props.prompts.at(selectIndex);
if (selectedPrompt) {
props.onPromptSelect(selectedPrompt);
}
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
// eslint-disable-next-line react-hooks/exhaustive-deps
2023-05-21 03:58:10 +00:00
}, [props.prompts.length, selectIndex]);
if (noPrompts) return null;
2023-04-02 15:05:54 +00:00
return (
<div className={styles["prompt-hints"]}>
{props.prompts.map((prompt, i) => (
<div
ref={i === selectIndex ? selectedRef : null}
className={
styles["prompt-hint"] +
` ${i === selectIndex ? styles["prompt-hint-selected"] : ""}`
}
2023-04-02 15:05:54 +00:00
key={prompt.title + i.toString()}
onClick={() => props.onPromptSelect(prompt)}
onMouseEnter={() => setSelectIndex(i)}
2023-04-02 15:05:54 +00:00
>
<div className={styles["hint-title"]}>{prompt.title}</div>
<div className={styles["hint-content"]}>{prompt.content}</div>
</div>
))}
</div>
);
}
2023-05-20 17:28:09 +00:00
function ClearContextDivider() {
const chatStore = useChatStore();
return (
<div
2023-06-25 15:53:22 +00:00
className={styles["clear-context"]}
2023-05-20 17:28:09 +00:00
onClick={() =>
chatStore.updateCurrentSession(
(session) => (session.clearContextIndex = undefined),
2023-05-20 17:28:09 +00:00
)
}
>
2023-06-25 15:53:22 +00:00
<div className={styles["clear-context-tips"]}>{Locale.Context.Clear}</div>
<div className={styles["clear-context-revert-btn"]}>
2023-05-20 17:44:59 +00:00
{Locale.Context.Revert}
</div>
2023-05-20 17:28:09 +00:00
</div>
);
}
function ChatAction(props: {
text: string;
icon: JSX.Element;
onClick: () => void;
}) {
const iconRef = useRef<HTMLDivElement>(null);
const textRef = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState({
full: 16,
icon: 16,
});
function updateWidth() {
if (!iconRef.current || !textRef.current) return;
const getWidth = (dom: HTMLDivElement) => dom.getBoundingClientRect().width;
const textWidth = getWidth(textRef.current);
const iconWidth = getWidth(iconRef.current);
setWidth({
full: textWidth + iconWidth,
icon: iconWidth,
});
}
return (
<div
2023-06-25 15:53:22 +00:00
className={`${styles["chat-input-action"]} clickable`}
onClick={() => {
props.onClick();
setTimeout(updateWidth, 1);
}}
2023-06-27 17:15:55 +00:00
onMouseEnter={updateWidth}
onTouchStart={updateWidth}
style={
{
"--icon-width": `${width.icon}px`,
"--full-width": `${width.full}px`,
} as React.CSSProperties
}
>
2023-06-25 15:53:22 +00:00
<div ref={iconRef} className={styles["icon"]}>
{props.icon}
</div>
2023-06-25 15:53:22 +00:00
<div className={styles["text"]} ref={textRef}>
{props.text}
</div>
</div>
);
}
2023-04-02 15:19:36 +00:00
function useScrollToBottom() {
// for auto-scroll
const scrollRef = useRef<HTMLDivElement>(null);
const [autoScroll, setAutoScroll] = useState(true);
function scrollDomToBottom() {
2023-04-02 15:19:36 +00:00
const dom = scrollRef.current;
if (dom) {
requestAnimationFrame(() => {
setAutoScroll(true);
dom.scrollTo(0, dom.scrollHeight);
});
2023-04-02 15:19:36 +00:00
}
}
// auto scroll
2023-06-24 08:37:29 +00:00
useEffect(() => {
if (autoScroll) {
scrollDomToBottom();
}
});
2023-04-02 15:19:36 +00:00
return {
scrollRef,
autoScroll,
setAutoScroll,
scrollDomToBottom,
2023-04-02 15:19:36 +00:00
};
}
export function ChatActions(props: {
showPromptModal: () => void;
scrollToBottom: () => void;
2023-04-25 18:02:46 +00:00
showPromptHints: () => void;
hitBottom: boolean;
}) {
2023-04-21 16:12:07 +00:00
const config = useAppConfig();
2023-04-25 18:02:46 +00:00
const navigate = useNavigate();
2023-05-20 17:28:09 +00:00
const chatStore = useChatStore();
2023-04-16 10:07:43 +00:00
// switch themes
2023-04-21 16:12:07 +00:00
const theme = config.theme;
function nextTheme() {
const themes = [Theme.Auto, Theme.Light, Theme.Dark];
const themeIndex = themes.indexOf(theme);
const nextIndex = (themeIndex + 1) % themes.length;
const nextTheme = themes[nextIndex];
2023-04-21 16:12:07 +00:00
config.update((config) => (config.theme = nextTheme));
}
2023-04-16 10:07:43 +00:00
// stop all responses
const couldStop = ChatControllerPool.hasPending();
const stopAll = () => ChatControllerPool.stopAll();
2023-04-16 10:07:43 +00:00
// switch model
const currentModel = chatStore.currentSession().mask.modelConfig.model;
const models = useMemo(
2023-07-09 13:56:49 +00:00
() =>
config
.allModels()
.filter((m) => m.available)
.map((m) => m.name),
[config],
);
const [showModelSelector, setShowModelSelector] = useState(false);
return (
2023-06-25 15:53:22 +00:00
<div className={styles["chat-input-actions"]}>
2023-04-16 10:07:43 +00:00
{couldStop && (
<ChatAction
2023-04-16 10:07:43 +00:00
onClick={stopAll}
text={Locale.Chat.InputActions.Stop}
icon={<StopIcon />}
/>
2023-04-16 10:07:43 +00:00
)}
{!props.hitBottom && (
<ChatAction
onClick={props.scrollToBottom}
text={Locale.Chat.InputActions.ToBottom}
icon={<BottomIcon />}
/>
)}
{props.hitBottom && (
<ChatAction
onClick={props.showPromptModal}
text={Locale.Chat.InputActions.Settings}
icon={<SettingsIcon />}
/>
)}
<ChatAction
onClick={nextTheme}
text={Locale.Chat.InputActions.Theme[theme]}
icon={
<>
{theme === Theme.Auto ? (
<AutoIcon />
) : theme === Theme.Light ? (
<LightIcon />
) : theme === Theme.Dark ? (
<DarkIcon />
) : null}
</>
}
/>
2023-04-25 18:02:46 +00:00
<ChatAction
2023-04-25 18:02:46 +00:00
onClick={props.showPromptHints}
text={Locale.Chat.InputActions.Prompt}
icon={<PromptIcon />}
/>
2023-04-25 18:02:46 +00:00
<ChatAction
2023-04-25 18:02:46 +00:00
onClick={() => {
navigate(Path.Masks);
}}
text={Locale.Chat.InputActions.Masks}
icon={<MaskIcon />}
/>
2023-05-20 17:28:09 +00:00
<ChatAction
text={Locale.Chat.InputActions.Clear}
icon={<BreakIcon />}
2023-05-20 17:28:09 +00:00
onClick={() => {
chatStore.updateCurrentSession((session) => {
2023-05-20 17:44:59 +00:00
if (session.clearContextIndex === session.messages.length) {
session.clearContextIndex = undefined;
2023-05-20 17:28:09 +00:00
} else {
session.clearContextIndex = session.messages.length;
session.memoryPrompt = ""; // will clear memory
}
});
}}
/>
<ChatAction
onClick={() => setShowModelSelector(true)}
text={currentModel}
icon={<RobotIcon />}
/>
{showModelSelector && (
<Selector
2023-08-02 14:53:36 +00:00
defaultSelectedValue={currentModel}
items={models.map((m) => ({
title: m,
value: m,
}))}
onClose={() => setShowModelSelector(false)}
onSelection={(s) => {
if (s.length === 0) return;
chatStore.updateCurrentSession((session) => {
session.mask.modelConfig.model = s[0] as ModelType;
session.mask.syncGlobalConfig = false;
});
showToast(s[0]);
}}
/>
)}
</div>
);
}
export function EditMessageModal(props: { onClose: () => void }) {
const chatStore = useChatStore();
const session = chatStore.currentSession();
const [messages, setMessages] = useState(session.messages.slice());
return (
<div className="modal-mask">
<Modal
title={Locale.Chat.EditMessage.Title}
onClose={props.onClose}
actions={[
<IconButton
text={Locale.UI.Cancel}
icon={<CancelIcon />}
key="cancel"
onClick={() => {
props.onClose();
}}
/>,
<IconButton
type="primary"
text={Locale.UI.Confirm}
icon={<ConfirmIcon />}
key="ok"
onClick={() => {
chatStore.updateCurrentSession(
(session) => (session.messages = messages),
);
props.onClose();
}}
/>,
]}
>
<List>
<ListItem
title={Locale.Chat.EditMessage.Topic.Title}
subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
>
<input
type="text"
value={session.topic}
onInput={(e) =>
chatStore.updateCurrentSession(
(session) => (session.topic = e.currentTarget.value),
)
}
></input>
</ListItem>
</List>
<ContextPrompts
context={messages}
updateContext={(updater) => {
const newMessages = messages.slice();
updater(newMessages);
setMessages(newMessages);
}}
/>
</Modal>
</div>
);
}
function _Chat() {
type RenderMessage = ChatMessage & { preview?: boolean };
2023-04-02 15:05:54 +00:00
const chatStore = useChatStore();
const session = chatStore.currentSession();
2023-04-21 16:12:07 +00:00
const config = useAppConfig();
const fontSize = config.fontSize;
2023-04-02 15:05:54 +00:00
const [showExport, setShowExport] = useState(false);
2023-04-02 15:05:54 +00:00
const inputRef = useRef<HTMLTextAreaElement>(null);
const [userInput, setUserInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const { submitKey, shouldSubmit } = useSubmitHandler();
const { scrollRef, setAutoScroll, scrollDomToBottom } = useScrollToBottom();
const [hitBottom, setHitBottom] = useState(true);
2023-04-20 15:20:25 +00:00
const isMobileScreen = useMobileScreen();
2023-04-20 17:12:39 +00:00
const navigate = useNavigate();
2023-04-02 18:28:07 +00:00
2023-04-02 15:05:54 +00:00
// prompt hints
const promptStore = usePromptStore();
2023-07-09 11:37:42 +00:00
const [promptHints, setPromptHints] = useState<RenderPompt[]>([]);
2023-04-02 15:05:54 +00:00
const onSearch = useDebouncedCallback(
(text: string) => {
2023-06-24 15:38:11 +00:00
const matchedPrompts = promptStore.search(text);
setPromptHints(matchedPrompts);
2023-04-02 15:05:54 +00:00
},
100,
{ leading: true, trailing: true },
);
2023-04-07 18:36:02 +00:00
// auto grow input
const [inputRows, setInputRows] = useState(2);
const measure = useDebouncedCallback(
() => {
const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
const inputRows = Math.min(
20,
2023-04-20 15:20:25 +00:00
Math.max(2 + Number(!isMobileScreen), rows),
2023-04-07 18:36:02 +00:00
);
setInputRows(inputRows);
},
100,
{
leading: true,
trailing: true,
},
);
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(measure, [userInput]);
2023-04-07 04:17:37 +00:00
2023-06-24 15:38:11 +00:00
// chat commands shortcuts
const chatCommands = useChatCommand({
new: () => chatStore.newSession(),
newm: () => navigate(Path.NewChat),
prev: () => chatStore.nextSession(-1),
next: () => chatStore.nextSession(1),
clear: () =>
chatStore.updateCurrentSession(
(session) => (session.clearContextIndex = session.messages.length),
),
del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
});
2023-04-02 15:05:54 +00:00
// only search prompts when user input is short
const SEARCH_TEXT_LIMIT = 30;
const onInput = (text: string) => {
setUserInput(text);
const n = text.trim().length;
// clear search results
if (n === 0) {
setPromptHints([]);
2023-06-24 15:38:11 +00:00
} else if (text.startsWith(ChatCommandPrefix)) {
setPromptHints(chatCommands.search(text));
2023-04-21 16:12:07 +00:00
} else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
2023-04-02 15:05:54 +00:00
// check if need to trigger auto completion
if (text.startsWith("/")) {
let searchText = text.slice(1);
onSearch(searchText);
2023-04-02 15:05:54 +00:00
}
}
};
const doSubmit = (userInput: string) => {
if (userInput.trim() === "") return;
2023-06-24 15:38:11 +00:00
const matchCommand = chatCommands.match(userInput);
if (matchCommand.matched) {
setUserInput("");
setPromptHints([]);
matchCommand.invoke();
return;
}
2023-04-02 15:05:54 +00:00
setIsLoading(true);
chatStore.onUserInput(userInput).then(() => setIsLoading(false));
localStorage.setItem(LAST_INPUT_KEY, userInput);
2023-04-02 15:05:54 +00:00
setUserInput("");
setPromptHints([]);
2023-04-20 15:20:25 +00:00
if (!isMobileScreen) inputRef.current?.focus();
2023-04-03 06:56:13 +00:00
setAutoScroll(true);
2023-04-02 15:05:54 +00:00
};
2023-07-09 11:37:42 +00:00
const onPromptSelect = (prompt: RenderPompt) => {
2023-06-27 15:39:27 +00:00
setTimeout(() => {
setPromptHints([]);
const matchedChatCommand = chatCommands.match(prompt.content);
if (matchedChatCommand.matched) {
// if user is selecting a chat command, just trigger it
matchedChatCommand.invoke();
setUserInput("");
} else {
// or fill the prompt
setUserInput(prompt.content);
}
inputRef.current?.focus();
}, 30);
};
2023-04-02 15:05:54 +00:00
// stop response
2023-07-09 11:37:42 +00:00
const onUserStop = (messageId: string) => {
ChatControllerPool.stop(session.id, messageId);
};
useEffect(() => {
2023-05-17 17:24:36 +00:00
chatStore.updateCurrentSession((session) => {
const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
session.messages.forEach((m) => {
// check if should stop all stale messages
2023-05-20 11:58:12 +00:00
if (m.isError || new Date(m.date).getTime() < stopTiming) {
if (m.streaming) {
m.streaming = false;
}
if (m.content.length === 0) {
2023-05-20 11:58:12 +00:00
m.isError = true;
m.content = prettyObject({
error: true,
message: "empty response",
});
}
2023-05-17 17:24:36 +00:00
}
});
// auto sync mask config from global config
if (session.mask.syncGlobalConfig) {
console.log("[Mask] syncing from global, name = ", session.mask.name);
session.mask.modelConfig = { ...config.modelConfig };
}
2023-05-17 17:24:36 +00:00
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
2023-04-02 15:05:54 +00:00
// check if should send message
const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// if ArrowUp and no userInput, fill with last input
if (
e.key === "ArrowUp" &&
userInput.length <= 0 &&
!(e.metaKey || e.altKey || e.ctrlKey)
) {
setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
e.preventDefault();
return;
}
if (shouldSubmit(e) && promptHints.length === 0) {
doSubmit(userInput);
2023-04-02 15:05:54 +00:00
e.preventDefault();
}
};
const onRightClick = (e: any, message: ChatMessage) => {
2023-04-02 15:05:54 +00:00
// copy to clipboard
if (selectOrCopy(e.currentTarget, message.content)) {
if (userInput.length === 0) {
setUserInput(message.content);
}
2023-04-02 15:05:54 +00:00
e.preventDefault();
}
};
2023-07-09 11:37:42 +00:00
const deleteMessage = (msgId?: string) => {
2023-07-09 08:15:58 +00:00
chatStore.updateCurrentSession(
(session) =>
(session.messages = session.messages.filter((m) => m.id !== msgId)),
);
};
2023-07-09 11:37:42 +00:00
const onDelete = (msgId: string) => {
2023-07-09 08:15:58 +00:00
deleteMessage(msgId);
};
2023-07-09 08:39:46 +00:00
const onResend = (message: ChatMessage) => {
// when it is resending a message
// 1. for a user's message, find the next bot response
// 2. for a bot's message, find the last user's input
// 3. delete original user input and bot's message
// 4. resend the user's input
const resendingIndex = session.messages.findIndex(
(m) => m.id === message.id,
);
if (resendingIndex <= 0 || resendingIndex >= session.messages.length) {
console.error("[Chat] failed to find resending message", message);
return;
}
let userMessage: ChatMessage | undefined;
let botMessage: ChatMessage | undefined;
2023-07-09 08:39:46 +00:00
if (message.role === "assistant") {
// if it is resending a bot's message, find the user input for it
botMessage = message;
for (let i = resendingIndex; i >= 0; i -= 1) {
if (session.messages[i].role === "user") {
userMessage = session.messages[i];
break;
}
2023-07-09 08:39:46 +00:00
}
} else if (message.role === "user") {
// if it is resending a user's input, find the bot's response
userMessage = message;
for (let i = resendingIndex; i < session.messages.length; i += 1) {
if (session.messages[i].role === "assistant") {
botMessage = session.messages[i];
break;
}
}
}
if (userMessage === undefined) {
console.error("[Chat] failed to resend", message);
return;
2023-07-09 08:39:46 +00:00
}
// delete the original messages
deleteMessage(userMessage.id);
deleteMessage(botMessage?.id);
// resend the message
setIsLoading(true);
chatStore.onUserInput(userMessage.content).then(() => setIsLoading(false));
inputRef.current?.focus();
2023-04-02 15:05:54 +00:00
};
2023-07-09 08:15:58 +00:00
const onPinMessage = (message: ChatMessage) => {
chatStore.updateCurrentSession((session) =>
2023-07-09 08:15:58 +00:00
session.mask.context.push(message),
);
showToast(Locale.Chat.Actions.PinToastContent, {
text: Locale.Chat.Actions.PinToastAction,
onClick: () => {
setShowPromptModal(true);
},
});
};
const context: RenderMessage[] = useMemo(() => {
return session.mask.hideContext ? [] : session.mask.context.slice();
}, [session.mask.context, session.mask.hideContext]);
2023-04-09 15:51:12 +00:00
const accessStore = useAccessStore();
if (
context.length === 0 &&
session.messages.at(0)?.content !== BOT_HELLO.content
) {
2023-04-09 15:51:12 +00:00
const copiedHello = Object.assign({}, BOT_HELLO);
if (!accessStore.isAuthorized()) {
copiedHello.content = Locale.Error.Unauthorized;
}
context.push(copiedHello);
}
2023-05-20 17:28:09 +00:00
// clear context index = context length + index in messages
const clearContextIndex =
(session.clearContextIndex ?? -1) >= 0
? session.clearContextIndex! + context.length
: -1;
2023-04-02 15:05:54 +00:00
// preview messages
const renderMessages = useMemo(() => {
return context
.concat(session.messages as RenderMessage[])
.concat(
isLoading
? [
{
...createMessage({
role: "assistant",
content: "……",
}),
preview: true,
},
]
: [],
)
.concat(
userInput.length > 0 && config.sendPreviewBubble
? [
{
...createMessage({
role: "user",
content: userInput,
}),
preview: true,
},
]
: [],
);
}, [
config.sendPreviewBubble,
context,
isLoading,
session.messages,
userInput,
]);
2023-08-03 18:39:32 +00:00
const [msgRenderIndex, _setMsgRenderIndex] = useState(
Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
);
2023-08-03 18:39:32 +00:00
function setMsgRenderIndex(newIndex: number) {
newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
newIndex = Math.max(0, newIndex);
_setMsgRenderIndex(newIndex);
}
const messages = useMemo(() => {
const endRenderIndex = Math.min(
msgRenderIndex + 3 * CHAT_PAGE_SIZE,
renderMessages.length,
2023-04-02 15:05:54 +00:00
);
return renderMessages.slice(msgRenderIndex, endRenderIndex);
}, [msgRenderIndex, renderMessages]);
const onChatBodyScroll = (e: HTMLElement) => {
const bottomHeight = e.scrollTop + e.clientHeight;
2023-08-03 18:39:32 +00:00
const edgeThreshold = e.clientHeight;
const isTouchTopEdge = e.scrollTop <= edgeThreshold;
const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
const isHitBottom = bottomHeight >= e.scrollHeight - 10;
2023-08-03 18:39:32 +00:00
const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
if (isTouchTopEdge) {
2023-08-03 18:39:32 +00:00
setMsgRenderIndex(prevPageMsgIndex);
} else if (isTouchBottomEdge) {
2023-08-03 18:39:32 +00:00
setMsgRenderIndex(nextPageMsgIndex);
}
setHitBottom(isHitBottom);
setAutoScroll(isHitBottom);
};
function scrollToBottom() {
setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
scrollDomToBottom();
}
2023-04-02 15:05:54 +00:00
const [showPromptModal, setShowPromptModal] = useState(false);
const clientConfig = useMemo(() => getClientConfig(), []);
const location = useLocation();
const isChat = location.pathname === Path.Chat;
2023-05-03 08:24:25 +00:00
const autoFocus = !isMobileScreen || isChat; // only focus in chat page
const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
2023-04-02 19:24:29 +00:00
useCommand({
fill: setUserInput,
submit: (text) => {
doSubmit(text);
},
code: (text) => {
console.log("[Command] got code from url: ", text);
showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
if (res) {
accessStore.updateCode(text);
}
});
},
settings: (text) => {
try {
const payload = JSON.parse(text) as {
key?: string;
url?: string;
};
console.log("[Command] got settings from url: ", payload);
if (payload.key || payload.url) {
showConfirm(
Locale.URLCommand.Settings +
`\n${JSON.stringify(payload, null, 4)}`,
).then((res) => {
if (!res) return;
if (payload.key) {
accessStore.updateToken(payload.key);
}
if (payload.url) {
accessStore.updateOpenAiUrl(payload.url);
}
});
}
} catch {
console.error("[Command] failed to get settings from url: ", text);
}
},
});
// edit / insert message modal
const [isEditingMessage, setIsEditingMessage] = useState(false);
2023-04-02 15:05:54 +00:00
return (
<div className={styles.chat} key={session.id}>
2023-06-15 15:20:14 +00:00
<div className="window-header" data-tauri-drag-region>
{isMobileScreen && (
<div className="window-actions">
<div className={"window-action-button"}>
<IconButton
icon={<ReturnIcon />}
bordered
title={Locale.Chat.Actions.ChatList}
onClick={() => navigate(Path.Home)}
/>
</div>
</div>
)}
<div className={`window-header-title ${styles["chat-body-title"]}`}>
2023-04-02 15:05:54 +00:00
<div
className={`window-header-main-title ${styles["chat-body-main-title"]}`}
onClickCapture={() => setIsEditingMessage(true)}
2023-04-02 15:05:54 +00:00
>
2023-04-22 17:27:15 +00:00
{!session.topic ? DEFAULT_TOPIC : session.topic}
2023-04-02 15:05:54 +00:00
</div>
2023-04-24 16:49:27 +00:00
<div className="window-header-sub-title">
2023-04-02 15:05:54 +00:00
{Locale.Chat.SubTitle(session.messages.length)}
</div>
</div>
2023-04-24 16:49:27 +00:00
<div className="window-actions">
{!isMobileScreen && (
<div className="window-action-button">
<IconButton
icon={<RenameIcon />}
bordered
onClick={() => setIsEditingMessage(true)}
/>
</div>
)}
2023-04-24 16:49:27 +00:00
<div className="window-action-button">
2023-04-02 15:05:54 +00:00
<IconButton
icon={<ExportIcon />}
bordered
title={Locale.Chat.Actions.Export}
onClick={() => {
setShowExport(true);
2023-04-02 15:05:54 +00:00
}}
/>
</div>
{showMaxIcon && (
2023-04-24 16:49:27 +00:00
<div className="window-action-button">
<IconButton
2023-04-21 16:12:07 +00:00
icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
bordered
onClick={() => {
2023-04-21 16:12:07 +00:00
config.update(
(config) => (config.tightBorder = !config.tightBorder),
);
}}
/>
</div>
)}
2023-04-02 15:05:54 +00:00
</div>
<PromptToast
2023-04-02 18:28:07 +00:00
showToast={!hitBottom}
showModal={showPromptModal}
setShowModal={setShowPromptModal}
/>
2023-04-02 15:05:54 +00:00
</div>
2023-04-02 18:28:07 +00:00
<div
className={styles["chat-body"]}
ref={scrollRef}
onScroll={(e) => onChatBodyScroll(e.currentTarget)}
onMouseDown={() => inputRef.current?.blur()}
2023-04-03 06:56:13 +00:00
onTouchStart={() => {
inputRef.current?.blur();
setAutoScroll(false);
}}
2023-04-02 18:28:07 +00:00
>
2023-04-02 15:05:54 +00:00
{messages.map((message, i) => {
const isUser = message.role === "user";
2023-07-09 08:39:46 +00:00
const isContext = i < context.length;
const showActions =
i > 0 &&
!(message.preview || message.content.length === 0) &&
!isContext;
const showTyping = message.preview || message.streaming;
2023-04-02 15:05:54 +00:00
2023-05-20 17:28:09 +00:00
const shouldShowClearContextDivider = i === clearContextIndex - 1;
2023-04-02 15:05:54 +00:00
return (
<Fragment key={message.id}>
2023-05-20 17:28:09 +00:00
<div
className={
isUser ? styles["chat-message-user"] : styles["chat-message"]
}
>
<div className={styles["chat-message-container"]}>
2023-07-09 08:15:58 +00:00
<div className={styles["chat-message-header"]}>
<div className={styles["chat-message-avatar"]}>
<div className={styles["chat-message-edit"]}>
<IconButton
icon={<EditIcon />}
onClick={async () => {
const newMessage = await showPrompt(
Locale.Chat.Actions.Edit,
message.content,
10,
);
2023-07-09 08:15:58 +00:00
chatStore.updateCurrentSession((session) => {
const m = session.messages.find(
(m) => m.id === message.id,
);
if (m) {
m.content = newMessage;
}
});
}}
></IconButton>
</div>
{isUser ? (
<Avatar avatar={config.avatar} />
) : (
<MaskAvatar mask={session.mask} />
)}
2023-05-20 17:28:09 +00:00
</div>
2023-06-25 15:53:22 +00:00
{showActions && (
<div className={styles["chat-message-actions"]}>
2023-07-09 08:15:58 +00:00
<div className={styles["chat-input-actions"]}>
2023-06-25 15:53:22 +00:00
{message.streaming ? (
<ChatAction
text={Locale.Chat.Actions.Stop}
icon={<StopIcon />}
onClick={() => onUserStop(message.id ?? i)}
/>
) : (
<>
<ChatAction
text={Locale.Chat.Actions.Retry}
icon={<ResetIcon />}
2023-07-09 08:39:46 +00:00
onClick={() => onResend(message)}
2023-06-25 15:53:22 +00:00
/>
<ChatAction
text={Locale.Chat.Actions.Delete}
icon={<DeleteIcon />}
onClick={() => onDelete(message.id ?? i)}
/>
<ChatAction
text={Locale.Chat.Actions.Pin}
icon={<PinIcon />}
onClick={() => onPinMessage(message)}
/>
<ChatAction
text={Locale.Chat.Actions.Copy}
icon={<CopyIcon />}
onClick={() => copyToClipboard(message.content)}
/>
2023-06-25 15:53:22 +00:00
</>
)}
</div>
2023-04-02 15:05:54 +00:00
</div>
2023-06-25 15:53:22 +00:00
)}
</div>
2023-07-09 08:15:58 +00:00
{showTyping && (
<div className={styles["chat-message-status"]}>
{Locale.Chat.Typing}
</div>
)}
<div className={styles["chat-message-item"]}>
<Markdown
content={message.content}
loading={
(message.preview || message.streaming) &&
message.content.length === 0 &&
2023-07-09 08:15:58 +00:00
!isUser
}
onContextMenu={(e) => onRightClick(e, message)}
onDoubleClickCapture={() => {
if (!isMobileScreen) return;
setUserInput(message.content);
}}
fontSize={fontSize}
parentRef={scrollRef}
defaultShow={i >= messages.length - 6}
2023-07-09 08:15:58 +00:00
/>
</div>
2023-07-09 08:39:46 +00:00
<div className={styles["chat-message-action-date"]}>
{isContext
? Locale.Chat.IsContext
: message.date.toLocaleString()}
</div>
2023-04-02 15:05:54 +00:00
</div>
</div>
2023-05-20 17:28:09 +00:00
{shouldShowClearContextDivider && <ClearContextDivider />}
2023-07-14 13:15:34 +00:00
</Fragment>
2023-04-02 15:05:54 +00:00
);
})}
</div>
<div className={styles["chat-input-panel"]}>
<PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
<ChatActions
showPromptModal={() => setShowPromptModal(true)}
scrollToBottom={scrollToBottom}
hitBottom={hitBottom}
2023-04-25 18:02:46 +00:00
showPromptHints={() => {
// Click again to close
if (promptHints.length > 0) {
setPromptHints([]);
return;
}
2023-04-25 18:02:46 +00:00
inputRef.current?.focus();
setUserInput("/");
2023-04-25 18:02:46 +00:00
onSearch("");
}}
/>
2023-04-02 15:05:54 +00:00
<div className={styles["chat-input-panel-inner"]}>
<textarea
ref={inputRef}
className={styles["chat-input"]}
placeholder={Locale.Chat.Input(submitKey)}
onInput={(e) => onInput(e.currentTarget.value)}
value={userInput}
onKeyDown={onInputKeyDown}
onFocus={scrollToBottom}
onClick={scrollToBottom}
2023-04-07 18:36:02 +00:00
rows={inputRows}
autoFocus={autoFocus}
style={{
fontSize: config.fontSize,
}}
2023-04-02 15:05:54 +00:00
/>
<IconButton
icon={<SendWhiteIcon />}
text={Locale.Chat.Send}
2023-04-02 18:28:07 +00:00
className={styles["chat-input-send"]}
type="primary"
onClick={() => doSubmit(userInput)}
2023-04-02 15:05:54 +00:00
/>
</div>
</div>
{showExport && (
<ExportMessageModal onClose={() => setShowExport(false)} />
)}
{isEditingMessage && (
<EditMessageModal
onClose={() => {
setIsEditingMessage(false);
}}
/>
)}
2023-04-02 15:05:54 +00:00
</div>
);
}
export function Chat() {
const chatStore = useChatStore();
const sessionIndex = chatStore.currentSessionIndex;
return <_Chat key={sessionIndex}></_Chat>;
}