DeepSeekChat.tsx 47 KB

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