chat.tsx 75 KB

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