chat.tsx 27 KB

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