chat.tsx 62 KB

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