chat.tsx 30 KB

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