chat.tsx 56 KB

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