chat.tsx 50 KB

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