chat.tsx 51 KB

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