chat.tsx 36 KB

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