chat.tsx 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  1. import { useDebouncedCallback } from "use-debounce";
  2. import React, {
  3. useState,
  4. useRef,
  5. useEffect,
  6. useMemo,
  7. useCallback,
  8. Fragment,
  9. RefObject,
  10. } from "react";
  11. import SendWhiteIcon from "../icons/send-white.svg";
  12. import BrainIcon from "../icons/brain.svg";
  13. import RenameIcon from "../icons/rename.svg";
  14. import ExportIcon from "../icons/share.svg";
  15. import ReturnIcon from "../icons/return.svg";
  16. import CopyIcon from "../icons/copy.svg";
  17. import faviconSrc from "../icons/favicon.png";
  18. import LeftIcon from "../icons/left.svg";
  19. import Favicon from "../icons/favicon.svg";
  20. import LoadingIcon from "../icons/three-dots.svg";
  21. import LoadingButtonIcon from "../icons/loading.svg";
  22. import PromptIcon from "../icons/prompt.svg";
  23. import MaskIcon from "../icons/mask.svg";
  24. import MaxIcon from "../icons/max.svg";
  25. import MinIcon from "../icons/min.svg";
  26. import ResetIcon from "../icons/reload.svg";
  27. import BreakIcon from "../icons/break.svg";
  28. import SettingsIcon from "../icons/chat-settings.svg";
  29. import DeleteIcon from "../icons/clear.svg";
  30. import PinIcon from "../icons/pin.svg";
  31. import EditIcon from "../icons/rename.svg";
  32. import ConfirmIcon from "../icons/confirm.svg";
  33. import CancelIcon from "../icons/cancel.svg";
  34. import ImageIcon from "../icons/image.svg";
  35. import LightIcon from "../icons/light.svg";
  36. import DarkIcon from "../icons/dark.svg";
  37. import AutoIcon from "../icons/auto.svg";
  38. import BottomIcon from "../icons/bottom.svg";
  39. import StopIcon from "../icons/pause.svg";
  40. import RobotIcon from "../icons/robot.svg";
  41. import AddIcon from "../icons/add.svg";
  42. import SizeIcon from "../icons/size.svg";
  43. import PluginIcon from "../icons/plugin.svg";
  44. import {
  45. ChatMessage,
  46. SubmitKey,
  47. useChatStore,
  48. BOT_HELLO,
  49. createMessage,
  50. useAccessStore,
  51. Theme,
  52. useAppConfig,
  53. DEFAULT_TOPIC,
  54. ModelType,
  55. } from "../store";
  56. import {
  57. copyToClipboard,
  58. selectOrCopy,
  59. autoGrowTextArea,
  60. useMobileScreen,
  61. getMessageTextContent,
  62. getMessageImages,
  63. isVisionModel,
  64. isDalle3,
  65. } from "../utils";
  66. import { uploadImage as uploadImageRemote } from "@/app/utils/chat";
  67. import dynamic from "next/dynamic";
  68. import { ChatControllerPool } from "../client/controller";
  69. import { DalleSize } from "../typing";
  70. import { Prompt, usePromptStore } from "../store/prompt";
  71. import { useGlobalStore } from "../store";
  72. import Locale from "../locales";
  73. import { IconButton } from "./button";
  74. import styles from "./chat.module.scss";
  75. import {
  76. List,
  77. ListItem,
  78. Modal,
  79. Selector,
  80. showConfirm,
  81. showPrompt,
  82. showToast,
  83. } from "./ui-lib";
  84. import { useNavigate } from "react-router-dom";
  85. import {
  86. CHAT_PAGE_SIZE,
  87. LAST_INPUT_KEY,
  88. Path,
  89. REQUEST_TIMEOUT_MS,
  90. UNFINISHED_INPUT,
  91. ServiceProvider,
  92. Plugin,
  93. } from "../constant";
  94. import { Avatar } from "./emoji";
  95. import { ContextPrompts, MaskAvatar, MaskConfig } from "./mask";
  96. import { useMaskStore } from "../store/mask";
  97. import { ChatCommandPrefix, useChatCommand, useCommand } from "../command";
  98. import { prettyObject } from "../utils/format";
  99. import { ExportMessageModal } from "./exporter";
  100. import { getClientConfig } from "../config/client";
  101. import { useAllModels } from "../utils/hooks";
  102. import { Select } from 'antd';
  103. import { RightOutlined } from '@ant-design/icons';
  104. import api from "@/app/api/api";
  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 globalStore = useGlobalStore();
  838. type QuestionList = any[];
  839. const [questionList, setQuestionList] = useState<QuestionList>([]);
  840. useEffect(() => {
  841. console.log(questionList, 'questionList');
  842. }, [questionList]);
  843. // 获取应用列表
  844. const fetchApplicationList = async () => {
  845. setLoading(true);
  846. try {
  847. const res = await api.get('/bigmodel/api/application/list');
  848. const list = res.data.filter((item: any) => item.appId !== '1234567890123456789').map((item: any) => {
  849. return {
  850. label: item.name,
  851. value: item.appId,
  852. }
  853. })
  854. setAppList(list);
  855. let newAppValue = '';
  856. setAppValue(list[0]?.value);
  857. newAppValue = list[0]?.value;
  858. globalStore.setSelectedAppId(newAppValue);
  859. chatStore.updateCurrentSession((session) => (session.appId = newAppValue));
  860. } catch (error) {
  861. console.error(error);
  862. } finally {
  863. setLoading(false);
  864. }
  865. }
  866. const fetchDefaultQuestion = async () => {
  867. try {
  868. const res = await api.get('/bigmodel/api/presets');
  869. setQuestionList(res.data);
  870. } catch (error) {
  871. console.error(error);
  872. } finally {
  873. setLoading(false);
  874. }
  875. }
  876. const init = async () => {
  877. await fetchApplicationList();
  878. await fetchDefaultQuestion();
  879. }
  880. useEffect(() => {
  881. init();
  882. }, [])
  883. const [inputRows, setInputRows] = useState(2);
  884. const measure = useDebouncedCallback(
  885. () => {
  886. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  887. const inputRows = Math.min(
  888. 20,
  889. Math.max(2 + Number(!isMobileScreen), rows),
  890. );
  891. setInputRows(inputRows);
  892. },
  893. 100,
  894. {
  895. leading: true,
  896. trailing: true,
  897. },
  898. );
  899. // eslint-disable-next-line react-hooks/exhaustive-deps
  900. useEffect(measure, [userInput]);
  901. // chat commands shortcuts
  902. const chatCommands = useChatCommand({
  903. new: () => chatStore.newSession(),
  904. newm: () => navigate(Path.NewChat),
  905. prev: () => chatStore.nextSession(-1),
  906. next: () => chatStore.nextSession(1),
  907. clear: () =>
  908. chatStore.updateCurrentSession(
  909. (session) => (session.clearContextIndex = session.messages.length),
  910. ),
  911. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  912. });
  913. // only search prompts when user input is short
  914. const SEARCH_TEXT_LIMIT = 30;
  915. const onInput = (text: string) => {
  916. setUserInput(text);
  917. const n = text.trim().length;
  918. // clear search results
  919. if (n === 0) {
  920. setPromptHints([]);
  921. } else if (text.match(ChatCommandPrefix)) {
  922. setPromptHints(chatCommands.search(text));
  923. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  924. // check if need to trigger auto completion
  925. if (text.startsWith("/")) {
  926. let searchText = text.slice(1);
  927. onSearch(searchText);
  928. }
  929. }
  930. };
  931. const doSubmit = (userInput: string) => {
  932. if (userInput.trim() === "") return;
  933. const matchCommand = chatCommands.match(userInput);
  934. if (matchCommand.matched) {
  935. setUserInput("");
  936. setPromptHints([]);
  937. matchCommand.invoke();
  938. return;
  939. }
  940. setIsLoading(true);
  941. chatStore.onUserInput(userInput, attachImages).then(() => setIsLoading(false));
  942. setAttachImages([]);
  943. localStorage.setItem(LAST_INPUT_KEY, userInput);
  944. setUserInput("");
  945. setPromptHints([]);
  946. if (!isMobileScreen) inputRef.current?.focus();
  947. setAutoScroll(true);
  948. };
  949. const onPromptSelect = (prompt: RenderPrompt) => {
  950. setTimeout(() => {
  951. setPromptHints([]);
  952. const matchedChatCommand = chatCommands.match(prompt.content);
  953. if (matchedChatCommand.matched) {
  954. // if user is selecting a chat command, just trigger it
  955. matchedChatCommand.invoke();
  956. setUserInput("");
  957. } else {
  958. // or fill the prompt
  959. setUserInput(prompt.content);
  960. }
  961. inputRef.current?.focus();
  962. }, 30);
  963. };
  964. // stop response
  965. const onUserStop = (messageId: string) => {
  966. ChatControllerPool.stop(session.id, messageId);
  967. };
  968. useEffect(() => {
  969. chatStore.updateCurrentSession((session) => {
  970. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  971. session.messages.forEach((m) => {
  972. // check if should stop all stale messages
  973. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  974. if (m.streaming) {
  975. m.streaming = false;
  976. }
  977. if (m.content.length === 0) {
  978. m.isError = true;
  979. m.content = prettyObject({
  980. error: true,
  981. message: "empty response",
  982. });
  983. }
  984. }
  985. });
  986. // auto sync mask config from global config
  987. if (session.mask.syncGlobalConfig) {
  988. console.log("[Mask] syncing from global, name = ", session.mask.name);
  989. session.mask.modelConfig = { ...config.modelConfig };
  990. }
  991. });
  992. // eslint-disable-next-line react-hooks/exhaustive-deps
  993. }, []);
  994. // check if should send message
  995. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  996. if (
  997. e.key === "ArrowUp" &&
  998. userInput.length <= 0 &&
  999. !(e.metaKey || e.altKey || e.ctrlKey)
  1000. ) {
  1001. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  1002. e.preventDefault();
  1003. return;
  1004. }
  1005. if (shouldSubmit(e) && promptHints.length === 0) {
  1006. doSubmit(userInput);
  1007. e.preventDefault();
  1008. }
  1009. };
  1010. const onRightClick = (e: any, message: ChatMessage) => {
  1011. // copy to clipboard
  1012. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  1013. if (userInput.length === 0) {
  1014. setUserInput(getMessageTextContent(message));
  1015. }
  1016. e.preventDefault();
  1017. }
  1018. };
  1019. const deleteMessage = (msgId?: string) => {
  1020. chatStore.updateCurrentSession(
  1021. (session) =>
  1022. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  1023. );
  1024. };
  1025. const onDelete = (msgId: string) => {
  1026. deleteMessage(msgId);
  1027. };
  1028. const onResend = (message: ChatMessage) => {
  1029. // when it is resending a message
  1030. // 1. for a user's message, find the next bot response
  1031. // 2. for a bot's message, find the last user's input
  1032. // 3. delete original user input and bot's message
  1033. // 4. resend the user's input
  1034. const resendingIndex = session.messages.findIndex(
  1035. (m) => m.id === message.id,
  1036. );
  1037. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  1038. console.error("[Chat] failed to find resending message", message);
  1039. return;
  1040. }
  1041. let userMessage: ChatMessage | undefined;
  1042. let botMessage: ChatMessage | undefined;
  1043. if (message.role === "assistant") {
  1044. // if it is resending a bot's message, find the user input for it
  1045. botMessage = message;
  1046. for (let i = resendingIndex; i >= 0; i -= 1) {
  1047. if (session.messages[i].role === "user") {
  1048. userMessage = session.messages[i];
  1049. break;
  1050. }
  1051. }
  1052. } else if (message.role === "user") {
  1053. // if it is resending a user's input, find the bot's response
  1054. userMessage = message;
  1055. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  1056. if (session.messages[i].role === "assistant") {
  1057. botMessage = session.messages[i];
  1058. break;
  1059. }
  1060. }
  1061. }
  1062. if (userMessage === undefined) {
  1063. console.error("[Chat] failed to resend", message);
  1064. return;
  1065. }
  1066. // delete the original messages
  1067. deleteMessage(userMessage.id);
  1068. deleteMessage(botMessage?.id);
  1069. // resend the message
  1070. setIsLoading(true);
  1071. const textContent = getMessageTextContent(userMessage);
  1072. const images = getMessageImages(userMessage);
  1073. chatStore.onUserInput(textContent, images).then(() => setIsLoading(false));
  1074. inputRef.current?.focus();
  1075. };
  1076. const onPinMessage = (message: ChatMessage) => {
  1077. chatStore.updateCurrentSession((session) =>
  1078. session.mask.context.push(message),
  1079. );
  1080. showToast(Locale.Chat.Actions.PinToastContent, {
  1081. text: Locale.Chat.Actions.PinToastAction,
  1082. onClick: () => {
  1083. setShowPromptModal(true);
  1084. },
  1085. });
  1086. };
  1087. const context: RenderMessage[] = useMemo(() => {
  1088. return session.mask.hideContext ? [] : session.mask.context.slice();
  1089. }, [session.mask.context, session.mask.hideContext]);
  1090. const accessStore = useAccessStore();
  1091. if (
  1092. context.length === 0 &&
  1093. session.messages.at(0)?.content !== BOT_HELLO.content
  1094. ) {
  1095. const copiedHello = Object.assign({}, BOT_HELLO);
  1096. if (!accessStore.isAuthorized()) {
  1097. copiedHello.content = Locale.Error.Unauthorized;
  1098. }
  1099. context.push(copiedHello);
  1100. }
  1101. // preview messages
  1102. const renderMessages = useMemo(() => {
  1103. return context.concat(session.messages as RenderMessage[]).concat(
  1104. isLoading
  1105. ? [
  1106. {
  1107. ...createMessage({
  1108. role: "assistant",
  1109. content: "……",
  1110. }),
  1111. preview: true,
  1112. },
  1113. ]
  1114. : [],
  1115. ).concat(
  1116. userInput.length > 0 && config.sendPreviewBubble
  1117. ? [
  1118. {
  1119. ...createMessage({
  1120. role: "user",
  1121. content: userInput,
  1122. }),
  1123. preview: true,
  1124. },
  1125. ]
  1126. : [],
  1127. );
  1128. }, [
  1129. config.sendPreviewBubble,
  1130. context,
  1131. isLoading,
  1132. session.messages,
  1133. userInput,
  1134. ]);
  1135. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  1136. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1137. );
  1138. function setMsgRenderIndex(newIndex: number) {
  1139. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1140. newIndex = Math.max(0, newIndex);
  1141. _setMsgRenderIndex(newIndex);
  1142. }
  1143. const messages = useMemo(() => {
  1144. const endRenderIndex = Math.min(
  1145. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1146. renderMessages.length,
  1147. );
  1148. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1149. }, [msgRenderIndex, renderMessages]);
  1150. const onChatBodyScroll = (e: HTMLElement) => {
  1151. const bottomHeight = e.scrollTop + e.clientHeight;
  1152. const edgeThreshold = e.clientHeight;
  1153. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1154. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1155. const isHitBottom =
  1156. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1157. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1158. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1159. if (isTouchTopEdge && !isTouchBottomEdge) {
  1160. setMsgRenderIndex(prevPageMsgIndex);
  1161. } else if (isTouchBottomEdge) {
  1162. setMsgRenderIndex(nextPageMsgIndex);
  1163. }
  1164. setHitBottom(isHitBottom);
  1165. setAutoScroll(isHitBottom);
  1166. };
  1167. function scrollToBottom() {
  1168. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1169. scrollDomToBottom();
  1170. }
  1171. // clear context index = context length + index in messages
  1172. const clearContextIndex =
  1173. (session.clearContextIndex ?? -1) >= 0
  1174. ? session.clearContextIndex! + context.length - msgRenderIndex
  1175. : -1;
  1176. const [showPromptModal, setShowPromptModal] = useState(false);
  1177. const clientConfig = useMemo(() => getClientConfig(), []);
  1178. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1179. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1180. useCommand({
  1181. fill: setUserInput,
  1182. submit: (text) => {
  1183. doSubmit(text);
  1184. },
  1185. code: (text) => {
  1186. if (accessStore.disableFastLink) return;
  1187. console.log("[Command] got code from url: ", text);
  1188. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1189. if (res) {
  1190. accessStore.update((access) => (access.accessCode = text));
  1191. }
  1192. });
  1193. },
  1194. settings: (text) => {
  1195. if (accessStore.disableFastLink) return;
  1196. try {
  1197. const payload = JSON.parse(text) as {
  1198. key?: string;
  1199. url?: string;
  1200. };
  1201. console.log("[Command] got settings from url: ", payload);
  1202. if (payload.key || payload.url) {
  1203. showConfirm(
  1204. Locale.URLCommand.Settings +
  1205. `\n${JSON.stringify(payload, null, 4)}`,
  1206. ).then((res) => {
  1207. if (!res) return;
  1208. if (payload.key) {
  1209. accessStore.update(
  1210. (access) => (access.openaiApiKey = payload.key!),
  1211. );
  1212. }
  1213. if (payload.url) {
  1214. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1215. }
  1216. accessStore.update((access) => (access.useCustomConfig = true));
  1217. });
  1218. }
  1219. } catch {
  1220. console.error("[Command] failed to get settings from url: ", text);
  1221. }
  1222. },
  1223. });
  1224. // edit / insert message modal
  1225. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1226. // remember unfinished input
  1227. useEffect(() => {
  1228. // try to load from local storage
  1229. const key = UNFINISHED_INPUT(session.id);
  1230. const mayBeUnfinishedInput = localStorage.getItem(key);
  1231. if (mayBeUnfinishedInput && userInput.length === 0) {
  1232. setUserInput(mayBeUnfinishedInput);
  1233. localStorage.removeItem(key);
  1234. }
  1235. const dom = inputRef.current;
  1236. return () => {
  1237. localStorage.setItem(key, dom?.value ?? "");
  1238. };
  1239. // eslint-disable-next-line react-hooks/exhaustive-deps
  1240. }, []);
  1241. const handlePaste = useCallback(
  1242. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1243. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1244. if (!isVisionModel(currentModel)) {
  1245. return;
  1246. }
  1247. const items = (event.clipboardData || window.clipboardData).items;
  1248. for (const item of items) {
  1249. if (item.kind === "file" && item.type.startsWith("image/")) {
  1250. event.preventDefault();
  1251. const file = item.getAsFile();
  1252. if (file) {
  1253. const images: string[] = [];
  1254. images.push(...attachImages);
  1255. images.push(
  1256. ...(await new Promise<string[]>((res, rej) => {
  1257. setUploading(true);
  1258. const imagesData: string[] = [];
  1259. uploadImageRemote(file).then((dataUrl) => {
  1260. imagesData.push(dataUrl);
  1261. setUploading(false);
  1262. res(imagesData);
  1263. }).catch((e) => {
  1264. setUploading(false);
  1265. rej(e);
  1266. });
  1267. })),
  1268. );
  1269. const imagesLength = images.length;
  1270. if (imagesLength > 3) {
  1271. images.splice(3, imagesLength - 3);
  1272. }
  1273. setAttachImages(images);
  1274. }
  1275. }
  1276. }
  1277. },
  1278. [attachImages, chatStore],
  1279. );
  1280. async function uploadImage() {
  1281. const images: string[] = [];
  1282. images.push(...attachImages);
  1283. images.push(
  1284. ...(await new Promise<string[]>((res, rej) => {
  1285. const fileInput = document.createElement("input");
  1286. fileInput.type = "file";
  1287. fileInput.accept =
  1288. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1289. fileInput.multiple = true;
  1290. fileInput.onchange = (event: any) => {
  1291. setUploading(true);
  1292. const files = event.target.files;
  1293. const imagesData: string[] = [];
  1294. for (let i = 0; i < files.length; i++) {
  1295. const file = event.target.files[i];
  1296. uploadImageRemote(file).then((dataUrl) => {
  1297. imagesData.push(dataUrl);
  1298. if (
  1299. imagesData.length === 3 ||
  1300. imagesData.length === files.length
  1301. ) {
  1302. setUploading(false);
  1303. res(imagesData);
  1304. }
  1305. }).catch((e) => {
  1306. setUploading(false);
  1307. rej(e);
  1308. });
  1309. }
  1310. };
  1311. fileInput.click();
  1312. })),
  1313. );
  1314. const imagesLength = images.length;
  1315. if (imagesLength > 3) {
  1316. images.splice(3, imagesLength - 3);
  1317. }
  1318. setAttachImages(images);
  1319. }
  1320. const getAppName = () => {
  1321. const item = appList.find(item => item.value === appValue);
  1322. if (!item) {
  1323. return
  1324. }
  1325. return item.label;
  1326. }
  1327. return (
  1328. <div className={styles.chat} key={session.id}>
  1329. <div className="window-header" data-tauri-drag-region>
  1330. {/* {isMobileScreen && (
  1331. <div className="window-actions">
  1332. <div className={"window-action-button"}>
  1333. <IconButton
  1334. icon={<ReturnIcon />}
  1335. bordered
  1336. title={Locale.Chat.Actions.ChatList}
  1337. onClick={() => navigate(Path.Home)}
  1338. />
  1339. </div>
  1340. </div>
  1341. )} */}
  1342. <div style={{ display: 'flex', alignItems: 'center' }}
  1343. className={`window-header-title ${styles["chat-body-title"]}`}>
  1344. <div>
  1345. {
  1346. isMobileScreen &&
  1347. <IconButton
  1348. style={{ padding: 0, marginRight: 20 }}
  1349. icon={<LeftIcon />}
  1350. text={Locale.NewChat.Return}
  1351. onClick={() => navigate(Path.Home)}
  1352. />
  1353. }
  1354. </div>
  1355. <div>
  1356. {
  1357. appList.length > 1 ?
  1358. <Select
  1359. style={{ width: '100%', height: 38, marginRight: 5 }}
  1360. placeholder='请选择'
  1361. options={appList}
  1362. value={appValue}
  1363. onChange={(value) => {
  1364. setAppValue(value);
  1365. globalStore.setSelectedAppId(value);
  1366. chatStore.clearSessions();
  1367. chatStore.updateCurrentSession((values) => {
  1368. values.appId = value;
  1369. });
  1370. }}
  1371. />
  1372. :
  1373. null
  1374. }
  1375. </div>
  1376. </div>
  1377. <div className="window-actions">
  1378. {/* <IconButton
  1379. icon={<AddIcon />}
  1380. bordered
  1381. title='新建对话'
  1382. aria='新建对话'
  1383. onClick={() => {
  1384. localStorage.clear()
  1385. location.reload()
  1386. }}
  1387. /> */}
  1388. {/* {!isMobileScreen && (
  1389. <div className="window-action-button">
  1390. <IconButton
  1391. icon={<RenameIcon />}
  1392. bordered
  1393. title={Locale.Chat.EditMessage.Title}
  1394. aria={Locale.Chat.EditMessage.Title}
  1395. onClick={() => setIsEditingMessage(true)}
  1396. />
  1397. </div>
  1398. )} */}
  1399. <div className="window-action-button">
  1400. <IconButton
  1401. icon={<ExportIcon />}
  1402. bordered
  1403. title={Locale.Chat.Actions.Export}
  1404. onClick={() => {
  1405. // setShowExport(true);
  1406. console.log('分享聊天记录');
  1407. }}
  1408. />
  1409. </div>
  1410. {/* {showMaxIcon && (
  1411. <div className="window-action-button">
  1412. <IconButton
  1413. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1414. bordered
  1415. title={Locale.Chat.Actions.FullScreen}
  1416. aria={Locale.Chat.Actions.FullScreen}
  1417. onClick={() => {
  1418. config.update(
  1419. (config) => (config.tightBorder = !config.tightBorder),
  1420. );
  1421. }}
  1422. />
  1423. </div>
  1424. )} */}
  1425. </div>
  1426. {/* <PromptToast
  1427. showToast={!hitBottom}
  1428. showModal={showPromptModal}
  1429. setShowModal={setShowPromptModal}
  1430. /> */}
  1431. </div>
  1432. <div
  1433. className={styles["chat-body"]}
  1434. ref={scrollRef}
  1435. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1436. onMouseDown={() => inputRef.current?.blur()}
  1437. onTouchStart={() => {
  1438. inputRef.current?.blur();
  1439. setAutoScroll(false);
  1440. }}
  1441. >
  1442. {
  1443. messages.length > 1 ?
  1444. <>
  1445. {messages.map((message, i) => {
  1446. const isUser = message.role === "user";
  1447. const isContext = i < context.length;
  1448. const showActions =
  1449. i > 0 &&
  1450. !(message.preview || message.content.length === 0) &&
  1451. !isContext;
  1452. const showTyping = message.preview || message.streaming;
  1453. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1454. return (
  1455. <Fragment key={message.id}>
  1456. <div
  1457. className={
  1458. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1459. }
  1460. >
  1461. <div className={styles["chat-message-container"]}>
  1462. <div className={styles["chat-message-header"]}>
  1463. <div className={styles["chat-message-avatar"]}>
  1464. {/* <div className={styles["chat-message-edit"]}>
  1465. <IconButton
  1466. icon={<EditIcon />}
  1467. aria={Locale.Chat.Actions.Edit}
  1468. onClick={async () => {
  1469. const newMessage = await showPrompt(
  1470. Locale.Chat.Actions.Edit,
  1471. getMessageTextContent(message),
  1472. 10,
  1473. );
  1474. let newContent: string | MultimodalContent[] =
  1475. newMessage;
  1476. const images = getMessageImages(message);
  1477. if (images.length > 0) {
  1478. newContent = [{ type: "text", text: newMessage }];
  1479. for (let i = 0; i < images.length; i++) {
  1480. newContent.push({
  1481. type: "image_url",
  1482. image_url: {
  1483. url: images[i],
  1484. },
  1485. });
  1486. }
  1487. }
  1488. chatStore.updateCurrentSession((session) => {
  1489. const m = session.mask.context
  1490. .concat(session.messages)
  1491. .find((m) => m.id === message.id);
  1492. if (m) {
  1493. m.content = newContent;
  1494. }
  1495. });
  1496. }}
  1497. ></IconButton>
  1498. </div> */}
  1499. {isUser ? (
  1500. // 在这里换头像
  1501. <div style={{ position: 'relative' }}>
  1502. {/* <MaskAvatar */}
  1503. {/* avatar={session.mask.avatar} */}
  1504. {/* /> */}
  1505. {/* <div */}
  1506. {/* style={{ */}
  1507. {/* position: 'absolute', */}
  1508. {/* zIndex: 2, */}
  1509. {/* top: '50%', */}
  1510. {/* left: '50%', */}
  1511. {/* transform: ' translate(-50%, -50%)', */}
  1512. {/* fontSize: 14, */}
  1513. {/* }}> */}
  1514. {/* 我 */}
  1515. {/* </div> */}
  1516. <div
  1517. style={{
  1518. position: 'absolute',
  1519. zIndex: 2,
  1520. top: '50%',
  1521. left: '50%',
  1522. transform: ' translate(-110%, -100%)',
  1523. fontSize: 14,
  1524. }}>
  1525. </div>
  1526. </div>
  1527. ) : (
  1528. <>
  1529. {["system"].includes(message.role) ? (
  1530. <Avatar avatar="2699-fe0f" />
  1531. ) : (
  1532. <MaskAvatar
  1533. avatar={session.mask.avatar}
  1534. model={
  1535. message.model || session.mask.modelConfig.model
  1536. }
  1537. />
  1538. )}
  1539. </>
  1540. )}
  1541. </div>
  1542. {/* {showActions && (
  1543. <div className={styles["chat-message-actions"]}>
  1544. <div className={styles["chat-input-actions"]}>
  1545. {message.streaming ? (
  1546. <ChatAction
  1547. text={Locale.Chat.Actions.Stop}
  1548. icon={<StopIcon />}
  1549. onClick={() => onUserStop(message.id ?? i)}
  1550. />
  1551. ) : (
  1552. <>
  1553. <ChatAction
  1554. text={Locale.Chat.Actions.Retry}
  1555. icon={<ResetIcon />}
  1556. onClick={() => onResend(message)}
  1557. />
  1558. <ChatAction
  1559. text={Locale.Chat.Actions.Delete}
  1560. icon={<DeleteIcon />}
  1561. onClick={() => onDelete(message.id ?? i)}
  1562. />
  1563. <ChatAction
  1564. text={Locale.Chat.Actions.Pin}
  1565. icon={<PinIcon />}
  1566. onClick={() => onPinMessage(message)}
  1567. />
  1568. <ChatAction
  1569. text={Locale.Chat.Actions.Copy}
  1570. icon={<CopyIcon />}
  1571. onClick={() =>
  1572. copyToClipboard(
  1573. getMessageTextContent(message),
  1574. )
  1575. }
  1576. />
  1577. </>
  1578. )}
  1579. </div>
  1580. </div>
  1581. )} */}
  1582. </div>
  1583. {showTyping && (
  1584. <div className={styles["chat-message-status"]}>
  1585. {Locale.Chat.Typing}
  1586. </div>
  1587. )}
  1588. <div className={styles["chat-message-item"]}>
  1589. <Markdown
  1590. key={message.streaming ? "loading" : "done"}
  1591. content={getMessageTextContent(message)}
  1592. loading={
  1593. (message.preview || message.streaming) &&
  1594. message.content.length === 0 &&
  1595. !isUser
  1596. }
  1597. // onContextMenu={(e) => onRightClick(e, message)}
  1598. onDoubleClickCapture={() => {
  1599. if (!isMobileScreen) return;
  1600. setUserInput(getMessageTextContent(message));
  1601. }}
  1602. fontSize={fontSize}
  1603. fontFamily={fontFamily}
  1604. parentRef={scrollRef}
  1605. defaultShow={i >= messages.length - 6}
  1606. />
  1607. {getMessageImages(message).length == 1 && (
  1608. <img
  1609. className={styles["chat-message-item-image"]}
  1610. src={getMessageImages(message)[0]}
  1611. alt=""
  1612. />
  1613. )}
  1614. {getMessageImages(message).length > 1 && (
  1615. <div
  1616. className={styles["chat-message-item-images"]}
  1617. style={
  1618. {
  1619. "--image-count": getMessageImages(message).length,
  1620. } as React.CSSProperties
  1621. }
  1622. >
  1623. {getMessageImages(message).map((image, index) => {
  1624. return (
  1625. <img
  1626. className={
  1627. styles["chat-message-item-image-multi"]
  1628. }
  1629. key={index}
  1630. src={image}
  1631. alt=""
  1632. />
  1633. );
  1634. })}
  1635. </div>
  1636. )}
  1637. </div>
  1638. {/* <div className={styles["chat-message-action-date"]}>
  1639. {isContext
  1640. ? Locale.Chat.IsContext
  1641. : message.date.toLocaleString()}
  1642. </div> */}
  1643. </div>
  1644. </div>
  1645. {shouldShowClearContextDivider && <ClearContextDivider />}
  1646. </Fragment>
  1647. );
  1648. })}
  1649. </>
  1650. :
  1651. <>
  1652. <div style={{ position: 'absolute', width: '800px', height: '550px', top: '0', left: '0', right: '0', bottom: '0', margin: 'auto' }}>
  1653. <h1 style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
  1654. {getAppName()}
  1655. </h1>
  1656. <p style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>创建人: admin</p>
  1657. <p style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
  1658. 您好,欢迎使用建科·小智使用知识库创建的
  1659. <span>
  1660. {getAppName()}
  1661. </span>
  1662. </p>
  1663. <p style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>如果需要问本企业相关的其他问题请点击左上角,选中切换的知识库问答应用使用</p>
  1664. <p>我猜您可能想问:</p>
  1665. {
  1666. questionList.map((item) => {
  1667. return (
  1668. <div style={{
  1669. padding: '10px',
  1670. marginBottom: '10px',
  1671. border: '1px solid #e6e8f1',
  1672. borderRadius: '10px',
  1673. fontSize: '16px',
  1674. display: 'flex',
  1675. justifyContent: 'space-between',
  1676. alignItems: 'center',
  1677. cursor: 'pointer'
  1678. }} onClick={() => {
  1679. setUserInput(item)
  1680. }}>
  1681. <div>
  1682. {item}
  1683. </div>
  1684. <RightOutlined />
  1685. </div>
  1686. )
  1687. })
  1688. }
  1689. </div>
  1690. </>
  1691. }
  1692. </div>
  1693. <div className={styles["chat-input-panel"]}>
  1694. {/* <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} /> */}
  1695. <ChatActions
  1696. setUserInput={setUserInput}
  1697. doSubmit={doSubmit}
  1698. uploadImage={uploadImage}
  1699. setAttachImages={setAttachImages}
  1700. setUploading={setUploading}
  1701. showPromptModal={() => setShowPromptModal(true)}
  1702. scrollToBottom={scrollToBottom}
  1703. hitBottom={hitBottom}
  1704. uploading={uploading}
  1705. showPromptHints={() => {
  1706. // Click again to close
  1707. if (promptHints.length > 0) {
  1708. setPromptHints([]);
  1709. return;
  1710. }
  1711. inputRef.current?.focus();
  1712. setUserInput("/");
  1713. onSearch("");
  1714. }}
  1715. />
  1716. <label
  1717. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  1718. ? styles["chat-input-panel-inner-attach"]
  1719. : ""
  1720. }`}
  1721. htmlFor="chat-input"
  1722. >
  1723. <textarea
  1724. id="chat-input"
  1725. ref={inputRef}
  1726. className={styles["chat-input"]}
  1727. placeholder={Locale.Chat.Input(submitKey)}
  1728. onInput={(e) => onInput(e.currentTarget.value)}
  1729. value={userInput}
  1730. onKeyDown={onInputKeyDown}
  1731. onFocus={scrollToBottom}
  1732. onClick={scrollToBottom}
  1733. onPaste={handlePaste}
  1734. rows={inputRows}
  1735. autoFocus={autoFocus}
  1736. style={{
  1737. fontSize: config.fontSize,
  1738. fontFamily: config.fontFamily,
  1739. }}
  1740. />
  1741. {attachImages.length != 0 && (
  1742. <div className={styles["attach-images"]}>
  1743. {attachImages.map((image, index) => {
  1744. return (
  1745. <div
  1746. key={index}
  1747. className={styles["attach-image"]}
  1748. style={{ backgroundImage: `url("${image}")` }}
  1749. >
  1750. <div className={styles["attach-image-mask"]}>
  1751. <DeleteImageButton
  1752. deleteImage={() => {
  1753. setAttachImages(
  1754. attachImages.filter((_, i) => i !== index),
  1755. );
  1756. }}
  1757. />
  1758. </div>
  1759. </div>
  1760. );
  1761. })}
  1762. </div>
  1763. )}
  1764. <IconButton
  1765. icon={<SendWhiteIcon />}
  1766. text='发送'
  1767. className={styles["chat-input-send"]}
  1768. type="primary"
  1769. onClick={() => doSubmit(userInput)}
  1770. />
  1771. </label>
  1772. </div>
  1773. {showExport && (
  1774. <ExportMessageModal onClose={() => setShowExport(false)} />
  1775. )}
  1776. {isEditingMessage && (
  1777. <EditMessageModal
  1778. onClose={() => {
  1779. setIsEditingMessage(false);
  1780. }}
  1781. />
  1782. )}
  1783. </div>
  1784. );
  1785. }
  1786. export function Chat() {
  1787. const chatStore = useChatStore();
  1788. const sessionIndex = chatStore.currentSessionIndex;
  1789. return <_Chat key={sessionIndex}></_Chat>;
  1790. }