chat.tsx 30 KB

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