chat.tsx 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  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.startsWith(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. key={message.streaming ? "loading" : "done"}
  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. parentRef={scrollRef}
  1366. defaultShow={i >= messages.length - 6}
  1367. />
  1368. {getMessageImages(message).length == 1 && (
  1369. <img
  1370. className={styles["chat-message-item-image"]}
  1371. src={getMessageImages(message)[0]}
  1372. alt=""
  1373. />
  1374. )}
  1375. {getMessageImages(message).length > 1 && (
  1376. <div
  1377. className={styles["chat-message-item-images"]}
  1378. style={
  1379. {
  1380. "--image-count": getMessageImages(message).length,
  1381. } as React.CSSProperties
  1382. }
  1383. >
  1384. {getMessageImages(message).map((image, index) => {
  1385. return (
  1386. <img
  1387. className={
  1388. styles["chat-message-item-image-multi"]
  1389. }
  1390. key={index}
  1391. src={image}
  1392. alt=""
  1393. />
  1394. );
  1395. })}
  1396. </div>
  1397. )}
  1398. </div>
  1399. <div className={styles["chat-message-action-date"]}>
  1400. {isContext
  1401. ? Locale.Chat.IsContext
  1402. : message.date.toLocaleString()}
  1403. </div>
  1404. </div>
  1405. </div>
  1406. {shouldShowClearContextDivider && <ClearContextDivider />}
  1407. </Fragment>
  1408. );
  1409. })}
  1410. </div>
  1411. <div className={styles["chat-input-panel"]}>
  1412. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  1413. <ChatActions
  1414. uploadImage={uploadImage}
  1415. setAttachImages={setAttachImages}
  1416. setUploading={setUploading}
  1417. showPromptModal={() => setShowPromptModal(true)}
  1418. scrollToBottom={scrollToBottom}
  1419. hitBottom={hitBottom}
  1420. uploading={uploading}
  1421. showPromptHints={() => {
  1422. // Click again to close
  1423. if (promptHints.length > 0) {
  1424. setPromptHints([]);
  1425. return;
  1426. }
  1427. inputRef.current?.focus();
  1428. setUserInput("/");
  1429. onSearch("");
  1430. }}
  1431. />
  1432. <label
  1433. className={`${styles["chat-input-panel-inner"]} ${
  1434. attachImages.length != 0
  1435. ? styles["chat-input-panel-inner-attach"]
  1436. : ""
  1437. }`}
  1438. htmlFor="chat-input"
  1439. >
  1440. <textarea
  1441. id="chat-input"
  1442. ref={inputRef}
  1443. className={styles["chat-input"]}
  1444. placeholder={Locale.Chat.Input(submitKey)}
  1445. onInput={(e) => onInput(e.currentTarget.value)}
  1446. value={userInput}
  1447. onKeyDown={onInputKeyDown}
  1448. onFocus={scrollToBottom}
  1449. onClick={scrollToBottom}
  1450. onPaste={handlePaste}
  1451. rows={inputRows}
  1452. autoFocus={autoFocus}
  1453. style={{
  1454. fontSize: config.fontSize,
  1455. }}
  1456. />
  1457. {attachImages.length != 0 && (
  1458. <div className={styles["attach-images"]}>
  1459. {attachImages.map((image, index) => {
  1460. return (
  1461. <div
  1462. key={index}
  1463. className={styles["attach-image"]}
  1464. style={{ backgroundImage: `url("${image}")` }}
  1465. >
  1466. <div className={styles["attach-image-mask"]}>
  1467. <DeleteImageButton
  1468. deleteImage={() => {
  1469. setAttachImages(
  1470. attachImages.filter((_, i) => i !== index),
  1471. );
  1472. }}
  1473. />
  1474. </div>
  1475. </div>
  1476. );
  1477. })}
  1478. </div>
  1479. )}
  1480. <IconButton
  1481. icon={<SendWhiteIcon />}
  1482. text={Locale.Chat.Send}
  1483. className={styles["chat-input-send"]}
  1484. type="primary"
  1485. onClick={() => doSubmit(userInput)}
  1486. />
  1487. </label>
  1488. </div>
  1489. {showExport && (
  1490. <ExportMessageModal onClose={() => setShowExport(false)} />
  1491. )}
  1492. {isEditingMessage && (
  1493. <EditMessageModal
  1494. onClose={() => {
  1495. setIsEditingMessage(false);
  1496. }}
  1497. />
  1498. )}
  1499. </div>
  1500. );
  1501. }
  1502. export function Chat() {
  1503. const chatStore = useChatStore();
  1504. const sessionIndex = chatStore.currentSessionIndex;
  1505. return <_Chat key={sessionIndex}></_Chat>;
  1506. }