chat.tsx 57 KB

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