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. 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 isUnavailableModel = !models.some((m) => m.name === currentModel);
  476. if (isUnavailableModel && 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. fork: () => chatStore.forkSession(),
  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. }