chat.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. import { useDebouncedCallback } from "use-debounce";
  2. import React, {
  3. useState,
  4. useRef,
  5. useEffect,
  6. useLayoutEffect,
  7. useMemo,
  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 = () => {
  315. const dom = scrollRef.current;
  316. if (dom) {
  317. setTimeout(() => (dom.scrollTop = dom.scrollHeight), 1);
  318. }
  319. };
  320. // auto scroll
  321. useLayoutEffect(() => {
  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. e.preventDefault();
  552. }
  553. };
  554. const findLastUserIndex = (messageId: number) => {
  555. // find last user input message and resend
  556. let lastUserMessageIndex: number | null = null;
  557. for (let i = 0; i < session.messages.length; i += 1) {
  558. const message = session.messages[i];
  559. if (message.id === messageId) {
  560. break;
  561. }
  562. if (message.role === "user") {
  563. lastUserMessageIndex = i;
  564. }
  565. }
  566. return lastUserMessageIndex;
  567. };
  568. const deleteMessage = (userIndex: number) => {
  569. chatStore.updateCurrentSession((session) =>
  570. session.messages.splice(userIndex, 2),
  571. );
  572. };
  573. const onDelete = (botMessageId: number) => {
  574. const userIndex = findLastUserIndex(botMessageId);
  575. if (userIndex === null) return;
  576. deleteMessage(userIndex);
  577. };
  578. const onResend = (botMessageId: number) => {
  579. // find last user input message and resend
  580. const userIndex = findLastUserIndex(botMessageId);
  581. if (userIndex === null) return;
  582. setIsLoading(true);
  583. const content = session.messages[userIndex].content;
  584. deleteMessage(userIndex);
  585. chatStore.onUserInput(content).then(() => setIsLoading(false));
  586. inputRef.current?.focus();
  587. };
  588. const context: RenderMessage[] = session.mask.hideContext
  589. ? []
  590. : session.mask.context.slice();
  591. const accessStore = useAccessStore();
  592. if (
  593. context.length === 0 &&
  594. session.messages.at(0)?.content !== BOT_HELLO.content
  595. ) {
  596. const copiedHello = Object.assign({}, BOT_HELLO);
  597. if (!accessStore.isAuthorized()) {
  598. copiedHello.content = Locale.Error.Unauthorized;
  599. }
  600. context.push(copiedHello);
  601. }
  602. // clear context index = context length + index in messages
  603. const clearContextIndex =
  604. (session.clearContextIndex ?? -1) >= 0
  605. ? session.clearContextIndex! + context.length
  606. : -1;
  607. // preview messages
  608. const messages = context
  609. .concat(session.messages as RenderMessage[])
  610. .concat(
  611. isLoading
  612. ? [
  613. {
  614. ...createMessage({
  615. role: "assistant",
  616. content: "……",
  617. }),
  618. preview: true,
  619. },
  620. ]
  621. : [],
  622. )
  623. .concat(
  624. userInput.length > 0 && config.sendPreviewBubble
  625. ? [
  626. {
  627. ...createMessage({
  628. role: "user",
  629. content: userInput,
  630. }),
  631. preview: true,
  632. },
  633. ]
  634. : [],
  635. );
  636. const [showPromptModal, setShowPromptModal] = useState(false);
  637. const renameSession = () => {
  638. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  639. if (newTopic && newTopic !== session.topic) {
  640. chatStore.updateCurrentSession((session) => (session.topic = newTopic!));
  641. }
  642. };
  643. const clientConfig = useMemo(() => getClientConfig(), []);
  644. const location = useLocation();
  645. const isChat = location.pathname === Path.Chat;
  646. const autoFocus = !isMobileScreen || isChat; // only focus in chat page
  647. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  648. useCommand({
  649. fill: setUserInput,
  650. submit: (text) => {
  651. doSubmit(text);
  652. },
  653. });
  654. return (
  655. <div className={styles.chat} key={session.id}>
  656. <div className="window-header" data-tauri-drag-region>
  657. <div className="window-header-title">
  658. <div
  659. className={`window-header-main-title " ${styles["chat-body-title"]}`}
  660. onClickCapture={renameSession}
  661. >
  662. {!session.topic ? DEFAULT_TOPIC : session.topic}
  663. </div>
  664. <div className="window-header-sub-title">
  665. {Locale.Chat.SubTitle(session.messages.length)}
  666. </div>
  667. </div>
  668. <div className="window-actions">
  669. <div className={"window-action-button" + " " + styles.mobile}>
  670. <IconButton
  671. icon={<ReturnIcon />}
  672. bordered
  673. title={Locale.Chat.Actions.ChatList}
  674. onClick={() => navigate(Path.Home)}
  675. />
  676. </div>
  677. <div className="window-action-button">
  678. <IconButton
  679. icon={<RenameIcon />}
  680. bordered
  681. onClick={renameSession}
  682. />
  683. </div>
  684. <div className="window-action-button">
  685. <IconButton
  686. icon={<ExportIcon />}
  687. bordered
  688. title={Locale.Chat.Actions.Export}
  689. onClick={() => {
  690. setShowExport(true);
  691. }}
  692. />
  693. </div>
  694. {showMaxIcon && (
  695. <div className="window-action-button">
  696. <IconButton
  697. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  698. bordered
  699. onClick={() => {
  700. config.update(
  701. (config) => (config.tightBorder = !config.tightBorder),
  702. );
  703. }}
  704. />
  705. </div>
  706. )}
  707. </div>
  708. <PromptToast
  709. showToast={!hitBottom}
  710. showModal={showPromptModal}
  711. setShowModal={setShowPromptModal}
  712. />
  713. </div>
  714. <div
  715. className={styles["chat-body"]}
  716. ref={scrollRef}
  717. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  718. onMouseDown={() => inputRef.current?.blur()}
  719. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  720. onTouchStart={() => {
  721. inputRef.current?.blur();
  722. setAutoScroll(false);
  723. }}
  724. >
  725. {messages.map((message, i) => {
  726. const isUser = message.role === "user";
  727. const showActions =
  728. !isUser &&
  729. i > 0 &&
  730. !(message.preview || message.content.length === 0);
  731. const showTyping = message.preview || message.streaming;
  732. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  733. return (
  734. <>
  735. <div
  736. key={i}
  737. className={
  738. isUser ? styles["chat-message-user"] : styles["chat-message"]
  739. }
  740. >
  741. <div className={styles["chat-message-container"]}>
  742. <div className={styles["chat-message-avatar"]}>
  743. {message.role === "user" ? (
  744. <Avatar avatar={config.avatar} />
  745. ) : (
  746. <MaskAvatar mask={session.mask} />
  747. )}
  748. </div>
  749. {showTyping && (
  750. <div className={styles["chat-message-status"]}>
  751. {Locale.Chat.Typing}
  752. </div>
  753. )}
  754. <div className={styles["chat-message-item"]}>
  755. {showActions && (
  756. <div className={styles["chat-message-top-actions"]}>
  757. {message.streaming ? (
  758. <div
  759. className={styles["chat-message-top-action"]}
  760. onClick={() => onUserStop(message.id ?? i)}
  761. >
  762. {Locale.Chat.Actions.Stop}
  763. </div>
  764. ) : (
  765. <>
  766. <div
  767. className={styles["chat-message-top-action"]}
  768. onClick={() => onDelete(message.id ?? i)}
  769. >
  770. {Locale.Chat.Actions.Delete}
  771. </div>
  772. <div
  773. className={styles["chat-message-top-action"]}
  774. onClick={() => onResend(message.id ?? i)}
  775. >
  776. {Locale.Chat.Actions.Retry}
  777. </div>
  778. </>
  779. )}
  780. <div
  781. className={styles["chat-message-top-action"]}
  782. onClick={() => copyToClipboard(message.content)}
  783. >
  784. {Locale.Chat.Actions.Copy}
  785. </div>
  786. </div>
  787. )}
  788. <Markdown
  789. content={message.content}
  790. loading={
  791. (message.preview || message.content.length === 0) &&
  792. !isUser
  793. }
  794. onContextMenu={(e) => onRightClick(e, message)}
  795. onDoubleClickCapture={() => {
  796. if (!isMobileScreen) return;
  797. setUserInput(message.content);
  798. }}
  799. fontSize={fontSize}
  800. parentRef={scrollRef}
  801. defaultShow={i >= messages.length - 10}
  802. />
  803. </div>
  804. {!isUser && !message.preview && (
  805. <div className={styles["chat-message-actions"]}>
  806. <div className={styles["chat-message-action-date"]}>
  807. {message.date.toLocaleString()}
  808. </div>
  809. </div>
  810. )}
  811. </div>
  812. </div>
  813. {shouldShowClearContextDivider && <ClearContextDivider />}
  814. </>
  815. );
  816. })}
  817. </div>
  818. <div className={styles["chat-input-panel"]}>
  819. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  820. <ChatActions
  821. showPromptModal={() => setShowPromptModal(true)}
  822. scrollToBottom={scrollToBottom}
  823. hitBottom={hitBottom}
  824. showPromptHints={() => {
  825. // Click again to close
  826. if (promptHints.length > 0) {
  827. setPromptHints([]);
  828. return;
  829. }
  830. inputRef.current?.focus();
  831. setUserInput("/");
  832. onSearch("");
  833. }}
  834. />
  835. <div className={styles["chat-input-panel-inner"]}>
  836. <textarea
  837. ref={inputRef}
  838. className={styles["chat-input"]}
  839. placeholder={Locale.Chat.Input(submitKey)}
  840. onInput={(e) => onInput(e.currentTarget.value)}
  841. value={userInput}
  842. onKeyDown={onInputKeyDown}
  843. onFocus={() => setAutoScroll(true)}
  844. onBlur={() => setAutoScroll(false)}
  845. rows={inputRows}
  846. autoFocus={autoFocus}
  847. style={{
  848. fontSize: config.fontSize,
  849. }}
  850. />
  851. <IconButton
  852. icon={<SendWhiteIcon />}
  853. text={Locale.Chat.Send}
  854. className={styles["chat-input-send"]}
  855. type="primary"
  856. onClick={() => doSubmit(userInput)}
  857. />
  858. </div>
  859. </div>
  860. {showExport && (
  861. <ExportMessageModal onClose={() => setShowExport(false)} />
  862. )}
  863. </div>
  864. );
  865. }