chat.tsx 74 KB

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