chat.tsx 57 KB

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