chat.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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"]}>上下文已清除</div>
  280. <div className={chatStyle["clear-context-revert-btn"]}>取消清除</div>
  281. </div>
  282. );
  283. }
  284. function useScrollToBottom() {
  285. // for auto-scroll
  286. const scrollRef = useRef<HTMLDivElement>(null);
  287. const [autoScroll, setAutoScroll] = useState(true);
  288. const scrollToBottom = () => {
  289. const dom = scrollRef.current;
  290. if (dom) {
  291. setTimeout(() => (dom.scrollTop = dom.scrollHeight), 1);
  292. }
  293. };
  294. // auto scroll
  295. useLayoutEffect(() => {
  296. autoScroll && scrollToBottom();
  297. });
  298. return {
  299. scrollRef,
  300. autoScroll,
  301. setAutoScroll,
  302. scrollToBottom,
  303. };
  304. }
  305. export function ChatActions(props: {
  306. showPromptModal: () => void;
  307. scrollToBottom: () => void;
  308. showPromptHints: () => void;
  309. hitBottom: boolean;
  310. }) {
  311. const config = useAppConfig();
  312. const navigate = useNavigate();
  313. const chatStore = useChatStore();
  314. // switch themes
  315. const theme = config.theme;
  316. function nextTheme() {
  317. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  318. const themeIndex = themes.indexOf(theme);
  319. const nextIndex = (themeIndex + 1) % themes.length;
  320. const nextTheme = themes[nextIndex];
  321. config.update((config) => (config.theme = nextTheme));
  322. }
  323. // stop all responses
  324. const couldStop = ChatControllerPool.hasPending();
  325. const stopAll = () => ChatControllerPool.stopAll();
  326. return (
  327. <div className={chatStyle["chat-input-actions"]}>
  328. {couldStop && (
  329. <div
  330. className={`${chatStyle["chat-input-action"]} clickable`}
  331. onClick={stopAll}
  332. >
  333. <StopIcon />
  334. </div>
  335. )}
  336. {!props.hitBottom && (
  337. <div
  338. className={`${chatStyle["chat-input-action"]} clickable`}
  339. onClick={props.scrollToBottom}
  340. >
  341. <BottomIcon />
  342. </div>
  343. )}
  344. {props.hitBottom && (
  345. <div
  346. className={`${chatStyle["chat-input-action"]} clickable`}
  347. onClick={props.showPromptModal}
  348. >
  349. <SettingsIcon />
  350. </div>
  351. )}
  352. <div
  353. className={`${chatStyle["chat-input-action"]} clickable`}
  354. onClick={nextTheme}
  355. >
  356. {theme === Theme.Auto ? (
  357. <AutoIcon />
  358. ) : theme === Theme.Light ? (
  359. <LightIcon />
  360. ) : theme === Theme.Dark ? (
  361. <DarkIcon />
  362. ) : null}
  363. </div>
  364. <div
  365. className={`${chatStyle["chat-input-action"]} clickable`}
  366. onClick={props.showPromptHints}
  367. >
  368. <PromptIcon />
  369. </div>
  370. <div
  371. className={`${chatStyle["chat-input-action"]} clickable`}
  372. onClick={() => {
  373. navigate(Path.Masks);
  374. }}
  375. >
  376. <MaskIcon />
  377. </div>
  378. <div
  379. className={`${chatStyle["chat-input-action"]} clickable`}
  380. onClick={() => {
  381. chatStore.updateCurrentSession((session) => {
  382. if ((session.clearContextIndex ?? -1) > 0) {
  383. session.clearContextIndex = -1;
  384. } else {
  385. session.clearContextIndex = session.messages.length;
  386. session.memoryPrompt = ""; // will clear memory
  387. }
  388. });
  389. }}
  390. >
  391. <BreakIcon />
  392. </div>
  393. </div>
  394. );
  395. }
  396. export function Chat() {
  397. type RenderMessage = ChatMessage & { preview?: boolean };
  398. const chatStore = useChatStore();
  399. const [session, sessionIndex] = useChatStore((state) => [
  400. state.currentSession(),
  401. state.currentSessionIndex,
  402. ]);
  403. const config = useAppConfig();
  404. const fontSize = config.fontSize;
  405. const inputRef = useRef<HTMLTextAreaElement>(null);
  406. const [userInput, setUserInput] = useState("");
  407. const [isLoading, setIsLoading] = useState(false);
  408. const { submitKey, shouldSubmit } = useSubmitHandler();
  409. const { scrollRef, setAutoScroll, scrollToBottom } = useScrollToBottom();
  410. const [hitBottom, setHitBottom] = useState(true);
  411. const isMobileScreen = useMobileScreen();
  412. const navigate = useNavigate();
  413. const onChatBodyScroll = (e: HTMLElement) => {
  414. const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 100;
  415. setHitBottom(isTouchBottom);
  416. };
  417. // prompt hints
  418. const promptStore = usePromptStore();
  419. const [promptHints, setPromptHints] = useState<Prompt[]>([]);
  420. const onSearch = useDebouncedCallback(
  421. (text: string) => {
  422. setPromptHints(promptStore.search(text));
  423. },
  424. 100,
  425. { leading: true, trailing: true },
  426. );
  427. const onPromptSelect = (prompt: Prompt) => {
  428. setPromptHints([]);
  429. inputRef.current?.focus();
  430. setTimeout(() => setUserInput(prompt.content), 60);
  431. };
  432. // auto grow input
  433. const [inputRows, setInputRows] = useState(2);
  434. const measure = useDebouncedCallback(
  435. () => {
  436. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  437. const inputRows = Math.min(
  438. 20,
  439. Math.max(2 + Number(!isMobileScreen), rows),
  440. );
  441. setInputRows(inputRows);
  442. },
  443. 100,
  444. {
  445. leading: true,
  446. trailing: true,
  447. },
  448. );
  449. // eslint-disable-next-line react-hooks/exhaustive-deps
  450. useEffect(measure, [userInput]);
  451. // only search prompts when user input is short
  452. const SEARCH_TEXT_LIMIT = 30;
  453. const onInput = (text: string) => {
  454. setUserInput(text);
  455. const n = text.trim().length;
  456. // clear search results
  457. if (n === 0) {
  458. setPromptHints([]);
  459. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  460. // check if need to trigger auto completion
  461. if (text.startsWith("/")) {
  462. let searchText = text.slice(1);
  463. onSearch(searchText);
  464. }
  465. }
  466. };
  467. const doSubmit = (userInput: string) => {
  468. if (userInput.trim() === "") return;
  469. setIsLoading(true);
  470. chatStore.onUserInput(userInput).then(() => setIsLoading(false));
  471. localStorage.setItem(LAST_INPUT_KEY, userInput);
  472. setUserInput("");
  473. setPromptHints([]);
  474. if (!isMobileScreen) inputRef.current?.focus();
  475. setAutoScroll(true);
  476. };
  477. // stop response
  478. const onUserStop = (messageId: number) => {
  479. ChatControllerPool.stop(sessionIndex, messageId);
  480. };
  481. useEffect(() => {
  482. chatStore.updateCurrentSession((session) => {
  483. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  484. session.messages.forEach((m) => {
  485. // check if should stop all stale messages
  486. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  487. if (m.streaming) {
  488. m.streaming = false;
  489. }
  490. if (m.content.length === 0) {
  491. m.isError = true;
  492. m.content = prettyObject({
  493. error: true,
  494. message: "empty response",
  495. });
  496. }
  497. }
  498. });
  499. // auto sync mask config from global config
  500. if (session.mask.syncGlobalConfig) {
  501. console.log("[Mask] syncing from global, name = ", session.mask.name);
  502. session.mask.modelConfig = { ...config.modelConfig };
  503. }
  504. });
  505. // eslint-disable-next-line react-hooks/exhaustive-deps
  506. }, []);
  507. // check if should send message
  508. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  509. // if ArrowUp and no userInput, fill with last input
  510. if (
  511. e.key === "ArrowUp" &&
  512. userInput.length <= 0 &&
  513. !(e.metaKey || e.altKey || e.ctrlKey)
  514. ) {
  515. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  516. e.preventDefault();
  517. return;
  518. }
  519. if (shouldSubmit(e) && promptHints.length === 0) {
  520. doSubmit(userInput);
  521. e.preventDefault();
  522. }
  523. };
  524. const onRightClick = (e: any, message: ChatMessage) => {
  525. // copy to clipboard
  526. if (selectOrCopy(e.currentTarget, message.content)) {
  527. e.preventDefault();
  528. }
  529. };
  530. const findLastUserIndex = (messageId: number) => {
  531. // find last user input message and resend
  532. let lastUserMessageIndex: number | null = null;
  533. for (let i = 0; i < session.messages.length; i += 1) {
  534. const message = session.messages[i];
  535. if (message.id === messageId) {
  536. break;
  537. }
  538. if (message.role === "user") {
  539. lastUserMessageIndex = i;
  540. }
  541. }
  542. return lastUserMessageIndex;
  543. };
  544. const deleteMessage = (userIndex: number) => {
  545. chatStore.updateCurrentSession((session) =>
  546. session.messages.splice(userIndex, 2),
  547. );
  548. };
  549. const onDelete = (botMessageId: number) => {
  550. const userIndex = findLastUserIndex(botMessageId);
  551. if (userIndex === null) return;
  552. deleteMessage(userIndex);
  553. };
  554. const onResend = (botMessageId: number) => {
  555. // find last user input message and resend
  556. const userIndex = findLastUserIndex(botMessageId);
  557. if (userIndex === null) return;
  558. setIsLoading(true);
  559. const content = session.messages[userIndex].content;
  560. deleteMessage(userIndex);
  561. chatStore.onUserInput(content).then(() => setIsLoading(false));
  562. inputRef.current?.focus();
  563. };
  564. const context: RenderMessage[] = session.mask.hideContext
  565. ? []
  566. : session.mask.context.slice();
  567. const accessStore = useAccessStore();
  568. if (
  569. context.length === 0 &&
  570. session.messages.at(0)?.content !== BOT_HELLO.content
  571. ) {
  572. const copiedHello = Object.assign({}, BOT_HELLO);
  573. if (!accessStore.isAuthorized()) {
  574. copiedHello.content = Locale.Error.Unauthorized;
  575. }
  576. context.push(copiedHello);
  577. }
  578. // clear context index = context length + index in messages
  579. const clearContextIndex =
  580. (session.clearContextIndex ?? -1) >= 0
  581. ? session.clearContextIndex! + context.length
  582. : -1;
  583. // preview messages
  584. const messages = context
  585. .concat(session.messages as RenderMessage[])
  586. .concat(
  587. isLoading
  588. ? [
  589. {
  590. ...createMessage({
  591. role: "assistant",
  592. content: "……",
  593. }),
  594. preview: true,
  595. },
  596. ]
  597. : [],
  598. )
  599. .concat(
  600. userInput.length > 0 && config.sendPreviewBubble
  601. ? [
  602. {
  603. ...createMessage({
  604. role: "user",
  605. content: userInput,
  606. }),
  607. preview: true,
  608. },
  609. ]
  610. : [],
  611. );
  612. const [showPromptModal, setShowPromptModal] = useState(false);
  613. const renameSession = () => {
  614. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  615. if (newTopic && newTopic !== session.topic) {
  616. chatStore.updateCurrentSession((session) => (session.topic = newTopic!));
  617. }
  618. };
  619. const location = useLocation();
  620. const isChat = location.pathname === Path.Chat;
  621. const autoFocus = !isMobileScreen || isChat; // only focus in chat page
  622. useCommand({
  623. fill: setUserInput,
  624. submit: (text) => {
  625. doSubmit(text);
  626. },
  627. });
  628. return (
  629. <div className={styles.chat} key={session.id}>
  630. <div className="window-header">
  631. <div className="window-header-title">
  632. <div
  633. className={`window-header-main-title " ${styles["chat-body-title"]}`}
  634. onClickCapture={renameSession}
  635. >
  636. {!session.topic ? DEFAULT_TOPIC : session.topic}
  637. </div>
  638. <div className="window-header-sub-title">
  639. {Locale.Chat.SubTitle(session.messages.length)}
  640. </div>
  641. </div>
  642. <div className="window-actions">
  643. <div className={"window-action-button" + " " + styles.mobile}>
  644. <IconButton
  645. icon={<ReturnIcon />}
  646. bordered
  647. title={Locale.Chat.Actions.ChatList}
  648. onClick={() => navigate(Path.Home)}
  649. />
  650. </div>
  651. <div className="window-action-button">
  652. <IconButton
  653. icon={<RenameIcon />}
  654. bordered
  655. onClick={renameSession}
  656. />
  657. </div>
  658. <div className="window-action-button">
  659. <IconButton
  660. icon={<ExportIcon />}
  661. bordered
  662. title={Locale.Chat.Actions.Export}
  663. onClick={() => {
  664. exportMessages(
  665. session.messages.filter((msg) => !msg.isError),
  666. session.topic,
  667. );
  668. }}
  669. />
  670. </div>
  671. {!isMobileScreen && (
  672. <div className="window-action-button">
  673. <IconButton
  674. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  675. bordered
  676. onClick={() => {
  677. config.update(
  678. (config) => (config.tightBorder = !config.tightBorder),
  679. );
  680. }}
  681. />
  682. </div>
  683. )}
  684. </div>
  685. <PromptToast
  686. showToast={!hitBottom}
  687. showModal={showPromptModal}
  688. setShowModal={setShowPromptModal}
  689. />
  690. </div>
  691. <div
  692. className={styles["chat-body"]}
  693. ref={scrollRef}
  694. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  695. onMouseDown={() => inputRef.current?.blur()}
  696. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  697. onTouchStart={() => {
  698. inputRef.current?.blur();
  699. setAutoScroll(false);
  700. }}
  701. >
  702. {messages.map((message, i) => {
  703. const isUser = message.role === "user";
  704. const showActions =
  705. !isUser &&
  706. i > 0 &&
  707. !(message.preview || message.content.length === 0);
  708. const showTyping = message.preview || message.streaming;
  709. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  710. return (
  711. <>
  712. <div
  713. key={i}
  714. className={
  715. isUser ? styles["chat-message-user"] : styles["chat-message"]
  716. }
  717. >
  718. <div className={styles["chat-message-container"]}>
  719. <div className={styles["chat-message-avatar"]}>
  720. {message.role === "user" ? (
  721. <Avatar avatar={config.avatar} />
  722. ) : (
  723. <MaskAvatar mask={session.mask} />
  724. )}
  725. </div>
  726. {showTyping && (
  727. <div className={styles["chat-message-status"]}>
  728. {Locale.Chat.Typing}
  729. </div>
  730. )}
  731. <div className={styles["chat-message-item"]}>
  732. {showActions && (
  733. <div className={styles["chat-message-top-actions"]}>
  734. {message.streaming ? (
  735. <div
  736. className={styles["chat-message-top-action"]}
  737. onClick={() => onUserStop(message.id ?? i)}
  738. >
  739. {Locale.Chat.Actions.Stop}
  740. </div>
  741. ) : (
  742. <>
  743. <div
  744. className={styles["chat-message-top-action"]}
  745. onClick={() => onDelete(message.id ?? i)}
  746. >
  747. {Locale.Chat.Actions.Delete}
  748. </div>
  749. <div
  750. className={styles["chat-message-top-action"]}
  751. onClick={() => onResend(message.id ?? i)}
  752. >
  753. {Locale.Chat.Actions.Retry}
  754. </div>
  755. </>
  756. )}
  757. <div
  758. className={styles["chat-message-top-action"]}
  759. onClick={() => copyToClipboard(message.content)}
  760. >
  761. {Locale.Chat.Actions.Copy}
  762. </div>
  763. </div>
  764. )}
  765. <Markdown
  766. content={message.content}
  767. loading={
  768. (message.preview || message.content.length === 0) &&
  769. !isUser
  770. }
  771. onContextMenu={(e) => onRightClick(e, message)}
  772. onDoubleClickCapture={() => {
  773. if (!isMobileScreen) return;
  774. setUserInput(message.content);
  775. }}
  776. fontSize={fontSize}
  777. parentRef={scrollRef}
  778. defaultShow={i >= messages.length - 10}
  779. />
  780. </div>
  781. {!isUser && !message.preview && (
  782. <div className={styles["chat-message-actions"]}>
  783. <div className={styles["chat-message-action-date"]}>
  784. {message.date.toLocaleString()}
  785. </div>
  786. </div>
  787. )}
  788. </div>
  789. </div>
  790. {shouldShowClearContextDivider && <ClearContextDivider />}
  791. </>
  792. );
  793. })}
  794. </div>
  795. <div className={styles["chat-input-panel"]}>
  796. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  797. <ChatActions
  798. showPromptModal={() => setShowPromptModal(true)}
  799. scrollToBottom={scrollToBottom}
  800. hitBottom={hitBottom}
  801. showPromptHints={() => {
  802. // Click again to close
  803. if (promptHints.length > 0) {
  804. setPromptHints([]);
  805. return;
  806. }
  807. inputRef.current?.focus();
  808. setUserInput("/");
  809. onSearch("");
  810. }}
  811. />
  812. <div className={styles["chat-input-panel-inner"]}>
  813. <textarea
  814. ref={inputRef}
  815. className={styles["chat-input"]}
  816. placeholder={Locale.Chat.Input(submitKey)}
  817. onInput={(e) => onInput(e.currentTarget.value)}
  818. value={userInput}
  819. onKeyDown={onInputKeyDown}
  820. onFocus={() => setAutoScroll(true)}
  821. onBlur={() => setAutoScroll(false)}
  822. rows={inputRows}
  823. autoFocus={autoFocus}
  824. />
  825. <IconButton
  826. icon={<SendWhiteIcon />}
  827. text={Locale.Chat.Send}
  828. className={styles["chat-input-send"]}
  829. type="primary"
  830. onClick={() => doSubmit(userInput)}
  831. />
  832. </div>
  833. </div>
  834. </div>
  835. );
  836. }