chat.tsx 54 KB

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