chat.tsx 27 KB

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