chat.tsx 27 KB

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