chat.tsx 59 KB

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