chat.tsx 49 KB

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