chat.tsx 27 KB

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