chat.tsx 59 KB

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