chat.tsx 62 KB

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