chat.tsx 62 KB

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