chat.tsx 54 KB

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