chat.tsx 62 KB

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