chat.tsx 62 KB

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