chat.tsx 62 KB

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