chat.tsx 59 KB

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