chat.tsx 58 KB

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