chat.tsx 29 KB

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