chat.tsx 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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: 16,
  272. icon: 16,
  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. const onClick = () => setTimeout(updateWidth, 10);
  286. onClick();
  287. window.addEventListener("click", onClick);
  288. return () => {
  289. window.removeEventListener("click", onClick);
  290. };
  291. }, []);
  292. return (
  293. <div
  294. className={`${styles["chat-input-action"]} clickable`}
  295. onClick={() => {
  296. props.onClick();
  297. setTimeout(updateWidth, 1);
  298. }}
  299. style={
  300. {
  301. "--icon-width": `${width.icon}px`,
  302. "--full-width": `${width.full}px`,
  303. } as React.CSSProperties
  304. }
  305. >
  306. <div ref={iconRef} className={styles["icon"]}>
  307. {props.icon}
  308. </div>
  309. <div className={styles["text"]} ref={textRef}>
  310. {props.text}
  311. </div>
  312. </div>
  313. );
  314. }
  315. function useScrollToBottom() {
  316. // for auto-scroll
  317. const scrollRef = useRef<HTMLDivElement>(null);
  318. const [autoScroll, setAutoScroll] = useState(true);
  319. const scrollToBottom = useCallback(() => {
  320. const dom = scrollRef.current;
  321. if (dom) {
  322. requestAnimationFrame(() => dom.scrollTo(0, dom.scrollHeight));
  323. }
  324. }, []);
  325. // auto scroll
  326. useEffect(() => {
  327. autoScroll && scrollToBottom();
  328. });
  329. return {
  330. scrollRef,
  331. autoScroll,
  332. setAutoScroll,
  333. scrollToBottom,
  334. };
  335. }
  336. export function ChatActions(props: {
  337. showPromptModal: () => void;
  338. scrollToBottom: () => void;
  339. showPromptHints: () => void;
  340. hitBottom: boolean;
  341. }) {
  342. const config = useAppConfig();
  343. const navigate = useNavigate();
  344. const chatStore = useChatStore();
  345. // switch themes
  346. const theme = config.theme;
  347. function nextTheme() {
  348. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  349. const themeIndex = themes.indexOf(theme);
  350. const nextIndex = (themeIndex + 1) % themes.length;
  351. const nextTheme = themes[nextIndex];
  352. config.update((config) => (config.theme = nextTheme));
  353. }
  354. // stop all responses
  355. const couldStop = ChatControllerPool.hasPending();
  356. const stopAll = () => ChatControllerPool.stopAll();
  357. // switch model
  358. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  359. function nextModel() {
  360. const models = ALL_MODELS.filter((m) => m.available).map((m) => m.name);
  361. const modelIndex = models.indexOf(currentModel);
  362. const nextIndex = (modelIndex + 1) % models.length;
  363. const nextModel = models[nextIndex];
  364. chatStore.updateCurrentSession((session) => {
  365. session.mask.modelConfig.model = nextModel;
  366. session.mask.syncGlobalConfig = false;
  367. });
  368. }
  369. return (
  370. <div className={styles["chat-input-actions"]}>
  371. {couldStop && (
  372. <ChatAction
  373. onClick={stopAll}
  374. text={Locale.Chat.InputActions.Stop}
  375. icon={<StopIcon />}
  376. />
  377. )}
  378. {!props.hitBottom && (
  379. <ChatAction
  380. onClick={props.scrollToBottom}
  381. text={Locale.Chat.InputActions.ToBottom}
  382. icon={<BottomIcon />}
  383. />
  384. )}
  385. {props.hitBottom && (
  386. <ChatAction
  387. onClick={props.showPromptModal}
  388. text={Locale.Chat.InputActions.Settings}
  389. icon={<SettingsIcon />}
  390. />
  391. )}
  392. <ChatAction
  393. onClick={nextTheme}
  394. text={Locale.Chat.InputActions.Theme[theme]}
  395. icon={
  396. <>
  397. {theme === Theme.Auto ? (
  398. <AutoIcon />
  399. ) : theme === Theme.Light ? (
  400. <LightIcon />
  401. ) : theme === Theme.Dark ? (
  402. <DarkIcon />
  403. ) : null}
  404. </>
  405. }
  406. />
  407. <ChatAction
  408. onClick={props.showPromptHints}
  409. text={Locale.Chat.InputActions.Prompt}
  410. icon={<PromptIcon />}
  411. />
  412. <ChatAction
  413. onClick={() => {
  414. navigate(Path.Masks);
  415. }}
  416. text={Locale.Chat.InputActions.Masks}
  417. icon={<MaskIcon />}
  418. />
  419. <ChatAction
  420. text={Locale.Chat.InputActions.Clear}
  421. icon={<BreakIcon />}
  422. onClick={() => {
  423. chatStore.updateCurrentSession((session) => {
  424. if (session.clearContextIndex === session.messages.length) {
  425. session.clearContextIndex = undefined;
  426. } else {
  427. session.clearContextIndex = session.messages.length;
  428. session.memoryPrompt = ""; // will clear memory
  429. }
  430. });
  431. }}
  432. />
  433. <ChatAction
  434. onClick={nextModel}
  435. text={currentModel}
  436. icon={<RobotIcon />}
  437. />
  438. </div>
  439. );
  440. }
  441. export function Chat() {
  442. type RenderMessage = ChatMessage & { preview?: boolean };
  443. const chatStore = useChatStore();
  444. const [session, sessionIndex] = useChatStore((state) => [
  445. state.currentSession(),
  446. state.currentSessionIndex,
  447. ]);
  448. const config = useAppConfig();
  449. const fontSize = config.fontSize;
  450. const [showExport, setShowExport] = useState(false);
  451. const inputRef = useRef<HTMLTextAreaElement>(null);
  452. const [userInput, setUserInput] = useState("");
  453. const [isLoading, setIsLoading] = useState(false);
  454. const { submitKey, shouldSubmit } = useSubmitHandler();
  455. const { scrollRef, setAutoScroll, scrollToBottom } = useScrollToBottom();
  456. const [hitBottom, setHitBottom] = useState(true);
  457. const isMobileScreen = useMobileScreen();
  458. const navigate = useNavigate();
  459. const onChatBodyScroll = (e: HTMLElement) => {
  460. const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 10;
  461. setHitBottom(isTouchBottom);
  462. };
  463. // prompt hints
  464. const promptStore = usePromptStore();
  465. const [promptHints, setPromptHints] = useState<Prompt[]>([]);
  466. const onSearch = useDebouncedCallback(
  467. (text: string) => {
  468. const matchedPrompts = promptStore.search(text);
  469. setPromptHints(matchedPrompts);
  470. },
  471. 100,
  472. { leading: true, trailing: true },
  473. );
  474. // auto grow input
  475. const [inputRows, setInputRows] = useState(2);
  476. const measure = useDebouncedCallback(
  477. () => {
  478. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  479. const inputRows = Math.min(
  480. 20,
  481. Math.max(2 + Number(!isMobileScreen), rows),
  482. );
  483. setInputRows(inputRows);
  484. },
  485. 100,
  486. {
  487. leading: true,
  488. trailing: true,
  489. },
  490. );
  491. // eslint-disable-next-line react-hooks/exhaustive-deps
  492. useEffect(measure, [userInput]);
  493. // chat commands shortcuts
  494. const chatCommands = useChatCommand({
  495. new: () => chatStore.newSession(),
  496. newm: () => navigate(Path.NewChat),
  497. prev: () => chatStore.nextSession(-1),
  498. next: () => chatStore.nextSession(1),
  499. clear: () =>
  500. chatStore.updateCurrentSession(
  501. (session) => (session.clearContextIndex = session.messages.length),
  502. ),
  503. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  504. });
  505. // only search prompts when user input is short
  506. const SEARCH_TEXT_LIMIT = 30;
  507. const onInput = (text: string) => {
  508. setUserInput(text);
  509. const n = text.trim().length;
  510. // clear search results
  511. if (n === 0) {
  512. setPromptHints([]);
  513. } else if (text.startsWith(ChatCommandPrefix)) {
  514. setPromptHints(chatCommands.search(text));
  515. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  516. // check if need to trigger auto completion
  517. if (text.startsWith("/")) {
  518. let searchText = text.slice(1);
  519. onSearch(searchText);
  520. }
  521. }
  522. };
  523. const doSubmit = (userInput: string) => {
  524. if (userInput.trim() === "") return;
  525. const matchCommand = chatCommands.match(userInput);
  526. if (matchCommand.matched) {
  527. setUserInput("");
  528. setPromptHints([]);
  529. matchCommand.invoke();
  530. return;
  531. }
  532. setIsLoading(true);
  533. chatStore.onUserInput(userInput).then(() => setIsLoading(false));
  534. localStorage.setItem(LAST_INPUT_KEY, userInput);
  535. setUserInput("");
  536. setPromptHints([]);
  537. if (!isMobileScreen) inputRef.current?.focus();
  538. setAutoScroll(true);
  539. };
  540. const onPromptSelect = (prompt: Prompt) => {
  541. setTimeout(() => {
  542. setPromptHints([]);
  543. const matchedChatCommand = chatCommands.match(prompt.content);
  544. if (matchedChatCommand.matched) {
  545. // if user is selecting a chat command, just trigger it
  546. matchedChatCommand.invoke();
  547. setUserInput("");
  548. } else {
  549. // or fill the prompt
  550. setUserInput(prompt.content);
  551. }
  552. inputRef.current?.focus();
  553. }, 30);
  554. };
  555. // stop response
  556. const onUserStop = (messageId: number) => {
  557. ChatControllerPool.stop(sessionIndex, messageId);
  558. };
  559. useEffect(() => {
  560. chatStore.updateCurrentSession((session) => {
  561. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  562. session.messages.forEach((m) => {
  563. // check if should stop all stale messages
  564. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  565. if (m.streaming) {
  566. m.streaming = false;
  567. }
  568. if (m.content.length === 0) {
  569. m.isError = true;
  570. m.content = prettyObject({
  571. error: true,
  572. message: "empty response",
  573. });
  574. }
  575. }
  576. });
  577. // auto sync mask config from global config
  578. if (session.mask.syncGlobalConfig) {
  579. console.log("[Mask] syncing from global, name = ", session.mask.name);
  580. session.mask.modelConfig = { ...config.modelConfig };
  581. }
  582. });
  583. // eslint-disable-next-line react-hooks/exhaustive-deps
  584. }, []);
  585. // check if should send message
  586. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  587. // if ArrowUp and no userInput, fill with last input
  588. if (
  589. e.key === "ArrowUp" &&
  590. userInput.length <= 0 &&
  591. !(e.metaKey || e.altKey || e.ctrlKey)
  592. ) {
  593. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  594. e.preventDefault();
  595. return;
  596. }
  597. if (shouldSubmit(e) && promptHints.length === 0) {
  598. doSubmit(userInput);
  599. e.preventDefault();
  600. }
  601. };
  602. const onRightClick = (e: any, message: ChatMessage) => {
  603. // copy to clipboard
  604. if (selectOrCopy(e.currentTarget, message.content)) {
  605. if (userInput.length === 0) {
  606. setUserInput(message.content);
  607. }
  608. e.preventDefault();
  609. }
  610. };
  611. const findLastUserIndex = (messageId: number) => {
  612. // find last user input message and resend
  613. let lastUserMessageIndex: number | null = null;
  614. for (let i = 0; i < session.messages.length; i += 1) {
  615. const message = session.messages[i];
  616. if (message.id === messageId) {
  617. break;
  618. }
  619. if (message.role === "user") {
  620. lastUserMessageIndex = i;
  621. }
  622. }
  623. return lastUserMessageIndex;
  624. };
  625. const deleteMessage = (userIndex: number) => {
  626. chatStore.updateCurrentSession((session) =>
  627. session.messages.splice(userIndex, 2),
  628. );
  629. };
  630. const onDelete = (botMessageId: number) => {
  631. const userIndex = findLastUserIndex(botMessageId);
  632. if (userIndex === null) return;
  633. deleteMessage(userIndex);
  634. };
  635. const onResend = (botMessageId: number) => {
  636. // find last user input message and resend
  637. const userIndex = findLastUserIndex(botMessageId);
  638. if (userIndex === null) return;
  639. setIsLoading(true);
  640. const content = session.messages[userIndex].content;
  641. deleteMessage(userIndex);
  642. chatStore.onUserInput(content).then(() => setIsLoading(false));
  643. inputRef.current?.focus();
  644. };
  645. const onPinMessage = (botMessage: ChatMessage) => {
  646. if (!botMessage.id) return;
  647. const userMessageIndex = findLastUserIndex(botMessage.id);
  648. if (userMessageIndex === null) return;
  649. const userMessage = session.messages[userMessageIndex];
  650. chatStore.updateCurrentSession((session) =>
  651. session.mask.context.push(userMessage, botMessage),
  652. );
  653. showToast(Locale.Chat.Actions.PinToastContent, {
  654. text: Locale.Chat.Actions.PinToastAction,
  655. onClick: () => {
  656. setShowPromptModal(true);
  657. },
  658. });
  659. };
  660. const context: RenderMessage[] = session.mask.hideContext
  661. ? []
  662. : session.mask.context.slice();
  663. const accessStore = useAccessStore();
  664. if (
  665. context.length === 0 &&
  666. session.messages.at(0)?.content !== BOT_HELLO.content
  667. ) {
  668. const copiedHello = Object.assign({}, BOT_HELLO);
  669. if (!accessStore.isAuthorized()) {
  670. copiedHello.content = Locale.Error.Unauthorized;
  671. }
  672. context.push(copiedHello);
  673. }
  674. // clear context index = context length + index in messages
  675. const clearContextIndex =
  676. (session.clearContextIndex ?? -1) >= 0
  677. ? session.clearContextIndex! + context.length
  678. : -1;
  679. // preview messages
  680. const messages = context
  681. .concat(session.messages as RenderMessage[])
  682. .concat(
  683. isLoading
  684. ? [
  685. {
  686. ...createMessage({
  687. role: "assistant",
  688. content: "……",
  689. }),
  690. preview: true,
  691. },
  692. ]
  693. : [],
  694. )
  695. .concat(
  696. userInput.length > 0 && config.sendPreviewBubble
  697. ? [
  698. {
  699. ...createMessage({
  700. role: "user",
  701. content: userInput,
  702. }),
  703. preview: true,
  704. },
  705. ]
  706. : [],
  707. );
  708. const [showPromptModal, setShowPromptModal] = useState(false);
  709. const renameSession = () => {
  710. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  711. if (newTopic && newTopic !== session.topic) {
  712. chatStore.updateCurrentSession((session) => (session.topic = newTopic!));
  713. }
  714. };
  715. const clientConfig = useMemo(() => getClientConfig(), []);
  716. const location = useLocation();
  717. const isChat = location.pathname === Path.Chat;
  718. const autoFocus = !isMobileScreen || isChat; // only focus in chat page
  719. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  720. useCommand({
  721. fill: setUserInput,
  722. submit: (text) => {
  723. doSubmit(text);
  724. },
  725. });
  726. return (
  727. <div className={styles.chat} key={session.id}>
  728. <div className="window-header" data-tauri-drag-region>
  729. {isMobileScreen && (
  730. <div className="window-actions">
  731. <div className={"window-action-button"}>
  732. <IconButton
  733. icon={<ReturnIcon />}
  734. bordered
  735. title={Locale.Chat.Actions.ChatList}
  736. onClick={() => navigate(Path.Home)}
  737. />
  738. </div>
  739. </div>
  740. )}
  741. <div className={`window-header-title ${styles["chat-body-title"]}`}>
  742. <div
  743. className={`window-header-main-title ${styles["chat-body-main-title"]}`}
  744. onClickCapture={renameSession}
  745. >
  746. {!session.topic ? DEFAULT_TOPIC : session.topic}
  747. </div>
  748. <div className="window-header-sub-title">
  749. {Locale.Chat.SubTitle(session.messages.length)}
  750. </div>
  751. </div>
  752. <div className="window-actions">
  753. {!isMobileScreen && (
  754. <div className="window-action-button">
  755. <IconButton
  756. icon={<RenameIcon />}
  757. bordered
  758. onClick={renameSession}
  759. />
  760. </div>
  761. )}
  762. <div className="window-action-button">
  763. <IconButton
  764. icon={<ExportIcon />}
  765. bordered
  766. title={Locale.Chat.Actions.Export}
  767. onClick={() => {
  768. setShowExport(true);
  769. }}
  770. />
  771. </div>
  772. {showMaxIcon && (
  773. <div className="window-action-button">
  774. <IconButton
  775. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  776. bordered
  777. onClick={() => {
  778. config.update(
  779. (config) => (config.tightBorder = !config.tightBorder),
  780. );
  781. }}
  782. />
  783. </div>
  784. )}
  785. </div>
  786. <PromptToast
  787. showToast={!hitBottom}
  788. showModal={showPromptModal}
  789. setShowModal={setShowPromptModal}
  790. />
  791. </div>
  792. <div
  793. className={styles["chat-body"]}
  794. ref={scrollRef}
  795. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  796. onMouseDown={() => inputRef.current?.blur()}
  797. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  798. onTouchStart={() => {
  799. inputRef.current?.blur();
  800. setAutoScroll(false);
  801. }}
  802. >
  803. {messages.map((message, i) => {
  804. const isUser = message.role === "user";
  805. const showActions =
  806. !isUser &&
  807. i > 0 &&
  808. !(message.preview || message.content.length === 0);
  809. const showTyping = message.preview || message.streaming;
  810. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  811. return (
  812. <>
  813. <div
  814. key={i}
  815. className={
  816. isUser ? styles["chat-message-user"] : styles["chat-message"]
  817. }
  818. >
  819. <div className={styles["chat-message-container"]}>
  820. <div className={styles["chat-message-avatar"]}>
  821. {message.role === "user" ? (
  822. <Avatar avatar={config.avatar} />
  823. ) : (
  824. <MaskAvatar mask={session.mask} />
  825. )}
  826. </div>
  827. {showTyping && (
  828. <div className={styles["chat-message-status"]}>
  829. {Locale.Chat.Typing}
  830. </div>
  831. )}
  832. <div className={styles["chat-message-item"]}>
  833. <Markdown
  834. content={message.content}
  835. loading={
  836. (message.preview || message.content.length === 0) &&
  837. !isUser
  838. }
  839. onContextMenu={(e) => onRightClick(e, message)}
  840. onDoubleClickCapture={() => {
  841. if (!isMobileScreen) return;
  842. setUserInput(message.content);
  843. }}
  844. fontSize={fontSize}
  845. parentRef={scrollRef}
  846. defaultShow={i >= messages.length - 10}
  847. />
  848. {showActions && (
  849. <div className={styles["chat-message-actions"]}>
  850. <div
  851. className={styles["chat-input-actions"]}
  852. style={{
  853. marginTop: 10,
  854. marginBottom: 0,
  855. }}
  856. >
  857. {message.streaming ? (
  858. <ChatAction
  859. text={Locale.Chat.Actions.Stop}
  860. icon={<StopIcon />}
  861. onClick={() => onUserStop(message.id ?? i)}
  862. />
  863. ) : (
  864. <>
  865. <ChatAction
  866. text={Locale.Chat.Actions.Retry}
  867. icon={<ResetIcon />}
  868. onClick={() => onResend(message.id ?? i)}
  869. />
  870. <ChatAction
  871. text={Locale.Chat.Actions.Delete}
  872. icon={<DeleteIcon />}
  873. onClick={() => onDelete(message.id ?? i)}
  874. />
  875. <ChatAction
  876. text={Locale.Chat.Actions.Pin}
  877. icon={<PinIcon />}
  878. onClick={() => onPinMessage(message)}
  879. />
  880. <ChatAction
  881. text={Locale.Chat.Actions.Copy}
  882. icon={<CopyIcon />}
  883. onClick={() => copyToClipboard(message.content)}
  884. />
  885. </>
  886. )}
  887. </div>
  888. <div className={styles["chat-message-action-date"]}>
  889. {message.date.toLocaleString()}
  890. </div>
  891. </div>
  892. )}
  893. </div>
  894. </div>
  895. </div>
  896. {shouldShowClearContextDivider && <ClearContextDivider />}
  897. </>
  898. );
  899. })}
  900. </div>
  901. <div className={styles["chat-input-panel"]}>
  902. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  903. <ChatActions
  904. showPromptModal={() => setShowPromptModal(true)}
  905. scrollToBottom={scrollToBottom}
  906. hitBottom={hitBottom}
  907. showPromptHints={() => {
  908. // Click again to close
  909. if (promptHints.length > 0) {
  910. setPromptHints([]);
  911. return;
  912. }
  913. inputRef.current?.focus();
  914. setUserInput("/");
  915. onSearch("");
  916. }}
  917. />
  918. <div className={styles["chat-input-panel-inner"]}>
  919. <textarea
  920. ref={inputRef}
  921. className={styles["chat-input"]}
  922. placeholder={Locale.Chat.Input(submitKey)}
  923. onInput={(e) => onInput(e.currentTarget.value)}
  924. value={userInput}
  925. onKeyDown={onInputKeyDown}
  926. onFocus={() => setAutoScroll(true)}
  927. onBlur={() => setAutoScroll(false)}
  928. rows={inputRows}
  929. autoFocus={autoFocus}
  930. style={{
  931. fontSize: config.fontSize,
  932. }}
  933. />
  934. <IconButton
  935. icon={<SendWhiteIcon />}
  936. text={Locale.Chat.Send}
  937. className={styles["chat-input-send"]}
  938. type="primary"
  939. onClick={() => doSubmit(userInput)}
  940. />
  941. </div>
  942. </div>
  943. {showExport && (
  944. <ExportMessageModal onClose={() => setShowExport(false)} />
  945. )}
  946. </div>
  947. );
  948. }