chat.tsx 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  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={() => setShowPluginSelector(true)}
  673. text={Locale.Plugin.Name}
  674. icon={<PluginIcon />}
  675. />
  676. )}
  677. {showPluginSelector && showPlugins(currentProviderName, currentModel) && (
  678. <Selector
  679. multiple
  680. defaultSelectedValue={chatStore.currentSession().mask?.plugin}
  681. items={pluginStore.getAll().map((item) => ({
  682. title: `${item?.title}@${item?.version}`,
  683. value: item?.id,
  684. }))}
  685. onClose={() => setShowPluginSelector(false)}
  686. onSelection={(s) => {
  687. chatStore.updateCurrentSession((session) => {
  688. session.mask.plugin = s as string[];
  689. });
  690. }}
  691. />
  692. )}
  693. </div>
  694. );
  695. }
  696. export function EditMessageModal(props: { onClose: () => void }) {
  697. const chatStore = useChatStore();
  698. const session = chatStore.currentSession();
  699. const [messages, setMessages] = useState(session.messages.slice());
  700. return (
  701. <div className="modal-mask">
  702. <Modal
  703. title={Locale.Chat.EditMessage.Title}
  704. onClose={props.onClose}
  705. actions={[
  706. <IconButton
  707. text={Locale.UI.Cancel}
  708. icon={<CancelIcon />}
  709. key="cancel"
  710. onClick={() => {
  711. props.onClose();
  712. }}
  713. />,
  714. <IconButton
  715. type="primary"
  716. text={Locale.UI.Confirm}
  717. icon={<ConfirmIcon />}
  718. key="ok"
  719. onClick={() => {
  720. chatStore.updateCurrentSession(
  721. (session) => (session.messages = messages),
  722. );
  723. props.onClose();
  724. }}
  725. />,
  726. ]}
  727. >
  728. <List>
  729. <ListItem
  730. title={Locale.Chat.EditMessage.Topic.Title}
  731. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  732. >
  733. <input
  734. type="text"
  735. value={session.topic}
  736. onInput={(e) =>
  737. chatStore.updateCurrentSession(
  738. (session) => (session.topic = e.currentTarget.value),
  739. )
  740. }
  741. ></input>
  742. </ListItem>
  743. </List>
  744. <ContextPrompts
  745. context={messages}
  746. updateContext={(updater) => {
  747. const newMessages = messages.slice();
  748. updater(newMessages);
  749. setMessages(newMessages);
  750. }}
  751. />
  752. </Modal>
  753. </div>
  754. );
  755. }
  756. export function DeleteImageButton(props: { deleteImage: () => void }) {
  757. return (
  758. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  759. <DeleteIcon />
  760. </div>
  761. );
  762. }
  763. function _Chat() {
  764. type RenderMessage = ChatMessage & { preview?: boolean };
  765. const chatStore = useChatStore();
  766. const session = chatStore.currentSession();
  767. const config = useAppConfig();
  768. const fontSize = config.fontSize;
  769. const fontFamily = config.fontFamily;
  770. const [showExport, setShowExport] = useState(false);
  771. const inputRef = useRef<HTMLTextAreaElement>(null);
  772. const [userInput, setUserInput] = useState("");
  773. const [isLoading, setIsLoading] = useState(false);
  774. const { submitKey, shouldSubmit } = useSubmitHandler();
  775. const scrollRef = useRef<HTMLDivElement>(null);
  776. const isScrolledToBottom = scrollRef?.current
  777. ? Math.abs(
  778. scrollRef.current.scrollHeight -
  779. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  780. ) <= 1
  781. : false;
  782. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  783. scrollRef,
  784. isScrolledToBottom,
  785. );
  786. const [hitBottom, setHitBottom] = useState(true);
  787. const isMobileScreen = useMobileScreen();
  788. const navigate = useNavigate();
  789. const [attachImages, setAttachImages] = useState<string[]>([]);
  790. const [uploading, setUploading] = useState(false);
  791. // prompt hints
  792. const promptStore = usePromptStore();
  793. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  794. const onSearch = useDebouncedCallback(
  795. (text: string) => {
  796. const matchedPrompts = promptStore.search(text);
  797. setPromptHints(matchedPrompts);
  798. },
  799. 100,
  800. { leading: true, trailing: true },
  801. );
  802. // auto grow input
  803. const [inputRows, setInputRows] = useState(2);
  804. const measure = useDebouncedCallback(
  805. () => {
  806. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  807. const inputRows = Math.min(
  808. 20,
  809. Math.max(2 + Number(!isMobileScreen), rows),
  810. );
  811. setInputRows(inputRows);
  812. },
  813. 100,
  814. {
  815. leading: true,
  816. trailing: true,
  817. },
  818. );
  819. // eslint-disable-next-line react-hooks/exhaustive-deps
  820. useEffect(measure, [userInput]);
  821. // chat commands shortcuts
  822. const chatCommands = useChatCommand({
  823. new: () => chatStore.newSession(),
  824. newm: () => navigate(Path.NewChat),
  825. prev: () => chatStore.nextSession(-1),
  826. next: () => chatStore.nextSession(1),
  827. clear: () =>
  828. chatStore.updateCurrentSession(
  829. (session) => (session.clearContextIndex = session.messages.length),
  830. ),
  831. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  832. });
  833. // only search prompts when user input is short
  834. const SEARCH_TEXT_LIMIT = 30;
  835. const onInput = (text: string) => {
  836. setUserInput(text);
  837. const n = text.trim().length;
  838. // clear search results
  839. if (n === 0) {
  840. setPromptHints([]);
  841. } else if (text.match(ChatCommandPrefix)) {
  842. setPromptHints(chatCommands.search(text));
  843. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  844. // check if need to trigger auto completion
  845. if (text.startsWith("/")) {
  846. let searchText = text.slice(1);
  847. onSearch(searchText);
  848. }
  849. }
  850. };
  851. const doSubmit = (userInput: string) => {
  852. if (userInput.trim() === "") return;
  853. const matchCommand = chatCommands.match(userInput);
  854. if (matchCommand.matched) {
  855. setUserInput("");
  856. setPromptHints([]);
  857. matchCommand.invoke();
  858. return;
  859. }
  860. setIsLoading(true);
  861. chatStore
  862. .onUserInput(userInput, attachImages)
  863. .then(() => setIsLoading(false));
  864. setAttachImages([]);
  865. localStorage.setItem(LAST_INPUT_KEY, userInput);
  866. setUserInput("");
  867. setPromptHints([]);
  868. if (!isMobileScreen) inputRef.current?.focus();
  869. setAutoScroll(true);
  870. };
  871. const onPromptSelect = (prompt: RenderPrompt) => {
  872. setTimeout(() => {
  873. setPromptHints([]);
  874. const matchedChatCommand = chatCommands.match(prompt.content);
  875. if (matchedChatCommand.matched) {
  876. // if user is selecting a chat command, just trigger it
  877. matchedChatCommand.invoke();
  878. setUserInput("");
  879. } else {
  880. // or fill the prompt
  881. setUserInput(prompt.content);
  882. }
  883. inputRef.current?.focus();
  884. }, 30);
  885. };
  886. // stop response
  887. const onUserStop = (messageId: string) => {
  888. ChatControllerPool.stop(session.id, messageId);
  889. };
  890. useEffect(() => {
  891. chatStore.updateCurrentSession((session) => {
  892. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  893. session.messages.forEach((m) => {
  894. // check if should stop all stale messages
  895. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  896. if (m.streaming) {
  897. m.streaming = false;
  898. }
  899. if (m.content.length === 0) {
  900. m.isError = true;
  901. m.content = prettyObject({
  902. error: true,
  903. message: "empty response",
  904. });
  905. }
  906. }
  907. });
  908. // auto sync mask config from global config
  909. if (session.mask.syncGlobalConfig) {
  910. console.log("[Mask] syncing from global, name = ", session.mask.name);
  911. session.mask.modelConfig = { ...config.modelConfig };
  912. }
  913. });
  914. // eslint-disable-next-line react-hooks/exhaustive-deps
  915. }, []);
  916. // check if should send message
  917. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  918. // if ArrowUp and no userInput, fill with last input
  919. if (
  920. e.key === "ArrowUp" &&
  921. userInput.length <= 0 &&
  922. !(e.metaKey || e.altKey || e.ctrlKey)
  923. ) {
  924. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  925. e.preventDefault();
  926. return;
  927. }
  928. if (shouldSubmit(e) && promptHints.length === 0) {
  929. doSubmit(userInput);
  930. e.preventDefault();
  931. }
  932. };
  933. const onRightClick = (e: any, message: ChatMessage) => {
  934. // copy to clipboard
  935. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  936. if (userInput.length === 0) {
  937. setUserInput(getMessageTextContent(message));
  938. }
  939. e.preventDefault();
  940. }
  941. };
  942. const deleteMessage = (msgId?: string) => {
  943. chatStore.updateCurrentSession(
  944. (session) =>
  945. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  946. );
  947. };
  948. const onDelete = (msgId: string) => {
  949. deleteMessage(msgId);
  950. };
  951. const onResend = (message: ChatMessage) => {
  952. // when it is resending a message
  953. // 1. for a user's message, find the next bot response
  954. // 2. for a bot's message, find the last user's input
  955. // 3. delete original user input and bot's message
  956. // 4. resend the user's input
  957. const resendingIndex = session.messages.findIndex(
  958. (m) => m.id === message.id,
  959. );
  960. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  961. console.error("[Chat] failed to find resending message", message);
  962. return;
  963. }
  964. let userMessage: ChatMessage | undefined;
  965. let botMessage: ChatMessage | undefined;
  966. if (message.role === "assistant") {
  967. // if it is resending a bot's message, find the user input for it
  968. botMessage = message;
  969. for (let i = resendingIndex; i >= 0; i -= 1) {
  970. if (session.messages[i].role === "user") {
  971. userMessage = session.messages[i];
  972. break;
  973. }
  974. }
  975. } else if (message.role === "user") {
  976. // if it is resending a user's input, find the bot's response
  977. userMessage = message;
  978. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  979. if (session.messages[i].role === "assistant") {
  980. botMessage = session.messages[i];
  981. break;
  982. }
  983. }
  984. }
  985. if (userMessage === undefined) {
  986. console.error("[Chat] failed to resend", message);
  987. return;
  988. }
  989. // delete the original messages
  990. deleteMessage(userMessage.id);
  991. deleteMessage(botMessage?.id);
  992. // resend the message
  993. setIsLoading(true);
  994. const textContent = getMessageTextContent(userMessage);
  995. const images = getMessageImages(userMessage);
  996. chatStore.onUserInput(textContent, images).then(() => setIsLoading(false));
  997. inputRef.current?.focus();
  998. };
  999. const onPinMessage = (message: ChatMessage) => {
  1000. chatStore.updateCurrentSession((session) =>
  1001. session.mask.context.push(message),
  1002. );
  1003. showToast(Locale.Chat.Actions.PinToastContent, {
  1004. text: Locale.Chat.Actions.PinToastAction,
  1005. onClick: () => {
  1006. setShowPromptModal(true);
  1007. },
  1008. });
  1009. };
  1010. const context: RenderMessage[] = useMemo(() => {
  1011. return session.mask.hideContext ? [] : session.mask.context.slice();
  1012. }, [session.mask.context, session.mask.hideContext]);
  1013. const accessStore = useAccessStore();
  1014. if (
  1015. context.length === 0 &&
  1016. session.messages.at(0)?.content !== BOT_HELLO.content
  1017. ) {
  1018. const copiedHello = Object.assign({}, BOT_HELLO);
  1019. if (!accessStore.isAuthorized()) {
  1020. copiedHello.content = Locale.Error.Unauthorized;
  1021. }
  1022. context.push(copiedHello);
  1023. }
  1024. // preview messages
  1025. const renderMessages = useMemo(() => {
  1026. return context
  1027. .concat(session.messages as RenderMessage[])
  1028. .concat(
  1029. isLoading
  1030. ? [
  1031. {
  1032. ...createMessage({
  1033. role: "assistant",
  1034. content: "……",
  1035. }),
  1036. preview: true,
  1037. },
  1038. ]
  1039. : [],
  1040. )
  1041. .concat(
  1042. userInput.length > 0 && config.sendPreviewBubble
  1043. ? [
  1044. {
  1045. ...createMessage({
  1046. role: "user",
  1047. content: userInput,
  1048. }),
  1049. preview: true,
  1050. },
  1051. ]
  1052. : [],
  1053. );
  1054. }, [
  1055. config.sendPreviewBubble,
  1056. context,
  1057. isLoading,
  1058. session.messages,
  1059. userInput,
  1060. ]);
  1061. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  1062. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1063. );
  1064. function setMsgRenderIndex(newIndex: number) {
  1065. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1066. newIndex = Math.max(0, newIndex);
  1067. _setMsgRenderIndex(newIndex);
  1068. }
  1069. const messages = useMemo(() => {
  1070. const endRenderIndex = Math.min(
  1071. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1072. renderMessages.length,
  1073. );
  1074. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1075. }, [msgRenderIndex, renderMessages]);
  1076. const onChatBodyScroll = (e: HTMLElement) => {
  1077. const bottomHeight = e.scrollTop + e.clientHeight;
  1078. const edgeThreshold = e.clientHeight;
  1079. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1080. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1081. const isHitBottom =
  1082. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1083. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1084. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1085. if (isTouchTopEdge && !isTouchBottomEdge) {
  1086. setMsgRenderIndex(prevPageMsgIndex);
  1087. } else if (isTouchBottomEdge) {
  1088. setMsgRenderIndex(nextPageMsgIndex);
  1089. }
  1090. setHitBottom(isHitBottom);
  1091. setAutoScroll(isHitBottom);
  1092. };
  1093. function scrollToBottom() {
  1094. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1095. scrollDomToBottom();
  1096. }
  1097. // clear context index = context length + index in messages
  1098. const clearContextIndex =
  1099. (session.clearContextIndex ?? -1) >= 0
  1100. ? session.clearContextIndex! + context.length - msgRenderIndex
  1101. : -1;
  1102. const [showPromptModal, setShowPromptModal] = useState(false);
  1103. const clientConfig = useMemo(() => getClientConfig(), []);
  1104. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1105. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1106. useCommand({
  1107. fill: setUserInput,
  1108. submit: (text) => {
  1109. doSubmit(text);
  1110. },
  1111. code: (text) => {
  1112. if (accessStore.disableFastLink) return;
  1113. console.log("[Command] got code from url: ", text);
  1114. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1115. if (res) {
  1116. accessStore.update((access) => (access.accessCode = text));
  1117. }
  1118. });
  1119. },
  1120. settings: (text) => {
  1121. if (accessStore.disableFastLink) return;
  1122. try {
  1123. const payload = JSON.parse(text) as {
  1124. key?: string;
  1125. url?: string;
  1126. };
  1127. console.log("[Command] got settings from url: ", payload);
  1128. if (payload.key || payload.url) {
  1129. showConfirm(
  1130. Locale.URLCommand.Settings +
  1131. `\n${JSON.stringify(payload, null, 4)}`,
  1132. ).then((res) => {
  1133. if (!res) return;
  1134. if (payload.key) {
  1135. accessStore.update(
  1136. (access) => (access.openaiApiKey = payload.key!),
  1137. );
  1138. }
  1139. if (payload.url) {
  1140. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1141. }
  1142. accessStore.update((access) => (access.useCustomConfig = true));
  1143. });
  1144. }
  1145. } catch {
  1146. console.error("[Command] failed to get settings from url: ", text);
  1147. }
  1148. },
  1149. });
  1150. // edit / insert message modal
  1151. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1152. // remember unfinished input
  1153. useEffect(() => {
  1154. // try to load from local storage
  1155. const key = UNFINISHED_INPUT(session.id);
  1156. const mayBeUnfinishedInput = localStorage.getItem(key);
  1157. if (mayBeUnfinishedInput && userInput.length === 0) {
  1158. setUserInput(mayBeUnfinishedInput);
  1159. localStorage.removeItem(key);
  1160. }
  1161. const dom = inputRef.current;
  1162. return () => {
  1163. localStorage.setItem(key, dom?.value ?? "");
  1164. };
  1165. // eslint-disable-next-line react-hooks/exhaustive-deps
  1166. }, []);
  1167. const handlePaste = useCallback(
  1168. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1169. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1170. if (!isVisionModel(currentModel)) {
  1171. return;
  1172. }
  1173. const items = (event.clipboardData || window.clipboardData).items;
  1174. for (const item of items) {
  1175. if (item.kind === "file" && item.type.startsWith("image/")) {
  1176. event.preventDefault();
  1177. const file = item.getAsFile();
  1178. if (file) {
  1179. const images: string[] = [];
  1180. images.push(...attachImages);
  1181. images.push(
  1182. ...(await new Promise<string[]>((res, rej) => {
  1183. setUploading(true);
  1184. const imagesData: string[] = [];
  1185. uploadImageRemote(file)
  1186. .then((dataUrl) => {
  1187. imagesData.push(dataUrl);
  1188. setUploading(false);
  1189. res(imagesData);
  1190. })
  1191. .catch((e) => {
  1192. setUploading(false);
  1193. rej(e);
  1194. });
  1195. })),
  1196. );
  1197. const imagesLength = images.length;
  1198. if (imagesLength > 3) {
  1199. images.splice(3, imagesLength - 3);
  1200. }
  1201. setAttachImages(images);
  1202. }
  1203. }
  1204. }
  1205. },
  1206. [attachImages, chatStore],
  1207. );
  1208. async function uploadImage() {
  1209. const images: string[] = [];
  1210. images.push(...attachImages);
  1211. images.push(
  1212. ...(await new Promise<string[]>((res, rej) => {
  1213. const fileInput = document.createElement("input");
  1214. fileInput.type = "file";
  1215. fileInput.accept =
  1216. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1217. fileInput.multiple = true;
  1218. fileInput.onchange = (event: any) => {
  1219. setUploading(true);
  1220. const files = event.target.files;
  1221. const imagesData: string[] = [];
  1222. for (let i = 0; i < files.length; i++) {
  1223. const file = event.target.files[i];
  1224. uploadImageRemote(file)
  1225. .then((dataUrl) => {
  1226. imagesData.push(dataUrl);
  1227. if (
  1228. imagesData.length === 3 ||
  1229. imagesData.length === files.length
  1230. ) {
  1231. setUploading(false);
  1232. res(imagesData);
  1233. }
  1234. })
  1235. .catch((e) => {
  1236. setUploading(false);
  1237. rej(e);
  1238. });
  1239. }
  1240. };
  1241. fileInput.click();
  1242. })),
  1243. );
  1244. const imagesLength = images.length;
  1245. if (imagesLength > 3) {
  1246. images.splice(3, imagesLength - 3);
  1247. }
  1248. setAttachImages(images);
  1249. }
  1250. return (
  1251. <div className={styles.chat} key={session.id}>
  1252. <div className="window-header" data-tauri-drag-region>
  1253. {isMobileScreen && (
  1254. <div className="window-actions">
  1255. <div className={"window-action-button"}>
  1256. <IconButton
  1257. icon={<ReturnIcon />}
  1258. bordered
  1259. title={Locale.Chat.Actions.ChatList}
  1260. onClick={() => navigate(Path.Home)}
  1261. />
  1262. </div>
  1263. </div>
  1264. )}
  1265. <div className={`window-header-title ${styles["chat-body-title"]}`}>
  1266. <div
  1267. className={`window-header-main-title ${styles["chat-body-main-title"]}`}
  1268. onClickCapture={() => setIsEditingMessage(true)}
  1269. >
  1270. {!session.topic ? DEFAULT_TOPIC : session.topic}
  1271. </div>
  1272. <div className="window-header-sub-title">
  1273. {Locale.Chat.SubTitle(session.messages.length)}
  1274. </div>
  1275. </div>
  1276. <div className="window-actions">
  1277. {!isMobileScreen && (
  1278. <div className="window-action-button">
  1279. <IconButton
  1280. icon={<RenameIcon />}
  1281. bordered
  1282. title={Locale.Chat.EditMessage.Title}
  1283. aria={Locale.Chat.EditMessage.Title}
  1284. onClick={() => setIsEditingMessage(true)}
  1285. />
  1286. </div>
  1287. )}
  1288. <div className="window-action-button">
  1289. <IconButton
  1290. icon={<ExportIcon />}
  1291. bordered
  1292. title={Locale.Chat.Actions.Export}
  1293. onClick={() => {
  1294. setShowExport(true);
  1295. }}
  1296. />
  1297. </div>
  1298. {showMaxIcon && (
  1299. <div className="window-action-button">
  1300. <IconButton
  1301. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1302. bordered
  1303. title={Locale.Chat.Actions.FullScreen}
  1304. aria={Locale.Chat.Actions.FullScreen}
  1305. onClick={() => {
  1306. config.update(
  1307. (config) => (config.tightBorder = !config.tightBorder),
  1308. );
  1309. }}
  1310. />
  1311. </div>
  1312. )}
  1313. </div>
  1314. <PromptToast
  1315. showToast={!hitBottom}
  1316. showModal={showPromptModal}
  1317. setShowModal={setShowPromptModal}
  1318. />
  1319. </div>
  1320. <div
  1321. className={styles["chat-body"]}
  1322. ref={scrollRef}
  1323. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1324. onMouseDown={() => inputRef.current?.blur()}
  1325. onTouchStart={() => {
  1326. inputRef.current?.blur();
  1327. setAutoScroll(false);
  1328. }}
  1329. >
  1330. {messages.map((message, i) => {
  1331. const isUser = message.role === "user";
  1332. const isContext = i < context.length;
  1333. const showActions =
  1334. i > 0 &&
  1335. !(message.preview || message.content.length === 0) &&
  1336. !isContext;
  1337. const showTyping = message.preview || message.streaming;
  1338. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1339. return (
  1340. <Fragment key={message.id}>
  1341. <div
  1342. className={
  1343. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1344. }
  1345. >
  1346. <div className={styles["chat-message-container"]}>
  1347. <div className={styles["chat-message-header"]}>
  1348. <div className={styles["chat-message-avatar"]}>
  1349. <div className={styles["chat-message-edit"]}>
  1350. <IconButton
  1351. icon={<EditIcon />}
  1352. aria={Locale.Chat.Actions.Edit}
  1353. onClick={async () => {
  1354. const newMessage = await showPrompt(
  1355. Locale.Chat.Actions.Edit,
  1356. getMessageTextContent(message),
  1357. 10,
  1358. );
  1359. let newContent: string | MultimodalContent[] =
  1360. newMessage;
  1361. const images = getMessageImages(message);
  1362. if (images.length > 0) {
  1363. newContent = [{ type: "text", text: newMessage }];
  1364. for (let i = 0; i < images.length; i++) {
  1365. newContent.push({
  1366. type: "image_url",
  1367. image_url: {
  1368. url: images[i],
  1369. },
  1370. });
  1371. }
  1372. }
  1373. chatStore.updateCurrentSession((session) => {
  1374. const m = session.mask.context
  1375. .concat(session.messages)
  1376. .find((m) => m.id === message.id);
  1377. if (m) {
  1378. m.content = newContent;
  1379. }
  1380. });
  1381. }}
  1382. ></IconButton>
  1383. </div>
  1384. {isUser ? (
  1385. <Avatar avatar={config.avatar} />
  1386. ) : (
  1387. <>
  1388. {["system"].includes(message.role) ? (
  1389. <Avatar avatar="2699-fe0f" />
  1390. ) : (
  1391. <MaskAvatar
  1392. avatar={session.mask.avatar}
  1393. model={
  1394. message.model || session.mask.modelConfig.model
  1395. }
  1396. />
  1397. )}
  1398. </>
  1399. )}
  1400. </div>
  1401. {!isUser && (
  1402. <div className={styles["chat-model-name"]}>
  1403. {message.model}
  1404. </div>
  1405. )}
  1406. {showActions && (
  1407. <div className={styles["chat-message-actions"]}>
  1408. <div className={styles["chat-input-actions"]}>
  1409. {message.streaming ? (
  1410. <ChatAction
  1411. text={Locale.Chat.Actions.Stop}
  1412. icon={<StopIcon />}
  1413. onClick={() => onUserStop(message.id ?? i)}
  1414. />
  1415. ) : (
  1416. <>
  1417. <ChatAction
  1418. text={Locale.Chat.Actions.Retry}
  1419. icon={<ResetIcon />}
  1420. onClick={() => onResend(message)}
  1421. />
  1422. <ChatAction
  1423. text={Locale.Chat.Actions.Delete}
  1424. icon={<DeleteIcon />}
  1425. onClick={() => onDelete(message.id ?? i)}
  1426. />
  1427. <ChatAction
  1428. text={Locale.Chat.Actions.Pin}
  1429. icon={<PinIcon />}
  1430. onClick={() => onPinMessage(message)}
  1431. />
  1432. <ChatAction
  1433. text={Locale.Chat.Actions.Copy}
  1434. icon={<CopyIcon />}
  1435. onClick={() =>
  1436. copyToClipboard(
  1437. getMessageTextContent(message),
  1438. )
  1439. }
  1440. />
  1441. </>
  1442. )}
  1443. </div>
  1444. </div>
  1445. )}
  1446. </div>
  1447. {message?.tools?.length == 0 && showTyping && (
  1448. <div className={styles["chat-message-status"]}>
  1449. {Locale.Chat.Typing}
  1450. </div>
  1451. )}
  1452. {/*@ts-ignore*/}
  1453. {message?.tools?.length > 0 && (
  1454. <div className={styles["chat-message-tools"]}>
  1455. {message?.tools?.map((tool) => (
  1456. <div
  1457. key={tool.id}
  1458. className={styles["chat-message-tool"]}
  1459. >
  1460. {tool.isError === false ? (
  1461. <ConfirmIcon />
  1462. ) : tool.isError === true ? (
  1463. <CloseIcon />
  1464. ) : (
  1465. <LoadingButtonIcon />
  1466. )}
  1467. <span>{tool?.function?.name}</span>
  1468. </div>
  1469. ))}
  1470. </div>
  1471. )}
  1472. <div className={styles["chat-message-item"]}>
  1473. <Markdown
  1474. key={message.streaming ? "loading" : "done"}
  1475. content={getMessageTextContent(message)}
  1476. loading={
  1477. (message.preview || message.streaming) &&
  1478. message.content.length === 0 &&
  1479. !isUser
  1480. }
  1481. // onContextMenu={(e) => onRightClick(e, message)} // hard to use
  1482. onDoubleClickCapture={() => {
  1483. if (!isMobileScreen) return;
  1484. setUserInput(getMessageTextContent(message));
  1485. }}
  1486. fontSize={fontSize}
  1487. fontFamily={fontFamily}
  1488. parentRef={scrollRef}
  1489. defaultShow={i >= messages.length - 6}
  1490. />
  1491. {getMessageImages(message).length == 1 && (
  1492. <img
  1493. className={styles["chat-message-item-image"]}
  1494. src={getMessageImages(message)[0]}
  1495. alt=""
  1496. />
  1497. )}
  1498. {getMessageImages(message).length > 1 && (
  1499. <div
  1500. className={styles["chat-message-item-images"]}
  1501. style={
  1502. {
  1503. "--image-count": getMessageImages(message).length,
  1504. } as React.CSSProperties
  1505. }
  1506. >
  1507. {getMessageImages(message).map((image, index) => {
  1508. return (
  1509. <img
  1510. className={
  1511. styles["chat-message-item-image-multi"]
  1512. }
  1513. key={index}
  1514. src={image}
  1515. alt=""
  1516. />
  1517. );
  1518. })}
  1519. </div>
  1520. )}
  1521. </div>
  1522. <div className={styles["chat-message-action-date"]}>
  1523. {isContext
  1524. ? Locale.Chat.IsContext
  1525. : message.date.toLocaleString()}
  1526. </div>
  1527. </div>
  1528. </div>
  1529. {shouldShowClearContextDivider && <ClearContextDivider />}
  1530. </Fragment>
  1531. );
  1532. })}
  1533. </div>
  1534. <div className={styles["chat-input-panel"]}>
  1535. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  1536. <ChatActions
  1537. uploadImage={uploadImage}
  1538. setAttachImages={setAttachImages}
  1539. setUploading={setUploading}
  1540. showPromptModal={() => setShowPromptModal(true)}
  1541. scrollToBottom={scrollToBottom}
  1542. hitBottom={hitBottom}
  1543. uploading={uploading}
  1544. showPromptHints={() => {
  1545. // Click again to close
  1546. if (promptHints.length > 0) {
  1547. setPromptHints([]);
  1548. return;
  1549. }
  1550. inputRef.current?.focus();
  1551. setUserInput("/");
  1552. onSearch("");
  1553. }}
  1554. />
  1555. <label
  1556. className={`${styles["chat-input-panel-inner"]} ${
  1557. attachImages.length != 0
  1558. ? styles["chat-input-panel-inner-attach"]
  1559. : ""
  1560. }`}
  1561. htmlFor="chat-input"
  1562. >
  1563. <textarea
  1564. id="chat-input"
  1565. ref={inputRef}
  1566. className={styles["chat-input"]}
  1567. placeholder={Locale.Chat.Input(submitKey)}
  1568. onInput={(e) => onInput(e.currentTarget.value)}
  1569. value={userInput}
  1570. onKeyDown={onInputKeyDown}
  1571. onFocus={scrollToBottom}
  1572. onClick={scrollToBottom}
  1573. onPaste={handlePaste}
  1574. rows={inputRows}
  1575. autoFocus={autoFocus}
  1576. style={{
  1577. fontSize: config.fontSize,
  1578. fontFamily: config.fontFamily,
  1579. }}
  1580. />
  1581. {attachImages.length != 0 && (
  1582. <div className={styles["attach-images"]}>
  1583. {attachImages.map((image, index) => {
  1584. return (
  1585. <div
  1586. key={index}
  1587. className={styles["attach-image"]}
  1588. style={{ backgroundImage: `url("${image}")` }}
  1589. >
  1590. <div className={styles["attach-image-mask"]}>
  1591. <DeleteImageButton
  1592. deleteImage={() => {
  1593. setAttachImages(
  1594. attachImages.filter((_, i) => i !== index),
  1595. );
  1596. }}
  1597. />
  1598. </div>
  1599. </div>
  1600. );
  1601. })}
  1602. </div>
  1603. )}
  1604. <IconButton
  1605. icon={<SendWhiteIcon />}
  1606. text={Locale.Chat.Send}
  1607. className={styles["chat-input-send"]}
  1608. type="primary"
  1609. onClick={() => doSubmit(userInput)}
  1610. />
  1611. </label>
  1612. </div>
  1613. {showExport && (
  1614. <ExportMessageModal onClose={() => setShowExport(false)} />
  1615. )}
  1616. {isEditingMessage && (
  1617. <EditMessageModal
  1618. onClose={() => {
  1619. setIsEditingMessage(false);
  1620. }}
  1621. />
  1622. )}
  1623. </div>
  1624. );
  1625. }
  1626. export function Chat() {
  1627. const chatStore = useChatStore();
  1628. const sessionIndex = chatStore.currentSessionIndex;
  1629. return <_Chat key={sessionIndex}></_Chat>;
  1630. }