chat.tsx 54 KB

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