chat.tsx 59 KB

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