chat.tsx 62 KB

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