chat.tsx 26 KB

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