chat.tsx 54 KB

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