chat.tsx 31 KB

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