chat.tsx 53 KB

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