chat.tsx 70 KB

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