chat.tsx 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. setTimeout(updateWidth, 100);
  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 === null) 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. {isMobileScreen && (
  717. <div className="window-actions">
  718. <div className={"window-action-button"}>
  719. <IconButton
  720. icon={<ReturnIcon />}
  721. bordered
  722. title={Locale.Chat.Actions.ChatList}
  723. onClick={() => navigate(Path.Home)}
  724. />
  725. </div>
  726. </div>
  727. )}
  728. <div className={`window-header-title ${styles["chat-body-title"]}`}>
  729. <div
  730. className={`window-header-main-title ${styles["chat-body-main-title"]}`}
  731. onClickCapture={renameSession}
  732. >
  733. {!session.topic ? DEFAULT_TOPIC : session.topic}
  734. </div>
  735. <div className="window-header-sub-title">
  736. {Locale.Chat.SubTitle(session.messages.length)}
  737. </div>
  738. </div>
  739. <div className="window-actions">
  740. {!isMobileScreen && (
  741. <div className="window-action-button">
  742. <IconButton
  743. icon={<RenameIcon />}
  744. bordered
  745. onClick={renameSession}
  746. />
  747. </div>
  748. )}
  749. <div className="window-action-button">
  750. <IconButton
  751. icon={<ExportIcon />}
  752. bordered
  753. title={Locale.Chat.Actions.Export}
  754. onClick={() => {
  755. setShowExport(true);
  756. }}
  757. />
  758. </div>
  759. {showMaxIcon && (
  760. <div className="window-action-button">
  761. <IconButton
  762. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  763. bordered
  764. onClick={() => {
  765. config.update(
  766. (config) => (config.tightBorder = !config.tightBorder),
  767. );
  768. }}
  769. />
  770. </div>
  771. )}
  772. </div>
  773. <PromptToast
  774. showToast={!hitBottom}
  775. showModal={showPromptModal}
  776. setShowModal={setShowPromptModal}
  777. />
  778. </div>
  779. <div
  780. className={styles["chat-body"]}
  781. ref={scrollRef}
  782. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  783. onMouseDown={() => inputRef.current?.blur()}
  784. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  785. onTouchStart={() => {
  786. inputRef.current?.blur();
  787. setAutoScroll(false);
  788. }}
  789. >
  790. {messages.map((message, i) => {
  791. const isUser = message.role === "user";
  792. const showActions =
  793. !isUser &&
  794. i > 0 &&
  795. !(message.preview || message.content.length === 0);
  796. const showTyping = message.preview || message.streaming;
  797. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  798. return (
  799. <>
  800. <div
  801. key={i}
  802. className={
  803. isUser ? styles["chat-message-user"] : styles["chat-message"]
  804. }
  805. >
  806. <div className={styles["chat-message-container"]}>
  807. <div className={styles["chat-message-avatar"]}>
  808. {message.role === "user" ? (
  809. <Avatar avatar={config.avatar} />
  810. ) : (
  811. <MaskAvatar mask={session.mask} />
  812. )}
  813. </div>
  814. {showTyping && (
  815. <div className={styles["chat-message-status"]}>
  816. {Locale.Chat.Typing}
  817. </div>
  818. )}
  819. <div className={styles["chat-message-item"]}>
  820. <Markdown
  821. content={message.content}
  822. loading={
  823. (message.preview || message.content.length === 0) &&
  824. !isUser
  825. }
  826. onContextMenu={(e) => onRightClick(e, message)}
  827. onDoubleClickCapture={() => {
  828. if (!isMobileScreen) return;
  829. setUserInput(message.content);
  830. }}
  831. fontSize={fontSize}
  832. parentRef={scrollRef}
  833. defaultShow={i >= messages.length - 10}
  834. />
  835. {showActions && (
  836. <div className={styles["chat-message-actions"]}>
  837. <div
  838. className={styles["chat-input-actions"]}
  839. style={{
  840. marginTop: 10,
  841. marginBottom: 0,
  842. }}
  843. >
  844. {message.streaming ? (
  845. <ChatAction
  846. text={Locale.Chat.Actions.Stop}
  847. icon={<StopIcon />}
  848. onClick={() => onUserStop(message.id ?? i)}
  849. />
  850. ) : (
  851. <>
  852. <ChatAction
  853. text={Locale.Chat.Actions.Retry}
  854. icon={<ResetIcon />}
  855. onClick={() => onResend(message.id ?? i)}
  856. />
  857. <ChatAction
  858. text={Locale.Chat.Actions.Delete}
  859. icon={<DeleteIcon />}
  860. onClick={() => onDelete(message.id ?? i)}
  861. />
  862. <ChatAction
  863. text={Locale.Chat.Actions.Pin}
  864. icon={<PinIcon />}
  865. onClick={() => onPinMessage(message)}
  866. />
  867. <ChatAction
  868. text={Locale.Chat.Actions.Copy}
  869. icon={<CopyIcon />}
  870. onClick={() => copyToClipboard(message.content)}
  871. />
  872. </>
  873. )}
  874. </div>
  875. <div className={styles["chat-message-action-date"]}>
  876. {message.date.toLocaleString()}
  877. </div>
  878. </div>
  879. )}
  880. </div>
  881. </div>
  882. </div>
  883. {shouldShowClearContextDivider && <ClearContextDivider />}
  884. </>
  885. );
  886. })}
  887. </div>
  888. <div className={styles["chat-input-panel"]}>
  889. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  890. <ChatActions
  891. showPromptModal={() => setShowPromptModal(true)}
  892. scrollToBottom={scrollToBottom}
  893. hitBottom={hitBottom}
  894. showPromptHints={() => {
  895. // Click again to close
  896. if (promptHints.length > 0) {
  897. setPromptHints([]);
  898. return;
  899. }
  900. inputRef.current?.focus();
  901. setUserInput("/");
  902. onSearch("");
  903. }}
  904. />
  905. <div className={styles["chat-input-panel-inner"]}>
  906. <textarea
  907. ref={inputRef}
  908. className={styles["chat-input"]}
  909. placeholder={Locale.Chat.Input(submitKey)}
  910. onInput={(e) => onInput(e.currentTarget.value)}
  911. value={userInput}
  912. onKeyDown={onInputKeyDown}
  913. onFocus={() => setAutoScroll(true)}
  914. onBlur={() => setAutoScroll(false)}
  915. rows={inputRows}
  916. autoFocus={autoFocus}
  917. style={{
  918. fontSize: config.fontSize,
  919. }}
  920. />
  921. <IconButton
  922. icon={<SendWhiteIcon />}
  923. text={Locale.Chat.Send}
  924. className={styles["chat-input-send"]}
  925. type="primary"
  926. onClick={() => doSubmit(userInput)}
  927. />
  928. </div>
  929. </div>
  930. {showExport && (
  931. <ExportMessageModal onClose={() => setShowExport(false)} />
  932. )}
  933. </div>
  934. );
  935. }