chat.tsx 58 KB

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