chat.tsx 59 KB

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