chat.tsx 58 KB

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