chat.tsx 49 KB

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