chat.tsx 51 KB

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