chat.tsx 70 KB

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