chat.tsx 45 KB

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