chat.tsx 54 KB

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