chat.tsx 54 KB

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