chat.tsx 32 KB

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