chat.tsx 54 KB

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