chat.tsx 27 KB

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