chat.tsx 59 KB

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