chat.tsx 50 KB

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