chat.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. import { useDebouncedCallback } from "use-debounce";
  2. import React, {
  3. useState,
  4. useRef,
  5. useEffect,
  6. useMemo,
  7. useCallback,
  8. } from "react";
  9. import SendWhiteIcon from "../icons/send-white.svg";
  10. import BrainIcon from "../icons/brain.svg";
  11. import RenameIcon from "../icons/rename.svg";
  12. import ExportIcon from "../icons/share.svg";
  13. import ReturnIcon from "../icons/return.svg";
  14. import CopyIcon from "../icons/copy.svg";
  15. import LoadingIcon from "../icons/three-dots.svg";
  16. import PromptIcon from "../icons/prompt.svg";
  17. import MaskIcon from "../icons/mask.svg";
  18. import MaxIcon from "../icons/max.svg";
  19. import MinIcon from "../icons/min.svg";
  20. import ResetIcon from "../icons/reload.svg";
  21. import BreakIcon from "../icons/break.svg";
  22. import SettingsIcon from "../icons/chat-settings.svg";
  23. import DeleteIcon from "../icons/clear.svg";
  24. import PinIcon from "../icons/pin.svg";
  25. import LightIcon from "../icons/light.svg";
  26. import DarkIcon from "../icons/dark.svg";
  27. import AutoIcon from "../icons/auto.svg";
  28. import BottomIcon from "../icons/bottom.svg";
  29. import StopIcon from "../icons/pause.svg";
  30. import RobotIcon from "../icons/robot.svg";
  31. import {
  32. ChatMessage,
  33. SubmitKey,
  34. useChatStore,
  35. BOT_HELLO,
  36. createMessage,
  37. useAccessStore,
  38. Theme,
  39. useAppConfig,
  40. DEFAULT_TOPIC,
  41. ALL_MODELS,
  42. } from "../store";
  43. import {
  44. copyToClipboard,
  45. downloadAs,
  46. selectOrCopy,
  47. autoGrowTextArea,
  48. useMobileScreen,
  49. } from "../utils";
  50. import dynamic from "next/dynamic";
  51. import { ChatControllerPool } from "../client/controller";
  52. import { Prompt, usePromptStore } from "../store/prompt";
  53. import Locale from "../locales";
  54. import { IconButton } from "./button";
  55. import styles from "./chat.module.scss";
  56. import { ListItem, Modal, showToast } from "./ui-lib";
  57. import { useLocation, useNavigate } from "react-router-dom";
  58. import { LAST_INPUT_KEY, Path, REQUEST_TIMEOUT_MS } from "../constant";
  59. import { Avatar } from "./emoji";
  60. import { MaskAvatar, MaskConfig } from "./mask";
  61. import { useMaskStore } from "../store/mask";
  62. import { ChatCommandPrefix, useChatCommand, useCommand } from "../command";
  63. import { prettyObject } from "../utils/format";
  64. import { ExportMessageModal } from "./exporter";
  65. import { getClientConfig } from "../config/client";
  66. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  67. loading: () => <LoadingIcon />,
  68. });
  69. export function SessionConfigModel(props: { onClose: () => void }) {
  70. const chatStore = useChatStore();
  71. const session = chatStore.currentSession();
  72. const maskStore = useMaskStore();
  73. const navigate = useNavigate();
  74. return (
  75. <div className="modal-mask">
  76. <Modal
  77. title={Locale.Context.Edit}
  78. onClose={() => props.onClose()}
  79. actions={[
  80. <IconButton
  81. key="reset"
  82. icon={<ResetIcon />}
  83. bordered
  84. text={Locale.Chat.Config.Reset}
  85. onClick={() => {
  86. if (confirm(Locale.Memory.ResetConfirm)) {
  87. chatStore.updateCurrentSession(
  88. (session) => (session.memoryPrompt = ""),
  89. );
  90. }
  91. }}
  92. />,
  93. <IconButton
  94. key="copy"
  95. icon={<CopyIcon />}
  96. bordered
  97. text={Locale.Chat.Config.SaveAs}
  98. onClick={() => {
  99. navigate(Path.Masks);
  100. setTimeout(() => {
  101. maskStore.create(session.mask);
  102. }, 500);
  103. }}
  104. />,
  105. ]}
  106. >
  107. <MaskConfig
  108. mask={session.mask}
  109. updateMask={(updater) => {
  110. const mask = { ...session.mask };
  111. updater(mask);
  112. chatStore.updateCurrentSession((session) => (session.mask = mask));
  113. }}
  114. shouldSyncFromGlobal
  115. extraListItems={
  116. session.mask.modelConfig.sendMemory ? (
  117. <ListItem
  118. title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`}
  119. subTitle={session.memoryPrompt || Locale.Memory.EmptyContent}
  120. ></ListItem>
  121. ) : (
  122. <></>
  123. )
  124. }
  125. ></MaskConfig>
  126. </Modal>
  127. </div>
  128. );
  129. }
  130. function PromptToast(props: {
  131. showToast?: boolean;
  132. showModal?: boolean;
  133. setShowModal: (_: boolean) => void;
  134. }) {
  135. const chatStore = useChatStore();
  136. const session = chatStore.currentSession();
  137. const context = session.mask.context;
  138. return (
  139. <div className={styles["prompt-toast"]} key="prompt-toast">
  140. {props.showToast && (
  141. <div
  142. className={styles["prompt-toast-inner"] + " clickable"}
  143. role="button"
  144. onClick={() => props.setShowModal(true)}
  145. >
  146. <BrainIcon />
  147. <span className={styles["prompt-toast-content"]}>
  148. {Locale.Context.Toast(context.length)}
  149. </span>
  150. </div>
  151. )}
  152. {props.showModal && (
  153. <SessionConfigModel onClose={() => props.setShowModal(false)} />
  154. )}
  155. </div>
  156. );
  157. }
  158. function useSubmitHandler() {
  159. const config = useAppConfig();
  160. const submitKey = config.submitKey;
  161. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  162. if (e.key !== "Enter") return false;
  163. if (e.key === "Enter" && e.nativeEvent.isComposing) return false;
  164. return (
  165. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  166. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  167. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  168. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  169. (config.submitKey === SubmitKey.Enter &&
  170. !e.altKey &&
  171. !e.ctrlKey &&
  172. !e.shiftKey &&
  173. !e.metaKey)
  174. );
  175. };
  176. return {
  177. submitKey,
  178. shouldSubmit,
  179. };
  180. }
  181. export function PromptHints(props: {
  182. prompts: Prompt[];
  183. onPromptSelect: (prompt: Prompt) => void;
  184. }) {
  185. const noPrompts = props.prompts.length === 0;
  186. const [selectIndex, setSelectIndex] = useState(0);
  187. const selectedRef = useRef<HTMLDivElement>(null);
  188. useEffect(() => {
  189. setSelectIndex(0);
  190. }, [props.prompts.length]);
  191. useEffect(() => {
  192. const onKeyDown = (e: KeyboardEvent) => {
  193. if (noPrompts || e.metaKey || e.altKey || e.ctrlKey) {
  194. return;
  195. }
  196. // arrow up / down to select prompt
  197. const changeIndex = (delta: number) => {
  198. e.stopPropagation();
  199. e.preventDefault();
  200. const nextIndex = Math.max(
  201. 0,
  202. Math.min(props.prompts.length - 1, selectIndex + delta),
  203. );
  204. setSelectIndex(nextIndex);
  205. selectedRef.current?.scrollIntoView({
  206. block: "center",
  207. });
  208. };
  209. if (e.key === "ArrowUp") {
  210. changeIndex(1);
  211. } else if (e.key === "ArrowDown") {
  212. changeIndex(-1);
  213. } else if (e.key === "Enter") {
  214. const selectedPrompt = props.prompts.at(selectIndex);
  215. if (selectedPrompt) {
  216. props.onPromptSelect(selectedPrompt);
  217. }
  218. }
  219. };
  220. window.addEventListener("keydown", onKeyDown);
  221. return () => window.removeEventListener("keydown", onKeyDown);
  222. // eslint-disable-next-line react-hooks/exhaustive-deps
  223. }, [props.prompts.length, selectIndex]);
  224. if (noPrompts) return null;
  225. return (
  226. <div className={styles["prompt-hints"]}>
  227. {props.prompts.map((prompt, i) => (
  228. <div
  229. ref={i === selectIndex ? selectedRef : null}
  230. className={
  231. styles["prompt-hint"] +
  232. ` ${i === selectIndex ? styles["prompt-hint-selected"] : ""}`
  233. }
  234. key={prompt.title + i.toString()}
  235. onClick={() => props.onPromptSelect(prompt)}
  236. onMouseEnter={() => setSelectIndex(i)}
  237. >
  238. <div className={styles["hint-title"]}>{prompt.title}</div>
  239. <div className={styles["hint-content"]}>{prompt.content}</div>
  240. </div>
  241. ))}
  242. </div>
  243. );
  244. }
  245. function ClearContextDivider() {
  246. const chatStore = useChatStore();
  247. return (
  248. <div
  249. className={styles["clear-context"]}
  250. onClick={() =>
  251. chatStore.updateCurrentSession(
  252. (session) => (session.clearContextIndex = undefined),
  253. )
  254. }
  255. >
  256. <div className={styles["clear-context-tips"]}>{Locale.Context.Clear}</div>
  257. <div className={styles["clear-context-revert-btn"]}>
  258. {Locale.Context.Revert}
  259. </div>
  260. </div>
  261. );
  262. }
  263. function ChatAction(props: {
  264. text: string;
  265. icon: JSX.Element;
  266. onClick: () => void;
  267. }) {
  268. const iconRef = useRef<HTMLDivElement>(null);
  269. const textRef = useRef<HTMLDivElement>(null);
  270. const [width, setWidth] = useState({
  271. full: 16,
  272. icon: 16,
  273. });
  274. function updateWidth() {
  275. if (!iconRef.current || !textRef.current) return;
  276. const getWidth = (dom: HTMLDivElement) => dom.getBoundingClientRect().width;
  277. const textWidth = getWidth(textRef.current);
  278. const iconWidth = getWidth(iconRef.current);
  279. setWidth({
  280. full: textWidth + iconWidth,
  281. icon: iconWidth,
  282. });
  283. }
  284. return (
  285. <div
  286. className={`${styles["chat-input-action"]} clickable`}
  287. onClick={() => {
  288. props.onClick();
  289. setTimeout(updateWidth, 1);
  290. }}
  291. style={
  292. {
  293. "--icon-width": `${width.icon}px`,
  294. "--full-width": `${width.full}px`,
  295. } as React.CSSProperties
  296. }
  297. >
  298. <div ref={iconRef} className={styles["icon"]}>
  299. {props.icon}
  300. </div>
  301. <div className={styles["text"]} ref={textRef}>
  302. {props.text}
  303. </div>
  304. </div>
  305. );
  306. }
  307. function useScrollToBottom() {
  308. // for auto-scroll
  309. const scrollRef = useRef<HTMLDivElement>(null);
  310. const [autoScroll, setAutoScroll] = useState(true);
  311. const scrollToBottom = useCallback(() => {
  312. const dom = scrollRef.current;
  313. if (dom) {
  314. requestAnimationFrame(() => dom.scrollTo(0, dom.scrollHeight));
  315. }
  316. }, []);
  317. // auto scroll
  318. useEffect(() => {
  319. autoScroll && scrollToBottom();
  320. });
  321. return {
  322. scrollRef,
  323. autoScroll,
  324. setAutoScroll,
  325. scrollToBottom,
  326. };
  327. }
  328. export function ChatActions(props: {
  329. showPromptModal: () => void;
  330. scrollToBottom: () => void;
  331. showPromptHints: () => void;
  332. hitBottom: boolean;
  333. }) {
  334. const config = useAppConfig();
  335. const navigate = useNavigate();
  336. const chatStore = useChatStore();
  337. // switch themes
  338. const theme = config.theme;
  339. function nextTheme() {
  340. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  341. const themeIndex = themes.indexOf(theme);
  342. const nextIndex = (themeIndex + 1) % themes.length;
  343. const nextTheme = themes[nextIndex];
  344. config.update((config) => (config.theme = nextTheme));
  345. }
  346. // stop all responses
  347. const couldStop = ChatControllerPool.hasPending();
  348. const stopAll = () => ChatControllerPool.stopAll();
  349. // switch model
  350. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  351. function nextModel() {
  352. const models = ALL_MODELS.filter((m) => m.available).map((m) => m.name);
  353. const modelIndex = models.indexOf(currentModel);
  354. const nextIndex = (modelIndex + 1) % models.length;
  355. const nextModel = models[nextIndex];
  356. chatStore.updateCurrentSession((session) => {
  357. session.mask.modelConfig.model = nextModel;
  358. session.mask.syncGlobalConfig = false;
  359. });
  360. }
  361. return (
  362. <div className={styles["chat-input-actions"]}>
  363. {couldStop && (
  364. <ChatAction
  365. onClick={stopAll}
  366. text={Locale.Chat.InputActions.Stop}
  367. icon={<StopIcon />}
  368. />
  369. )}
  370. {!props.hitBottom && (
  371. <ChatAction
  372. onClick={props.scrollToBottom}
  373. text={Locale.Chat.InputActions.ToBottom}
  374. icon={<BottomIcon />}
  375. />
  376. )}
  377. {props.hitBottom && (
  378. <ChatAction
  379. onClick={props.showPromptModal}
  380. text={Locale.Chat.InputActions.Settings}
  381. icon={<SettingsIcon />}
  382. />
  383. )}
  384. <ChatAction
  385. onClick={nextTheme}
  386. text={Locale.Chat.InputActions.Theme[theme]}
  387. icon={
  388. <>
  389. {theme === Theme.Auto ? (
  390. <AutoIcon />
  391. ) : theme === Theme.Light ? (
  392. <LightIcon />
  393. ) : theme === Theme.Dark ? (
  394. <DarkIcon />
  395. ) : null}
  396. </>
  397. }
  398. />
  399. <ChatAction
  400. onClick={props.showPromptHints}
  401. text={Locale.Chat.InputActions.Prompt}
  402. icon={<PromptIcon />}
  403. />
  404. <ChatAction
  405. onClick={() => {
  406. navigate(Path.Masks);
  407. }}
  408. text={Locale.Chat.InputActions.Masks}
  409. icon={<MaskIcon />}
  410. />
  411. <ChatAction
  412. text={Locale.Chat.InputActions.Clear}
  413. icon={<BreakIcon />}
  414. onClick={() => {
  415. chatStore.updateCurrentSession((session) => {
  416. if (session.clearContextIndex === session.messages.length) {
  417. session.clearContextIndex = undefined;
  418. } else {
  419. session.clearContextIndex = session.messages.length;
  420. session.memoryPrompt = ""; // will clear memory
  421. }
  422. });
  423. }}
  424. />
  425. <ChatAction
  426. onClick={nextModel}
  427. text={currentModel}
  428. icon={<RobotIcon />}
  429. />
  430. </div>
  431. );
  432. }
  433. export function Chat() {
  434. type RenderMessage = ChatMessage & { preview?: boolean };
  435. const chatStore = useChatStore();
  436. const [session, sessionIndex] = useChatStore((state) => [
  437. state.currentSession(),
  438. state.currentSessionIndex,
  439. ]);
  440. const config = useAppConfig();
  441. const fontSize = config.fontSize;
  442. const [showExport, setShowExport] = useState(false);
  443. const inputRef = useRef<HTMLTextAreaElement>(null);
  444. const [userInput, setUserInput] = useState("");
  445. const [isLoading, setIsLoading] = useState(false);
  446. const { submitKey, shouldSubmit } = useSubmitHandler();
  447. const { scrollRef, setAutoScroll, scrollToBottom } = useScrollToBottom();
  448. const [hitBottom, setHitBottom] = useState(true);
  449. const isMobileScreen = useMobileScreen();
  450. const navigate = useNavigate();
  451. const onChatBodyScroll = (e: HTMLElement) => {
  452. const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 10;
  453. setHitBottom(isTouchBottom);
  454. };
  455. // prompt hints
  456. const promptStore = usePromptStore();
  457. const [promptHints, setPromptHints] = useState<Prompt[]>([]);
  458. const onSearch = useDebouncedCallback(
  459. (text: string) => {
  460. const matchedPrompts = promptStore.search(text);
  461. setPromptHints(matchedPrompts);
  462. },
  463. 100,
  464. { leading: true, trailing: true },
  465. );
  466. // auto grow input
  467. const [inputRows, setInputRows] = useState(2);
  468. const measure = useDebouncedCallback(
  469. () => {
  470. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  471. const inputRows = Math.min(
  472. 20,
  473. Math.max(2 + Number(!isMobileScreen), rows),
  474. );
  475. setInputRows(inputRows);
  476. },
  477. 100,
  478. {
  479. leading: true,
  480. trailing: true,
  481. },
  482. );
  483. // eslint-disable-next-line react-hooks/exhaustive-deps
  484. useEffect(measure, [userInput]);
  485. // chat commands shortcuts
  486. const chatCommands = useChatCommand({
  487. new: () => chatStore.newSession(),
  488. newm: () => navigate(Path.NewChat),
  489. prev: () => chatStore.nextSession(-1),
  490. next: () => chatStore.nextSession(1),
  491. clear: () =>
  492. chatStore.updateCurrentSession(
  493. (session) => (session.clearContextIndex = session.messages.length),
  494. ),
  495. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  496. });
  497. // only search prompts when user input is short
  498. const SEARCH_TEXT_LIMIT = 30;
  499. const onInput = (text: string) => {
  500. setUserInput(text);
  501. const n = text.trim().length;
  502. // clear search results
  503. if (n === 0) {
  504. setPromptHints([]);
  505. } else if (text.startsWith(ChatCommandPrefix)) {
  506. setPromptHints(chatCommands.search(text));
  507. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  508. // check if need to trigger auto completion
  509. if (text.startsWith("/")) {
  510. let searchText = text.slice(1);
  511. onSearch(searchText);
  512. }
  513. }
  514. };
  515. const doSubmit = (userInput: string) => {
  516. if (userInput.trim() === "") return;
  517. const matchCommand = chatCommands.match(userInput);
  518. if (matchCommand.matched) {
  519. setUserInput("");
  520. setPromptHints([]);
  521. matchCommand.invoke();
  522. return;
  523. }
  524. setIsLoading(true);
  525. chatStore.onUserInput(userInput).then(() => setIsLoading(false));
  526. localStorage.setItem(LAST_INPUT_KEY, userInput);
  527. setUserInput("");
  528. setPromptHints([]);
  529. if (!isMobileScreen) inputRef.current?.focus();
  530. setAutoScroll(true);
  531. };
  532. const onPromptSelect = (prompt: Prompt) => {
  533. setTimeout(() => {
  534. setPromptHints([]);
  535. const matchedChatCommand = chatCommands.match(prompt.content);
  536. if (matchedChatCommand.matched) {
  537. // if user is selecting a chat command, just trigger it
  538. matchedChatCommand.invoke();
  539. setUserInput("");
  540. } else {
  541. // or fill the prompt
  542. setUserInput(prompt.content);
  543. }
  544. inputRef.current?.focus();
  545. }, 30);
  546. };
  547. // stop response
  548. const onUserStop = (messageId: number) => {
  549. ChatControllerPool.stop(sessionIndex, messageId);
  550. };
  551. useEffect(() => {
  552. chatStore.updateCurrentSession((session) => {
  553. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  554. session.messages.forEach((m) => {
  555. // check if should stop all stale messages
  556. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  557. if (m.streaming) {
  558. m.streaming = false;
  559. }
  560. if (m.content.length === 0) {
  561. m.isError = true;
  562. m.content = prettyObject({
  563. error: true,
  564. message: "empty response",
  565. });
  566. }
  567. }
  568. });
  569. // auto sync mask config from global config
  570. if (session.mask.syncGlobalConfig) {
  571. console.log("[Mask] syncing from global, name = ", session.mask.name);
  572. session.mask.modelConfig = { ...config.modelConfig };
  573. }
  574. });
  575. // eslint-disable-next-line react-hooks/exhaustive-deps
  576. }, []);
  577. // check if should send message
  578. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  579. // if ArrowUp and no userInput, fill with last input
  580. if (
  581. e.key === "ArrowUp" &&
  582. userInput.length <= 0 &&
  583. !(e.metaKey || e.altKey || e.ctrlKey)
  584. ) {
  585. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  586. e.preventDefault();
  587. return;
  588. }
  589. if (shouldSubmit(e) && promptHints.length === 0) {
  590. doSubmit(userInput);
  591. e.preventDefault();
  592. }
  593. };
  594. const onRightClick = (e: any, message: ChatMessage) => {
  595. // copy to clipboard
  596. if (selectOrCopy(e.currentTarget, message.content)) {
  597. if (userInput.length === 0) {
  598. setUserInput(message.content);
  599. }
  600. e.preventDefault();
  601. }
  602. };
  603. const findLastUserIndex = (messageId: number) => {
  604. // find last user input message and resend
  605. let lastUserMessageIndex: number | null = null;
  606. for (let i = 0; i < session.messages.length; i += 1) {
  607. const message = session.messages[i];
  608. if (message.id === messageId) {
  609. break;
  610. }
  611. if (message.role === "user") {
  612. lastUserMessageIndex = i;
  613. }
  614. }
  615. return lastUserMessageIndex;
  616. };
  617. const deleteMessage = (userIndex: number) => {
  618. chatStore.updateCurrentSession((session) =>
  619. session.messages.splice(userIndex, 2),
  620. );
  621. };
  622. const onDelete = (botMessageId: number) => {
  623. const userIndex = findLastUserIndex(botMessageId);
  624. if (userIndex === null) return;
  625. deleteMessage(userIndex);
  626. };
  627. const onResend = (botMessageId: number) => {
  628. // find last user input message and resend
  629. const userIndex = findLastUserIndex(botMessageId);
  630. if (userIndex === null) return;
  631. setIsLoading(true);
  632. const content = session.messages[userIndex].content;
  633. deleteMessage(userIndex);
  634. chatStore.onUserInput(content).then(() => setIsLoading(false));
  635. inputRef.current?.focus();
  636. };
  637. const onPinMessage = (botMessage: ChatMessage) => {
  638. if (!botMessage.id) return;
  639. const userMessageIndex = findLastUserIndex(botMessage.id);
  640. if (userMessageIndex === null) return;
  641. const userMessage = session.messages[userMessageIndex];
  642. chatStore.updateCurrentSession((session) =>
  643. session.mask.context.push(userMessage, botMessage),
  644. );
  645. showToast(Locale.Chat.Actions.PinToastContent, {
  646. text: Locale.Chat.Actions.PinToastAction,
  647. onClick: () => {
  648. setShowPromptModal(true);
  649. },
  650. });
  651. };
  652. const context: RenderMessage[] = session.mask.hideContext
  653. ? []
  654. : session.mask.context.slice();
  655. const accessStore = useAccessStore();
  656. if (
  657. context.length === 0 &&
  658. session.messages.at(0)?.content !== BOT_HELLO.content
  659. ) {
  660. const copiedHello = Object.assign({}, BOT_HELLO);
  661. if (!accessStore.isAuthorized()) {
  662. copiedHello.content = Locale.Error.Unauthorized;
  663. }
  664. context.push(copiedHello);
  665. }
  666. // clear context index = context length + index in messages
  667. const clearContextIndex =
  668. (session.clearContextIndex ?? -1) >= 0
  669. ? session.clearContextIndex! + context.length
  670. : -1;
  671. // preview messages
  672. const messages = context
  673. .concat(session.messages as RenderMessage[])
  674. .concat(
  675. isLoading
  676. ? [
  677. {
  678. ...createMessage({
  679. role: "assistant",
  680. content: "……",
  681. }),
  682. preview: true,
  683. },
  684. ]
  685. : [],
  686. )
  687. .concat(
  688. userInput.length > 0 && config.sendPreviewBubble
  689. ? [
  690. {
  691. ...createMessage({
  692. role: "user",
  693. content: userInput,
  694. }),
  695. preview: true,
  696. },
  697. ]
  698. : [],
  699. );
  700. const [showPromptModal, setShowPromptModal] = useState(false);
  701. const renameSession = () => {
  702. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  703. if (newTopic && newTopic !== session.topic) {
  704. chatStore.updateCurrentSession((session) => (session.topic = newTopic!));
  705. }
  706. };
  707. const clientConfig = useMemo(() => getClientConfig(), []);
  708. const location = useLocation();
  709. const isChat = location.pathname === Path.Chat;
  710. const autoFocus = !isMobileScreen || isChat; // only focus in chat page
  711. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  712. useCommand({
  713. fill: setUserInput,
  714. submit: (text) => {
  715. doSubmit(text);
  716. },
  717. });
  718. return (
  719. <div className={styles.chat} key={session.id}>
  720. <div className="window-header" data-tauri-drag-region>
  721. {isMobileScreen && (
  722. <div className="window-actions">
  723. <div className={"window-action-button"}>
  724. <IconButton
  725. icon={<ReturnIcon />}
  726. bordered
  727. title={Locale.Chat.Actions.ChatList}
  728. onClick={() => navigate(Path.Home)}
  729. />
  730. </div>
  731. </div>
  732. )}
  733. <div className={`window-header-title ${styles["chat-body-title"]}`}>
  734. <div
  735. className={`window-header-main-title ${styles["chat-body-main-title"]}`}
  736. onClickCapture={renameSession}
  737. >
  738. {!session.topic ? DEFAULT_TOPIC : session.topic}
  739. </div>
  740. <div className="window-header-sub-title">
  741. {Locale.Chat.SubTitle(session.messages.length)}
  742. </div>
  743. </div>
  744. <div className="window-actions">
  745. {!isMobileScreen && (
  746. <div className="window-action-button">
  747. <IconButton
  748. icon={<RenameIcon />}
  749. bordered
  750. onClick={renameSession}
  751. />
  752. </div>
  753. )}
  754. <div className="window-action-button">
  755. <IconButton
  756. icon={<ExportIcon />}
  757. bordered
  758. title={Locale.Chat.Actions.Export}
  759. onClick={() => {
  760. setShowExport(true);
  761. }}
  762. />
  763. </div>
  764. {showMaxIcon && (
  765. <div className="window-action-button">
  766. <IconButton
  767. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  768. bordered
  769. onClick={() => {
  770. config.update(
  771. (config) => (config.tightBorder = !config.tightBorder),
  772. );
  773. }}
  774. />
  775. </div>
  776. )}
  777. </div>
  778. <PromptToast
  779. showToast={!hitBottom}
  780. showModal={showPromptModal}
  781. setShowModal={setShowPromptModal}
  782. />
  783. </div>
  784. <div
  785. className={styles["chat-body"]}
  786. ref={scrollRef}
  787. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  788. onMouseDown={() => inputRef.current?.blur()}
  789. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  790. onTouchStart={() => {
  791. inputRef.current?.blur();
  792. setAutoScroll(false);
  793. }}
  794. >
  795. {messages.map((message, i) => {
  796. const isUser = message.role === "user";
  797. const showActions =
  798. !isUser &&
  799. i > 0 &&
  800. !(message.preview || message.content.length === 0);
  801. const showTyping = message.preview || message.streaming;
  802. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  803. return (
  804. <>
  805. <div
  806. key={i}
  807. className={
  808. isUser ? styles["chat-message-user"] : styles["chat-message"]
  809. }
  810. >
  811. <div className={styles["chat-message-container"]}>
  812. <div className={styles["chat-message-avatar"]}>
  813. {message.role === "user" ? (
  814. <Avatar avatar={config.avatar} />
  815. ) : (
  816. <MaskAvatar mask={session.mask} />
  817. )}
  818. </div>
  819. {showTyping && (
  820. <div className={styles["chat-message-status"]}>
  821. {Locale.Chat.Typing}
  822. </div>
  823. )}
  824. <div className={styles["chat-message-item"]}>
  825. <Markdown
  826. content={message.content}
  827. loading={
  828. (message.preview || message.content.length === 0) &&
  829. !isUser
  830. }
  831. onContextMenu={(e) => onRightClick(e, message)}
  832. onDoubleClickCapture={() => {
  833. if (!isMobileScreen) return;
  834. setUserInput(message.content);
  835. }}
  836. fontSize={fontSize}
  837. parentRef={scrollRef}
  838. defaultShow={i >= messages.length - 10}
  839. />
  840. {showActions && (
  841. <div className={styles["chat-message-actions"]}>
  842. <div
  843. className={styles["chat-input-actions"]}
  844. style={{
  845. marginTop: 10,
  846. marginBottom: 0,
  847. }}
  848. >
  849. {message.streaming ? (
  850. <ChatAction
  851. text={Locale.Chat.Actions.Stop}
  852. icon={<StopIcon />}
  853. onClick={() => onUserStop(message.id ?? i)}
  854. />
  855. ) : (
  856. <>
  857. <ChatAction
  858. text={Locale.Chat.Actions.Retry}
  859. icon={<ResetIcon />}
  860. onClick={() => onResend(message.id ?? i)}
  861. />
  862. <ChatAction
  863. text={Locale.Chat.Actions.Delete}
  864. icon={<DeleteIcon />}
  865. onClick={() => onDelete(message.id ?? i)}
  866. />
  867. <ChatAction
  868. text={Locale.Chat.Actions.Pin}
  869. icon={<PinIcon />}
  870. onClick={() => onPinMessage(message)}
  871. />
  872. <ChatAction
  873. text={Locale.Chat.Actions.Copy}
  874. icon={<CopyIcon />}
  875. onClick={() => copyToClipboard(message.content)}
  876. />
  877. </>
  878. )}
  879. </div>
  880. <div className={styles["chat-message-action-date"]}>
  881. {message.date.toLocaleString()}
  882. </div>
  883. </div>
  884. )}
  885. </div>
  886. </div>
  887. </div>
  888. {shouldShowClearContextDivider && <ClearContextDivider />}
  889. </>
  890. );
  891. })}
  892. </div>
  893. <div className={styles["chat-input-panel"]}>
  894. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  895. <ChatActions
  896. showPromptModal={() => setShowPromptModal(true)}
  897. scrollToBottom={scrollToBottom}
  898. hitBottom={hitBottom}
  899. showPromptHints={() => {
  900. // Click again to close
  901. if (promptHints.length > 0) {
  902. setPromptHints([]);
  903. return;
  904. }
  905. inputRef.current?.focus();
  906. setUserInput("/");
  907. onSearch("");
  908. }}
  909. />
  910. <div className={styles["chat-input-panel-inner"]}>
  911. <textarea
  912. ref={inputRef}
  913. className={styles["chat-input"]}
  914. placeholder={Locale.Chat.Input(submitKey)}
  915. onInput={(e) => onInput(e.currentTarget.value)}
  916. value={userInput}
  917. onKeyDown={onInputKeyDown}
  918. onFocus={() => setAutoScroll(true)}
  919. onBlur={() => setAutoScroll(false)}
  920. rows={inputRows}
  921. autoFocus={autoFocus}
  922. style={{
  923. fontSize: config.fontSize,
  924. }}
  925. />
  926. <IconButton
  927. icon={<SendWhiteIcon />}
  928. text={Locale.Chat.Send}
  929. className={styles["chat-input-send"]}
  930. type="primary"
  931. onClick={() => doSubmit(userInput)}
  932. />
  933. </div>
  934. </div>
  935. {showExport && (
  936. <ExportMessageModal onClose={() => setShowExport(false)} />
  937. )}
  938. </div>
  939. );
  940. }