chat.tsx 53 KB

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