chat.tsx 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  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.Artifacts,
  587. value: Plugin.Artifacts,
  588. },
  589. ]}
  590. onClose={() => setShowPluginSelector(false)}
  591. onSelection={(s) => {
  592. const plugin = s[0];
  593. chatStore.updateCurrentSession((session) => {
  594. session.mask.plugin = s;
  595. });
  596. if (plugin) {
  597. showToast(plugin);
  598. }
  599. }}
  600. />
  601. )}
  602. </div>
  603. );
  604. }
  605. export function EditMessageModal(props: { onClose: () => void }) {
  606. const chatStore = useChatStore();
  607. const session = chatStore.currentSession();
  608. const [messages, setMessages] = useState(session.messages.slice());
  609. return (
  610. <div className="modal-mask">
  611. <Modal
  612. title={Locale.Chat.EditMessage.Title}
  613. onClose={props.onClose}
  614. actions={[
  615. <IconButton
  616. text={Locale.UI.Cancel}
  617. icon={<CancelIcon />}
  618. key="cancel"
  619. onClick={() => {
  620. props.onClose();
  621. }}
  622. />,
  623. <IconButton
  624. type="primary"
  625. text={Locale.UI.Confirm}
  626. icon={<ConfirmIcon />}
  627. key="ok"
  628. onClick={() => {
  629. chatStore.updateCurrentSession(
  630. (session) => (session.messages = messages),
  631. );
  632. props.onClose();
  633. }}
  634. />,
  635. ]}
  636. >
  637. <List>
  638. <ListItem
  639. title={Locale.Chat.EditMessage.Topic.Title}
  640. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  641. >
  642. <input
  643. type="text"
  644. value={session.topic}
  645. onInput={(e) =>
  646. chatStore.updateCurrentSession(
  647. (session) => (session.topic = e.currentTarget.value),
  648. )
  649. }
  650. ></input>
  651. </ListItem>
  652. </List>
  653. <ContextPrompts
  654. context={messages}
  655. updateContext={(updater) => {
  656. const newMessages = messages.slice();
  657. updater(newMessages);
  658. setMessages(newMessages);
  659. }}
  660. />
  661. </Modal>
  662. </div>
  663. );
  664. }
  665. export function DeleteImageButton(props: { deleteImage: () => void }) {
  666. return (
  667. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  668. <DeleteIcon />
  669. </div>
  670. );
  671. }
  672. function _Chat() {
  673. type RenderMessage = ChatMessage & { preview?: boolean };
  674. const chatStore = useChatStore();
  675. const session = chatStore.currentSession();
  676. const config = useAppConfig();
  677. const fontSize = config.fontSize;
  678. const fontFamily = config.fontFamily;
  679. const [showExport, setShowExport] = useState(false);
  680. const inputRef = useRef<HTMLTextAreaElement>(null);
  681. const [userInput, setUserInput] = useState("");
  682. const [isLoading, setIsLoading] = useState(false);
  683. const { submitKey, shouldSubmit } = useSubmitHandler();
  684. const scrollRef = useRef<HTMLDivElement>(null);
  685. const isScrolledToBottom = scrollRef?.current
  686. ? Math.abs(
  687. scrollRef.current.scrollHeight -
  688. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  689. ) <= 1
  690. : false;
  691. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  692. scrollRef,
  693. isScrolledToBottom,
  694. );
  695. const [hitBottom, setHitBottom] = useState(true);
  696. const isMobileScreen = useMobileScreen();
  697. const navigate = useNavigate();
  698. const [attachImages, setAttachImages] = useState<string[]>([]);
  699. const [uploading, setUploading] = useState(false);
  700. // prompt hints
  701. const promptStore = usePromptStore();
  702. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  703. const onSearch = useDebouncedCallback(
  704. (text: string) => {
  705. const matchedPrompts = promptStore.search(text);
  706. setPromptHints(matchedPrompts);
  707. },
  708. 100,
  709. { leading: true, trailing: true },
  710. );
  711. // auto grow input
  712. const [inputRows, setInputRows] = useState(2);
  713. const measure = useDebouncedCallback(
  714. () => {
  715. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  716. const inputRows = Math.min(
  717. 20,
  718. Math.max(2 + Number(!isMobileScreen), rows),
  719. );
  720. setInputRows(inputRows);
  721. },
  722. 100,
  723. {
  724. leading: true,
  725. trailing: true,
  726. },
  727. );
  728. // eslint-disable-next-line react-hooks/exhaustive-deps
  729. useEffect(measure, [userInput]);
  730. // chat commands shortcuts
  731. const chatCommands = useChatCommand({
  732. new: () => chatStore.newSession(),
  733. newm: () => navigate(Path.NewChat),
  734. prev: () => chatStore.nextSession(-1),
  735. next: () => chatStore.nextSession(1),
  736. clear: () =>
  737. chatStore.updateCurrentSession(
  738. (session) => (session.clearContextIndex = session.messages.length),
  739. ),
  740. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  741. });
  742. // only search prompts when user input is short
  743. const SEARCH_TEXT_LIMIT = 30;
  744. const onInput = (text: string) => {
  745. setUserInput(text);
  746. const n = text.trim().length;
  747. // clear search results
  748. if (n === 0) {
  749. setPromptHints([]);
  750. } else if (text.match(ChatCommandPrefix)) {
  751. setPromptHints(chatCommands.search(text));
  752. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  753. // check if need to trigger auto completion
  754. if (text.startsWith("/")) {
  755. let searchText = text.slice(1);
  756. onSearch(searchText);
  757. }
  758. }
  759. };
  760. const doSubmit = (userInput: string) => {
  761. if (userInput.trim() === "") return;
  762. const matchCommand = chatCommands.match(userInput);
  763. if (matchCommand.matched) {
  764. setUserInput("");
  765. setPromptHints([]);
  766. matchCommand.invoke();
  767. return;
  768. }
  769. setIsLoading(true);
  770. chatStore
  771. .onUserInput(userInput, attachImages)
  772. .then(() => setIsLoading(false));
  773. setAttachImages([]);
  774. localStorage.setItem(LAST_INPUT_KEY, userInput);
  775. setUserInput("");
  776. setPromptHints([]);
  777. if (!isMobileScreen) inputRef.current?.focus();
  778. setAutoScroll(true);
  779. };
  780. const onPromptSelect = (prompt: RenderPrompt) => {
  781. setTimeout(() => {
  782. setPromptHints([]);
  783. const matchedChatCommand = chatCommands.match(prompt.content);
  784. if (matchedChatCommand.matched) {
  785. // if user is selecting a chat command, just trigger it
  786. matchedChatCommand.invoke();
  787. setUserInput("");
  788. } else {
  789. // or fill the prompt
  790. setUserInput(prompt.content);
  791. }
  792. inputRef.current?.focus();
  793. }, 30);
  794. };
  795. // stop response
  796. const onUserStop = (messageId: string) => {
  797. ChatControllerPool.stop(session.id, messageId);
  798. };
  799. useEffect(() => {
  800. chatStore.updateCurrentSession((session) => {
  801. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  802. session.messages.forEach((m) => {
  803. // check if should stop all stale messages
  804. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  805. if (m.streaming) {
  806. m.streaming = false;
  807. }
  808. if (m.content.length === 0) {
  809. m.isError = true;
  810. m.content = prettyObject({
  811. error: true,
  812. message: "empty response",
  813. });
  814. }
  815. }
  816. });
  817. // auto sync mask config from global config
  818. if (session.mask.syncGlobalConfig) {
  819. console.log("[Mask] syncing from global, name = ", session.mask.name);
  820. session.mask.modelConfig = { ...config.modelConfig };
  821. }
  822. });
  823. // eslint-disable-next-line react-hooks/exhaustive-deps
  824. }, []);
  825. // check if should send message
  826. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  827. // if ArrowUp and no userInput, fill with last input
  828. if (
  829. e.key === "ArrowUp" &&
  830. userInput.length <= 0 &&
  831. !(e.metaKey || e.altKey || e.ctrlKey)
  832. ) {
  833. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  834. e.preventDefault();
  835. return;
  836. }
  837. if (shouldSubmit(e) && promptHints.length === 0) {
  838. doSubmit(userInput);
  839. e.preventDefault();
  840. }
  841. };
  842. const onRightClick = (e: any, message: ChatMessage) => {
  843. // copy to clipboard
  844. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  845. if (userInput.length === 0) {
  846. setUserInput(getMessageTextContent(message));
  847. }
  848. e.preventDefault();
  849. }
  850. };
  851. const deleteMessage = (msgId?: string) => {
  852. chatStore.updateCurrentSession(
  853. (session) =>
  854. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  855. );
  856. };
  857. const onDelete = (msgId: string) => {
  858. deleteMessage(msgId);
  859. };
  860. const onResend = (message: ChatMessage) => {
  861. // when it is resending a message
  862. // 1. for a user's message, find the next bot response
  863. // 2. for a bot's message, find the last user's input
  864. // 3. delete original user input and bot's message
  865. // 4. resend the user's input
  866. const resendingIndex = session.messages.findIndex(
  867. (m) => m.id === message.id,
  868. );
  869. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  870. console.error("[Chat] failed to find resending message", message);
  871. return;
  872. }
  873. let userMessage: ChatMessage | undefined;
  874. let botMessage: ChatMessage | undefined;
  875. if (message.role === "assistant") {
  876. // if it is resending a bot's message, find the user input for it
  877. botMessage = message;
  878. for (let i = resendingIndex; i >= 0; i -= 1) {
  879. if (session.messages[i].role === "user") {
  880. userMessage = session.messages[i];
  881. break;
  882. }
  883. }
  884. } else if (message.role === "user") {
  885. // if it is resending a user's input, find the bot's response
  886. userMessage = message;
  887. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  888. if (session.messages[i].role === "assistant") {
  889. botMessage = session.messages[i];
  890. break;
  891. }
  892. }
  893. }
  894. if (userMessage === undefined) {
  895. console.error("[Chat] failed to resend", message);
  896. return;
  897. }
  898. // delete the original messages
  899. deleteMessage(userMessage.id);
  900. deleteMessage(botMessage?.id);
  901. // resend the message
  902. setIsLoading(true);
  903. const textContent = getMessageTextContent(userMessage);
  904. const images = getMessageImages(userMessage);
  905. chatStore.onUserInput(textContent, images).then(() => setIsLoading(false));
  906. inputRef.current?.focus();
  907. };
  908. const onPinMessage = (message: ChatMessage) => {
  909. chatStore.updateCurrentSession((session) =>
  910. session.mask.context.push(message),
  911. );
  912. showToast(Locale.Chat.Actions.PinToastContent, {
  913. text: Locale.Chat.Actions.PinToastAction,
  914. onClick: () => {
  915. setShowPromptModal(true);
  916. },
  917. });
  918. };
  919. const context: RenderMessage[] = useMemo(() => {
  920. return session.mask.hideContext ? [] : session.mask.context.slice();
  921. }, [session.mask.context, session.mask.hideContext]);
  922. const accessStore = useAccessStore();
  923. if (
  924. context.length === 0 &&
  925. session.messages.at(0)?.content !== BOT_HELLO.content
  926. ) {
  927. const copiedHello = Object.assign({}, BOT_HELLO);
  928. if (!accessStore.isAuthorized()) {
  929. copiedHello.content = Locale.Error.Unauthorized;
  930. }
  931. context.push(copiedHello);
  932. }
  933. // preview messages
  934. const renderMessages = useMemo(() => {
  935. return context
  936. .concat(session.messages as RenderMessage[])
  937. .concat(
  938. isLoading
  939. ? [
  940. {
  941. ...createMessage({
  942. role: "assistant",
  943. content: "……",
  944. }),
  945. preview: true,
  946. },
  947. ]
  948. : [],
  949. )
  950. .concat(
  951. userInput.length > 0 && config.sendPreviewBubble
  952. ? [
  953. {
  954. ...createMessage({
  955. role: "user",
  956. content: userInput,
  957. }),
  958. preview: true,
  959. },
  960. ]
  961. : [],
  962. );
  963. }, [
  964. config.sendPreviewBubble,
  965. context,
  966. isLoading,
  967. session.messages,
  968. userInput,
  969. ]);
  970. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  971. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  972. );
  973. function setMsgRenderIndex(newIndex: number) {
  974. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  975. newIndex = Math.max(0, newIndex);
  976. _setMsgRenderIndex(newIndex);
  977. }
  978. const messages = useMemo(() => {
  979. const endRenderIndex = Math.min(
  980. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  981. renderMessages.length,
  982. );
  983. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  984. }, [msgRenderIndex, renderMessages]);
  985. const onChatBodyScroll = (e: HTMLElement) => {
  986. const bottomHeight = e.scrollTop + e.clientHeight;
  987. const edgeThreshold = e.clientHeight;
  988. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  989. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  990. const isHitBottom =
  991. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  992. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  993. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  994. if (isTouchTopEdge && !isTouchBottomEdge) {
  995. setMsgRenderIndex(prevPageMsgIndex);
  996. } else if (isTouchBottomEdge) {
  997. setMsgRenderIndex(nextPageMsgIndex);
  998. }
  999. setHitBottom(isHitBottom);
  1000. setAutoScroll(isHitBottom);
  1001. };
  1002. function scrollToBottom() {
  1003. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1004. scrollDomToBottom();
  1005. }
  1006. // clear context index = context length + index in messages
  1007. const clearContextIndex =
  1008. (session.clearContextIndex ?? -1) >= 0
  1009. ? session.clearContextIndex! + context.length - msgRenderIndex
  1010. : -1;
  1011. const [showPromptModal, setShowPromptModal] = useState(false);
  1012. const clientConfig = useMemo(() => getClientConfig(), []);
  1013. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1014. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1015. useCommand({
  1016. fill: setUserInput,
  1017. submit: (text) => {
  1018. doSubmit(text);
  1019. },
  1020. code: (text) => {
  1021. if (accessStore.disableFastLink) return;
  1022. console.log("[Command] got code from url: ", text);
  1023. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1024. if (res) {
  1025. accessStore.update((access) => (access.accessCode = text));
  1026. }
  1027. });
  1028. },
  1029. settings: (text) => {
  1030. if (accessStore.disableFastLink) return;
  1031. try {
  1032. const payload = JSON.parse(text) as {
  1033. key?: string;
  1034. url?: string;
  1035. };
  1036. console.log("[Command] got settings from url: ", payload);
  1037. if (payload.key || payload.url) {
  1038. showConfirm(
  1039. Locale.URLCommand.Settings +
  1040. `\n${JSON.stringify(payload, null, 4)}`,
  1041. ).then((res) => {
  1042. if (!res) return;
  1043. if (payload.key) {
  1044. accessStore.update(
  1045. (access) => (access.openaiApiKey = payload.key!),
  1046. );
  1047. }
  1048. if (payload.url) {
  1049. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1050. }
  1051. accessStore.update((access) => (access.useCustomConfig = true));
  1052. });
  1053. }
  1054. } catch {
  1055. console.error("[Command] failed to get settings from url: ", text);
  1056. }
  1057. },
  1058. });
  1059. // edit / insert message modal
  1060. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1061. // remember unfinished input
  1062. useEffect(() => {
  1063. // try to load from local storage
  1064. const key = UNFINISHED_INPUT(session.id);
  1065. const mayBeUnfinishedInput = localStorage.getItem(key);
  1066. if (mayBeUnfinishedInput && userInput.length === 0) {
  1067. setUserInput(mayBeUnfinishedInput);
  1068. localStorage.removeItem(key);
  1069. }
  1070. const dom = inputRef.current;
  1071. return () => {
  1072. localStorage.setItem(key, dom?.value ?? "");
  1073. };
  1074. // eslint-disable-next-line react-hooks/exhaustive-deps
  1075. }, []);
  1076. const handlePaste = useCallback(
  1077. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1078. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1079. if (!isVisionModel(currentModel)) {
  1080. return;
  1081. }
  1082. const items = (event.clipboardData || window.clipboardData).items;
  1083. for (const item of items) {
  1084. if (item.kind === "file" && item.type.startsWith("image/")) {
  1085. event.preventDefault();
  1086. const file = item.getAsFile();
  1087. if (file) {
  1088. const images: string[] = [];
  1089. images.push(...attachImages);
  1090. images.push(
  1091. ...(await new Promise<string[]>((res, rej) => {
  1092. setUploading(true);
  1093. const imagesData: string[] = [];
  1094. uploadImageRemote(file)
  1095. .then((dataUrl) => {
  1096. imagesData.push(dataUrl);
  1097. setUploading(false);
  1098. res(imagesData);
  1099. })
  1100. .catch((e) => {
  1101. setUploading(false);
  1102. rej(e);
  1103. });
  1104. })),
  1105. );
  1106. const imagesLength = images.length;
  1107. if (imagesLength > 3) {
  1108. images.splice(3, imagesLength - 3);
  1109. }
  1110. setAttachImages(images);
  1111. }
  1112. }
  1113. }
  1114. },
  1115. [attachImages, chatStore],
  1116. );
  1117. async function uploadImage() {
  1118. const images: string[] = [];
  1119. images.push(...attachImages);
  1120. images.push(
  1121. ...(await new Promise<string[]>((res, rej) => {
  1122. const fileInput = document.createElement("input");
  1123. fileInput.type = "file";
  1124. fileInput.accept =
  1125. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1126. fileInput.multiple = true;
  1127. fileInput.onchange = (event: any) => {
  1128. setUploading(true);
  1129. const files = event.target.files;
  1130. const imagesData: string[] = [];
  1131. for (let i = 0; i < files.length; i++) {
  1132. const file = event.target.files[i];
  1133. uploadImageRemote(file)
  1134. .then((dataUrl) => {
  1135. imagesData.push(dataUrl);
  1136. if (
  1137. imagesData.length === 3 ||
  1138. imagesData.length === files.length
  1139. ) {
  1140. setUploading(false);
  1141. res(imagesData);
  1142. }
  1143. })
  1144. .catch((e) => {
  1145. setUploading(false);
  1146. rej(e);
  1147. });
  1148. }
  1149. };
  1150. fileInput.click();
  1151. })),
  1152. );
  1153. const imagesLength = images.length;
  1154. if (imagesLength > 3) {
  1155. images.splice(3, imagesLength - 3);
  1156. }
  1157. setAttachImages(images);
  1158. }
  1159. return (
  1160. <div className={styles.chat} key={session.id}>
  1161. <div className="window-header" data-tauri-drag-region>
  1162. {isMobileScreen && (
  1163. <div className="window-actions">
  1164. <div className={"window-action-button"}>
  1165. <IconButton
  1166. icon={<ReturnIcon />}
  1167. bordered
  1168. title={Locale.Chat.Actions.ChatList}
  1169. onClick={() => navigate(Path.Home)}
  1170. />
  1171. </div>
  1172. </div>
  1173. )}
  1174. <div className={`window-header-title ${styles["chat-body-title"]}`}>
  1175. <div
  1176. className={`window-header-main-title ${styles["chat-body-main-title"]}`}
  1177. onClickCapture={() => setIsEditingMessage(true)}
  1178. >
  1179. {!session.topic ? DEFAULT_TOPIC : session.topic}
  1180. </div>
  1181. <div className="window-header-sub-title">
  1182. {Locale.Chat.SubTitle(session.messages.length)}
  1183. </div>
  1184. </div>
  1185. <div className="window-actions">
  1186. {!isMobileScreen && (
  1187. <div className="window-action-button">
  1188. <IconButton
  1189. icon={<RenameIcon />}
  1190. bordered
  1191. onClick={() => setIsEditingMessage(true)}
  1192. />
  1193. </div>
  1194. )}
  1195. <div className="window-action-button">
  1196. <IconButton
  1197. icon={<ExportIcon />}
  1198. bordered
  1199. title={Locale.Chat.Actions.Export}
  1200. onClick={() => {
  1201. setShowExport(true);
  1202. }}
  1203. />
  1204. </div>
  1205. {showMaxIcon && (
  1206. <div className="window-action-button">
  1207. <IconButton
  1208. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1209. bordered
  1210. onClick={() => {
  1211. config.update(
  1212. (config) => (config.tightBorder = !config.tightBorder),
  1213. );
  1214. }}
  1215. />
  1216. </div>
  1217. )}
  1218. </div>
  1219. <PromptToast
  1220. showToast={!hitBottom}
  1221. showModal={showPromptModal}
  1222. setShowModal={setShowPromptModal}
  1223. />
  1224. </div>
  1225. <div
  1226. className={styles["chat-body"]}
  1227. ref={scrollRef}
  1228. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1229. onMouseDown={() => inputRef.current?.blur()}
  1230. onTouchStart={() => {
  1231. inputRef.current?.blur();
  1232. setAutoScroll(false);
  1233. }}
  1234. >
  1235. {messages.map((message, i) => {
  1236. const isUser = message.role === "user";
  1237. const isContext = i < context.length;
  1238. const showActions =
  1239. i > 0 &&
  1240. !(message.preview || message.content.length === 0) &&
  1241. !isContext;
  1242. const showTyping = message.preview || message.streaming;
  1243. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1244. return (
  1245. <Fragment key={message.id}>
  1246. <div
  1247. className={
  1248. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1249. }
  1250. >
  1251. <div className={styles["chat-message-container"]}>
  1252. <div className={styles["chat-message-header"]}>
  1253. <div className={styles["chat-message-avatar"]}>
  1254. <div className={styles["chat-message-edit"]}>
  1255. <IconButton
  1256. icon={<EditIcon />}
  1257. onClick={async () => {
  1258. const newMessage = await showPrompt(
  1259. Locale.Chat.Actions.Edit,
  1260. getMessageTextContent(message),
  1261. 10,
  1262. );
  1263. let newContent: string | MultimodalContent[] =
  1264. newMessage;
  1265. const images = getMessageImages(message);
  1266. if (images.length > 0) {
  1267. newContent = [{ type: "text", text: newMessage }];
  1268. for (let i = 0; i < images.length; i++) {
  1269. newContent.push({
  1270. type: "image_url",
  1271. image_url: {
  1272. url: images[i],
  1273. },
  1274. });
  1275. }
  1276. }
  1277. chatStore.updateCurrentSession((session) => {
  1278. const m = session.mask.context
  1279. .concat(session.messages)
  1280. .find((m) => m.id === message.id);
  1281. if (m) {
  1282. m.content = newContent;
  1283. }
  1284. });
  1285. }}
  1286. ></IconButton>
  1287. </div>
  1288. {isUser ? (
  1289. <Avatar avatar={config.avatar} />
  1290. ) : (
  1291. <>
  1292. {["system"].includes(message.role) ? (
  1293. <Avatar avatar="2699-fe0f" />
  1294. ) : (
  1295. <MaskAvatar
  1296. avatar={session.mask.avatar}
  1297. model={
  1298. message.model || session.mask.modelConfig.model
  1299. }
  1300. />
  1301. )}
  1302. </>
  1303. )}
  1304. </div>
  1305. {showActions && (
  1306. <div className={styles["chat-message-actions"]}>
  1307. <div className={styles["chat-input-actions"]}>
  1308. {message.streaming ? (
  1309. <ChatAction
  1310. text={Locale.Chat.Actions.Stop}
  1311. icon={<StopIcon />}
  1312. onClick={() => onUserStop(message.id ?? i)}
  1313. />
  1314. ) : (
  1315. <>
  1316. <ChatAction
  1317. text={Locale.Chat.Actions.Retry}
  1318. icon={<ResetIcon />}
  1319. onClick={() => onResend(message)}
  1320. />
  1321. <ChatAction
  1322. text={Locale.Chat.Actions.Delete}
  1323. icon={<DeleteIcon />}
  1324. onClick={() => onDelete(message.id ?? i)}
  1325. />
  1326. <ChatAction
  1327. text={Locale.Chat.Actions.Pin}
  1328. icon={<PinIcon />}
  1329. onClick={() => onPinMessage(message)}
  1330. />
  1331. <ChatAction
  1332. text={Locale.Chat.Actions.Copy}
  1333. icon={<CopyIcon />}
  1334. onClick={() =>
  1335. copyToClipboard(
  1336. getMessageTextContent(message),
  1337. )
  1338. }
  1339. />
  1340. </>
  1341. )}
  1342. </div>
  1343. </div>
  1344. )}
  1345. </div>
  1346. {showTyping && (
  1347. <div className={styles["chat-message-status"]}>
  1348. {Locale.Chat.Typing}
  1349. </div>
  1350. )}
  1351. <div className={styles["chat-message-item"]}>
  1352. <Markdown
  1353. content={getMessageTextContent(message)}
  1354. loading={
  1355. (message.preview || message.streaming) &&
  1356. message.content.length === 0 &&
  1357. !isUser
  1358. }
  1359. onContextMenu={(e) => onRightClick(e, message)}
  1360. onDoubleClickCapture={() => {
  1361. if (!isMobileScreen) return;
  1362. setUserInput(getMessageTextContent(message));
  1363. }}
  1364. fontSize={fontSize}
  1365. fontFamily={fontFamily}
  1366. parentRef={scrollRef}
  1367. defaultShow={i >= messages.length - 6}
  1368. />
  1369. {getMessageImages(message).length == 1 && (
  1370. <img
  1371. className={styles["chat-message-item-image"]}
  1372. src={getMessageImages(message)[0]}
  1373. alt=""
  1374. />
  1375. )}
  1376. {getMessageImages(message).length > 1 && (
  1377. <div
  1378. className={styles["chat-message-item-images"]}
  1379. style={
  1380. {
  1381. "--image-count": getMessageImages(message).length,
  1382. } as React.CSSProperties
  1383. }
  1384. >
  1385. {getMessageImages(message).map((image, index) => {
  1386. return (
  1387. <img
  1388. className={
  1389. styles["chat-message-item-image-multi"]
  1390. }
  1391. key={index}
  1392. src={image}
  1393. alt=""
  1394. />
  1395. );
  1396. })}
  1397. </div>
  1398. )}
  1399. </div>
  1400. <div className={styles["chat-message-action-date"]}>
  1401. {isContext
  1402. ? Locale.Chat.IsContext
  1403. : message.date.toLocaleString()}
  1404. </div>
  1405. </div>
  1406. </div>
  1407. {shouldShowClearContextDivider && <ClearContextDivider />}
  1408. </Fragment>
  1409. );
  1410. })}
  1411. </div>
  1412. <div className={styles["chat-input-panel"]}>
  1413. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  1414. <ChatActions
  1415. uploadImage={uploadImage}
  1416. setAttachImages={setAttachImages}
  1417. setUploading={setUploading}
  1418. showPromptModal={() => setShowPromptModal(true)}
  1419. scrollToBottom={scrollToBottom}
  1420. hitBottom={hitBottom}
  1421. uploading={uploading}
  1422. showPromptHints={() => {
  1423. // Click again to close
  1424. if (promptHints.length > 0) {
  1425. setPromptHints([]);
  1426. return;
  1427. }
  1428. inputRef.current?.focus();
  1429. setUserInput("/");
  1430. onSearch("");
  1431. }}
  1432. />
  1433. <label
  1434. className={`${styles["chat-input-panel-inner"]} ${
  1435. attachImages.length != 0
  1436. ? styles["chat-input-panel-inner-attach"]
  1437. : ""
  1438. }`}
  1439. htmlFor="chat-input"
  1440. >
  1441. <textarea
  1442. id="chat-input"
  1443. ref={inputRef}
  1444. className={styles["chat-input"]}
  1445. placeholder={Locale.Chat.Input(submitKey)}
  1446. onInput={(e) => onInput(e.currentTarget.value)}
  1447. value={userInput}
  1448. onKeyDown={onInputKeyDown}
  1449. onFocus={scrollToBottom}
  1450. onClick={scrollToBottom}
  1451. onPaste={handlePaste}
  1452. rows={inputRows}
  1453. autoFocus={autoFocus}
  1454. style={{
  1455. fontSize: config.fontSize,
  1456. fontFamily: config.fontFamily,
  1457. }}
  1458. />
  1459. {attachImages.length != 0 && (
  1460. <div className={styles["attach-images"]}>
  1461. {attachImages.map((image, index) => {
  1462. return (
  1463. <div
  1464. key={index}
  1465. className={styles["attach-image"]}
  1466. style={{ backgroundImage: `url("${image}")` }}
  1467. >
  1468. <div className={styles["attach-image-mask"]}>
  1469. <DeleteImageButton
  1470. deleteImage={() => {
  1471. setAttachImages(
  1472. attachImages.filter((_, i) => i !== index),
  1473. );
  1474. }}
  1475. />
  1476. </div>
  1477. </div>
  1478. );
  1479. })}
  1480. </div>
  1481. )}
  1482. <IconButton
  1483. icon={<SendWhiteIcon />}
  1484. text={Locale.Chat.Send}
  1485. className={styles["chat-input-send"]}
  1486. type="primary"
  1487. onClick={() => doSubmit(userInput)}
  1488. />
  1489. </label>
  1490. </div>
  1491. {showExport && (
  1492. <ExportMessageModal onClose={() => setShowExport(false)} />
  1493. )}
  1494. {isEditingMessage && (
  1495. <EditMessageModal
  1496. onClose={() => {
  1497. setIsEditingMessage(false);
  1498. }}
  1499. />
  1500. )}
  1501. </div>
  1502. );
  1503. }
  1504. export function Chat() {
  1505. const chatStore = useChatStore();
  1506. const sessionIndex = chatStore.currentSessionIndex;
  1507. return <_Chat key={sessionIndex}></_Chat>;
  1508. }