chat.tsx 58 KB

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