chat.tsx 49 KB

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