chat.tsx 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383
  1. import { useDebouncedCallback } from "use-debounce";
  2. import React, {
  3. useState,
  4. useRef,
  5. useEffect,
  6. useMemo,
  7. useCallback,
  8. Fragment,
  9. RefObject,
  10. } from "react";
  11. import { HomeOutlined, MenuOutlined } from '@ant-design/icons';
  12. import SendWhiteIcon from "../icons/send-white.svg";
  13. import BrainIcon from "../icons/brain.svg";
  14. import RenameIcon from "../icons/rename.svg";
  15. import ExportIcon from "../icons/share.svg";
  16. import ReturnIcon from "../icons/return.svg";
  17. import CopyIcon from "../icons/copy.svg";
  18. import faviconSrc from "../icons/favicon.png";
  19. import LeftIcon from "../icons/left.svg";
  20. import Favicon from "../icons/favicon.svg";
  21. import LoadingIcon from "../icons/three-dots.svg";
  22. import LoadingButtonIcon from "../icons/loading.svg";
  23. import PromptIcon from "../icons/prompt.svg";
  24. import MaskIcon from "../icons/mask.svg";
  25. import MaxIcon from "../icons/max.svg";
  26. import MinIcon from "../icons/min.svg";
  27. import ResetIcon from "../icons/reload.svg";
  28. import BreakIcon from "../icons/break.svg";
  29. import SettingsIcon from "../icons/chat-settings.svg";
  30. import DeleteIcon from "../icons/clear.svg";
  31. import PinIcon from "../icons/pin.svg";
  32. import EditIcon from "../icons/rename.svg";
  33. import ConfirmIcon from "../icons/confirm.svg";
  34. import CancelIcon from "../icons/cancel.svg";
  35. import ImageIcon from "../icons/image.svg";
  36. import LightIcon from "../icons/light.svg";
  37. import DarkIcon from "../icons/dark.svg";
  38. import AutoIcon from "../icons/auto.svg";
  39. import BottomIcon from "../icons/bottom.svg";
  40. import StopIcon from "../icons/pause.svg";
  41. import RobotIcon from "../icons/robot.svg";
  42. import AddIcon from "../icons/add.svg";
  43. import SizeIcon from "../icons/size.svg";
  44. import PluginIcon from "../icons/plugin.svg";
  45. import avatarSrc from "../icons/avatar.png";
  46. import {
  47. ChatMessage,
  48. SubmitKey,
  49. useChatStore,
  50. BOT_HELLO,
  51. createMessage,
  52. useAccessStore,
  53. Theme,
  54. useAppConfig,
  55. DEFAULT_TOPIC,
  56. ModelType,
  57. } from "../store";
  58. import {
  59. copyToClipboard,
  60. selectOrCopy,
  61. autoGrowTextArea,
  62. useMobileScreen,
  63. getMessageTextContent,
  64. getMessageImages,
  65. isVisionModel,
  66. isDalle3,
  67. } from "../utils";
  68. import { uploadImage as uploadImageRemote } from "@/app/utils/chat";
  69. import dynamic from "next/dynamic";
  70. import { ChatControllerPool } from "../client/controller";
  71. import { DalleSize } from "../typing";
  72. import { Prompt, usePromptStore } from "../store/prompt";
  73. import { useGlobalStore } from "../store";
  74. import Locale from "../locales";
  75. import { IconButton } from "./button";
  76. import styles from "./chat.module.scss";
  77. import {
  78. List,
  79. ListItem,
  80. Modal,
  81. Selector,
  82. showConfirm,
  83. showPrompt,
  84. showToast,
  85. } from "./ui-lib";
  86. import { useNavigate, useLocation } from "react-router-dom";
  87. import {
  88. CHAT_PAGE_SIZE,
  89. LAST_INPUT_KEY,
  90. Path,
  91. REQUEST_TIMEOUT_MS,
  92. UNFINISHED_INPUT,
  93. ServiceProvider,
  94. Plugin,
  95. } from "../constant";
  96. 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. const [activeKey, setActiveKey]= useState('0'); // 控制手风琴是否展示
  608. return (
  609. <div className={styles["chat-input-actions"]}>
  610. {
  611. props.sendStatus &&
  612. <Collapse
  613. accordion={true}
  614. activeKey={activeKey}
  615. onChange={(key)=>{setActiveKey(key[0])}}
  616. bordered={false}
  617. style={{ width: '100%',backgroundColor:'#fff' }}
  618. expandIconPosition="end"
  619. items={[
  620. {
  621. key: '1',
  622. label:<span style={{ color: '#8096ca' }}>你还可以尝试提问:</span>,
  623. children: <div style={{ color: '#8096ca', fontSize: 13, overflowX: 'auto' }}>
  624. {/* <div>
  625. 你还可以尝试提问:
  626. </div> */}
  627. {
  628. guessList.length === 0 ?
  629. <Space style={{ margin: '10px 0' }}>
  630. <Skeleton.Button size="small" active={true} />
  631. <Skeleton.Button size="small" active={true} />
  632. <Skeleton.Button size="small" active={true} />
  633. </Space>
  634. :
  635. <div style={{ display: 'flex', margin: '10px 0', overflowX: 'auto' }}>
  636. {
  637. guessList.map((item, index) => {
  638. return (
  639. <div
  640. style={{
  641. padding: '5px 10px',
  642. background: '#f2f4f8',
  643. borderRadius: 5,
  644. margin: '0 10px 10px 0',
  645. cursor: 'pointer',
  646. }}
  647. onClick={() => {
  648. props.setUserInput(item);
  649. props.doSubmit(item)
  650. setActiveKey('')
  651. }}
  652. key={index}
  653. >
  654. {item}
  655. </div>
  656. )
  657. })
  658. }
  659. </div>
  660. }
  661. </div>
  662. }
  663. ]}
  664. />
  665. }
  666. {/* {
  667. props.sendStatus &&
  668. <div style={{ color: '#8096ca', fontSize: 13, overflowX: 'auto' }}>
  669. <div>
  670. 你还可以尝试提问:
  671. </div>
  672. {
  673. guessList.length === 0 ?
  674. <Space style={{ margin: '10px 0' }}>
  675. <Skeleton.Button size="small" active={true} />
  676. <Skeleton.Button size="small" active={true} />
  677. <Skeleton.Button size="small" active={true} />
  678. </Space>
  679. :
  680. <div style={{ display: 'flex', margin: '10px 0', overflowX: 'auto' }}>
  681. {
  682. guessList.map((item, index) => {
  683. return (
  684. <div
  685. style={{
  686. padding: '5px 10px',
  687. background: '#f2f4f8',
  688. borderRadius: 5,
  689. margin: '0 10px 10px 0',
  690. cursor: 'pointer',
  691. }}
  692. onClick={() => {
  693. props.setUserInput(item);
  694. props.doSubmit(item)
  695. }}
  696. key={index}
  697. >
  698. {item}
  699. </div>
  700. )
  701. })
  702. }
  703. </div>
  704. }
  705. </div>
  706. } */}
  707. {/* {couldStop && (
  708. <ChatAction
  709. onClick={stopAll}
  710. text={Locale.Chat.InputActions.Stop}
  711. icon={<StopIcon />}
  712. />
  713. )} */}
  714. {/* {!props.hitBottom && (
  715. <ChatAction
  716. onClick={props.scrollToBottom}
  717. text={Locale.Chat.InputActions.ToBottom}
  718. icon={<BottomIcon />}
  719. />
  720. )} */}
  721. {/* {props.hitBottom && (
  722. <ChatAction
  723. onClick={props.showPromptModal}
  724. text={Locale.Chat.InputActions.Settings}
  725. icon={<SettingsIcon />}
  726. />
  727. )} */}
  728. {/* {showUploadImage && (
  729. <ChatAction
  730. onClick={props.uploadImage}
  731. text={Locale.Chat.InputActions.UploadImage}
  732. icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />}
  733. />
  734. )} */}
  735. {/* <ChatAction
  736. onClick={nextTheme}
  737. text={Locale.Chat.InputActions.Theme[theme]}
  738. icon={
  739. <>
  740. {theme === Theme.Auto ? (
  741. <AutoIcon />
  742. ) : theme === Theme.Light ? (
  743. <LightIcon />
  744. ) : theme === Theme.Dark ? (
  745. <DarkIcon />
  746. ) : null}
  747. </>
  748. }
  749. /> */}
  750. {/* <CallWord */}
  751. {/* setUserInput={props.setUserInput} */}
  752. {/* doSubmit={props.doSubmit} */}
  753. {/* /> */}
  754. {/* <ChatAction
  755. onClick={props.showPromptHints}
  756. text={Locale.Chat.InputActions.Prompt}
  757. icon={<PromptIcon />}
  758. /> */}
  759. {/* <ChatAction
  760. onClick={() => {
  761. navigate(Path.Masks);
  762. }}
  763. text={Locale.Chat.InputActions.Masks}
  764. icon={<MaskIcon />}
  765. /> */}
  766. {/* <ChatAction
  767. text={Locale.Chat.InputActions.Clear}
  768. icon={<BreakIcon />}
  769. onClick={() => {
  770. chatStore.updateCurrentSession((session) => {
  771. if (session.clearContextIndex === session.messages.length) {
  772. session.clearContextIndex = undefined;
  773. } else {
  774. session.clearContextIndex = session.messages.length;
  775. session.memoryPrompt = ""; // will clear memory
  776. }
  777. });
  778. }}
  779. /> */}
  780. {/* <ChatAction
  781. onClick={() => setShowModelSelector(true)}
  782. text={currentModelName}
  783. icon={<RobotIcon />}
  784. /> */}
  785. {showModelSelector && (
  786. <Selector
  787. defaultSelectedValue={`${currentModel}@${currentProviderName}`}
  788. items={models.map((m) => ({
  789. title: `${m.displayName}${m?.provider?.providerName
  790. ? "(" + m?.provider?.providerName + ")"
  791. : ""
  792. }`,
  793. value: `${m.name}@${m?.provider?.providerName}`,
  794. }))}
  795. onClose={() => setShowModelSelector(false)}
  796. onSelection={(s) => {
  797. if (s.length === 0) return;
  798. const [model, providerName] = s[0].split("@");
  799. chatStore.updateCurrentSession((session) => {
  800. session.mask.modelConfig.model = model as ModelType;
  801. session.mask.modelConfig.providerName =
  802. providerName as ServiceProvider;
  803. session.mask.syncGlobalConfig = false;
  804. });
  805. if (providerName == "ByteDance") {
  806. const selectedModel = models.find(
  807. (m) =>
  808. m.name == model && m?.provider?.providerName == providerName,
  809. );
  810. showToast(selectedModel?.displayName ?? "");
  811. } else {
  812. showToast(model);
  813. }
  814. }}
  815. />
  816. )}
  817. {isDalle3(currentModel) && (
  818. <ChatAction
  819. onClick={() => setShowSizeSelector(true)}
  820. text={currentSize}
  821. icon={<SizeIcon />}
  822. />
  823. )}
  824. {showSizeSelector && (
  825. <Selector
  826. defaultSelectedValue={currentSize}
  827. items={dalle3Sizes.map((m) => ({
  828. title: m,
  829. value: m,
  830. }))}
  831. onClose={() => setShowSizeSelector(false)}
  832. onSelection={(s) => {
  833. if (s.length === 0) return;
  834. const size = s[0];
  835. chatStore.updateCurrentSession((session) => {
  836. session.mask.modelConfig.size = size;
  837. });
  838. showToast(size);
  839. }}
  840. />
  841. )}
  842. {/* <ChatAction
  843. onClick={() => setShowPluginSelector(true)}
  844. text={Locale.Plugin.Name}
  845. icon={<PluginIcon />}
  846. /> */}
  847. {showPluginSelector && (
  848. <Selector
  849. multiple
  850. defaultSelectedValue={chatStore.currentSession().mask?.plugin}
  851. items={[
  852. {
  853. title: Locale.Plugin.Artifacts,
  854. value: Plugin.Artifacts,
  855. },
  856. ]}
  857. onClose={() => setShowPluginSelector(false)}
  858. onSelection={(s) => {
  859. const plugin = s[0];
  860. chatStore.updateCurrentSession((session) => {
  861. session.mask.plugin = s;
  862. });
  863. if (plugin) {
  864. showToast(plugin);
  865. }
  866. }}
  867. />
  868. )}
  869. </div>
  870. );
  871. }
  872. export function EditMessageModal(props: { onClose: () => void }) {
  873. const chatStore = useChatStore();
  874. const session = chatStore.currentSession();
  875. const [messages, setMessages] = useState(session.messages.slice());
  876. return (
  877. <div className="modal-mask">
  878. <Modal
  879. title={Locale.Chat.EditMessage.Title}
  880. onClose={props.onClose}
  881. actions={[
  882. <IconButton
  883. text={Locale.UI.Cancel}
  884. icon={<CancelIcon />}
  885. key="cancel"
  886. onClick={() => {
  887. props.onClose();
  888. }}
  889. />,
  890. <IconButton
  891. type="primary"
  892. text={Locale.UI.Confirm}
  893. icon={<ConfirmIcon />}
  894. key="ok"
  895. onClick={() => {
  896. chatStore.updateCurrentSession(
  897. (session) => (session.messages = messages),
  898. );
  899. props.onClose();
  900. }}
  901. />,
  902. ]}
  903. >
  904. <List>
  905. <ListItem
  906. title={Locale.Chat.EditMessage.Topic.Title}
  907. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  908. >
  909. <input
  910. type="text"
  911. value={session.topic}
  912. onInput={(e) =>
  913. chatStore.updateCurrentSession(
  914. (session) => (session.topic = e.currentTarget.value),
  915. )
  916. }
  917. ></input>
  918. </ListItem>
  919. </List>
  920. <ContextPrompts
  921. context={messages}
  922. updateContext={(updater) => {
  923. const newMessages = messages.slice();
  924. updater(newMessages);
  925. setMessages(newMessages);
  926. }}
  927. />
  928. </Modal>
  929. </div>
  930. );
  931. }
  932. export function DeleteImageButton(props: { deleteImage: () => void }) {
  933. return (
  934. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  935. <DeleteIcon />
  936. </div>
  937. );
  938. }
  939. function _Chat() {
  940. type RenderMessage = ChatMessage & { preview?: boolean };
  941. const chatStore = useChatStore();
  942. const session = chatStore.currentSession();
  943. const config = useAppConfig();
  944. config.sendPreviewBubble = false;
  945. const fontSize = config.fontSize;
  946. const fontFamily = config.fontFamily;
  947. const [showExport, setShowExport] = useState(false);
  948. const inputRef = useRef<HTMLTextAreaElement>(null);
  949. const [userInput, setUserInput] = useState("");
  950. const [isLoading, setIsLoading] = useState(false);
  951. const [sendStatus, setSendStatus] = useState(false);
  952. const { submitKey, shouldSubmit } = useSubmitHandler();
  953. const scrollRef = useRef<HTMLDivElement>(null);
  954. const isScrolledToBottom = scrollRef?.current
  955. ? Math.abs(
  956. scrollRef.current.scrollHeight -
  957. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  958. ) <= 1
  959. : false;
  960. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  961. scrollRef,
  962. isScrolledToBottom,
  963. );
  964. const [hitBottom, setHitBottom] = useState(true);
  965. const isMobileScreen = useMobileScreen();
  966. const navigate = useNavigate();
  967. const [attachImages, setAttachImages] = useState<string[]>([]);
  968. const [uploading, setUploading] = useState(false);
  969. // prompt hints
  970. const promptStore = usePromptStore();
  971. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  972. const onSearch = useDebouncedCallback(
  973. (text: string) => {
  974. const matchedPrompts = promptStore.search(text);
  975. setPromptHints(matchedPrompts);
  976. },
  977. 100,
  978. { leading: true, trailing: true },
  979. );
  980. type AppList = {
  981. label: string,
  982. value: string,
  983. desc: string,
  984. }[];
  985. const [appList, setAppList] = useState<AppList>([]);
  986. const [appValue, setAppValue] = useState<string>();
  987. const globalStore = useGlobalStore();
  988. type QuestionList = string[];
  989. const [questionList, setQuestionList] = useState<QuestionList>([]);
  990. const location = useLocation();
  991. const [loading, setLoading] = useState<boolean>(false);
  992. const fruits = [
  993. { id: 'LOCAL', name: 'deepseek' },
  994. { id: 'ONLINE', name: '智谱AI' },
  995. ];
  996. const [selectedFruit, setSelectedFruit] = React.useState(chatStore.chatMode);
  997. // 获取应用列表
  998. const fetchApplicationList = async (chatMode?: string) => {
  999. let mode = chatMode || selectedFruit;
  1000. setLoading(true);
  1001. try {
  1002. let url = null;
  1003. if (mode === 'LOCAL') {
  1004. url = '/deepseek/api/application/list';
  1005. } else {
  1006. url = '/bigmodel/api/application/list';
  1007. }
  1008. const res = await api.get(url);
  1009. const list = res.data.filter((item: any) => item.appId !== '1234567890123456789').map((item: any) => {
  1010. return {
  1011. label: item.name,
  1012. value: item.appId,
  1013. desc: item.desc,
  1014. }
  1015. })
  1016. setAppList(list);
  1017. const search = location.search;
  1018. const params = new URLSearchParams(search);
  1019. const appId = params.get('appId') || '';
  1020. if (appId) {
  1021. setAppValue(appId);
  1022. } else {
  1023. setAppValue(list[0]?.value);
  1024. }
  1025. } catch (error) {
  1026. console.error(error);
  1027. } finally {
  1028. setLoading(false);
  1029. }
  1030. }
  1031. // 获取预设问题列表
  1032. const fetchDefaultQuestion = async (appId: string) => {
  1033. try {
  1034. let url = null;
  1035. if (selectedFruit === 'LOCAL') {
  1036. url = '/deepseek/api/presets';
  1037. } else {
  1038. url = '/bigmodel/api/presets';
  1039. }
  1040. const res = await api.get(url + `/${appId}`);
  1041. setQuestionList(res.data);
  1042. } catch (error) {
  1043. console.error(error);
  1044. } finally {
  1045. setLoading(false);
  1046. }
  1047. }
  1048. const init = async (chatMode?: string) => {
  1049. await fetchApplicationList(chatMode);
  1050. }
  1051. useEffect(() => {
  1052. const search = location.search;
  1053. const params = new URLSearchParams(search);
  1054. const chatMode = params.get('chatMode');
  1055. if (!chatMode) {
  1056. init();
  1057. }
  1058. }, [selectedFruit])
  1059. useEffect(() => {
  1060. const search = location.search;
  1061. const params = new URLSearchParams(search);
  1062. const chatMode = params.get('chatMode');
  1063. if (chatMode) {
  1064. setSelectedFruit(chatMode as "ONLINE" | "LOCAL");
  1065. const appId = params.get('appId');
  1066. if (appId) {
  1067. setAppValue(appId);
  1068. globalStore.setSelectedAppId(appId);
  1069. chatStore.updateCurrentSession((session) => {
  1070. session.appId = appId;
  1071. });
  1072. }
  1073. init(chatMode);
  1074. }
  1075. }, [])
  1076. useEffect(() => {
  1077. if (appValue) {
  1078. fetchDefaultQuestion(appValue);
  1079. }
  1080. }, [appValue, chatStore.chatMode])
  1081. const [inputRows, setInputRows] = useState(2);
  1082. const measure = useDebouncedCallback(
  1083. () => {
  1084. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  1085. const inputRows = Math.min(
  1086. 20,
  1087. Math.max(2 + Number(!isMobileScreen), rows),
  1088. );
  1089. setInputRows(inputRows);
  1090. },
  1091. 100,
  1092. {
  1093. leading: true,
  1094. trailing: true,
  1095. },
  1096. );
  1097. // eslint-disable-next-line react-hooks/exhaustive-deps
  1098. useEffect(measure, [userInput]);
  1099. // chat commands shortcuts
  1100. const chatCommands = useChatCommand({
  1101. new: () => chatStore.newSession(),
  1102. newm: () => navigate(Path.NewChat),
  1103. prev: () => chatStore.nextSession(-1),
  1104. next: () => chatStore.nextSession(1),
  1105. clear: () =>
  1106. chatStore.updateCurrentSession(
  1107. (session) => (session.clearContextIndex = session.messages.length),
  1108. ),
  1109. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  1110. });
  1111. // only search prompts when user input is short
  1112. const SEARCH_TEXT_LIMIT = 30;
  1113. const onInput = (text: string) => {
  1114. setUserInput(text);
  1115. const n = text.trim().length;
  1116. // clear search results
  1117. if (n === 0) {
  1118. setPromptHints([]);
  1119. } else if (text.match(ChatCommandPrefix)) {
  1120. setPromptHints(chatCommands.search(text));
  1121. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  1122. // check if need to trigger auto completion
  1123. if (text.startsWith("/")) {
  1124. let searchText = text.slice(1);
  1125. onSearch(searchText);
  1126. }
  1127. }
  1128. };
  1129. const doSubmit = (userInput: string) => {
  1130. if (userInput.trim() === "") return;
  1131. const matchCommand = chatCommands.match(userInput);
  1132. if (matchCommand.matched) {
  1133. setUserInput("");
  1134. setPromptHints([]);
  1135. matchCommand.invoke();
  1136. return;
  1137. }
  1138. setIsLoading(true);
  1139. // debugger
  1140. chatStore.onUserInput([], userInput, attachImages).then(() => setIsLoading(false));
  1141. setAttachImages([]);
  1142. localStorage.setItem(LAST_INPUT_KEY, userInput);
  1143. setUserInput("");
  1144. setPromptHints([]);
  1145. if (!isMobileScreen) inputRef.current?.focus();
  1146. setAutoScroll(true);
  1147. setSendStatus(true);
  1148. };
  1149. const onPromptSelect = (prompt: RenderPrompt) => {
  1150. setTimeout(() => {
  1151. setPromptHints([]);
  1152. const matchedChatCommand = chatCommands.match(prompt.content);
  1153. if (matchedChatCommand.matched) {
  1154. // if user is selecting a chat command, just trigger it
  1155. matchedChatCommand.invoke();
  1156. setUserInput("");
  1157. } else {
  1158. // or fill the prompt
  1159. setUserInput(prompt.content);
  1160. }
  1161. inputRef.current?.focus();
  1162. }, 30);
  1163. };
  1164. // stop response
  1165. const onUserStop = (messageId: string) => {
  1166. ChatControllerPool.stop(session.id, messageId);
  1167. };
  1168. useEffect(() => {
  1169. chatStore.updateCurrentSession((session) => {
  1170. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  1171. session.messages.forEach((m) => {
  1172. // check if should stop all stale messages
  1173. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  1174. if (m.streaming) {
  1175. m.streaming = false;
  1176. }
  1177. if (m.content.length === 0) {
  1178. m.isError = true;
  1179. m.content = prettyObject({
  1180. error: true,
  1181. message: "empty response",
  1182. });
  1183. }
  1184. }
  1185. });
  1186. // auto sync mask config from global config
  1187. if (session.mask.syncGlobalConfig) {
  1188. console.log("[Mask] syncing from global, name = ", session.mask.name);
  1189. session.mask.modelConfig = { ...config.modelConfig };
  1190. }
  1191. });
  1192. // eslint-disable-next-line react-hooks/exhaustive-deps
  1193. }, []);
  1194. // check if should send message
  1195. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  1196. if (
  1197. e.key === "ArrowUp" &&
  1198. userInput.length <= 0 &&
  1199. !(e.metaKey || e.altKey || e.ctrlKey)
  1200. ) {
  1201. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  1202. e.preventDefault();
  1203. return;
  1204. }
  1205. if (shouldSubmit(e) && promptHints.length === 0) {
  1206. doSubmit(userInput);
  1207. e.preventDefault();
  1208. }
  1209. };
  1210. const onRightClick = (e: any, message: ChatMessage) => {
  1211. // copy to clipboard
  1212. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  1213. if (userInput.length === 0) {
  1214. setUserInput(getMessageTextContent(message));
  1215. }
  1216. e.preventDefault();
  1217. }
  1218. };
  1219. const deleteMessage = (msgId?: string) => {
  1220. chatStore.updateCurrentSession(
  1221. (session) =>
  1222. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  1223. );
  1224. };
  1225. const onDelete = (msgId: string) => {
  1226. deleteMessage(msgId);
  1227. };
  1228. const onResend = (message: ChatMessage) => {
  1229. // when it is resending a message
  1230. // 1. for a user's message, find the next bot response
  1231. // 2. for a bot's message, find the last user's input
  1232. // 3. delete original user input and bot's message
  1233. // 4. resend the user's input
  1234. const resendingIndex = session.messages.findIndex(
  1235. (m) => m.id === message.id,
  1236. );
  1237. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  1238. console.error("[Chat] failed to find resending message", message);
  1239. return;
  1240. }
  1241. let userMessage: ChatMessage | undefined;
  1242. let botMessage: ChatMessage | undefined;
  1243. if (message.role === "assistant") {
  1244. // if it is resending a bot's message, find the user input for it
  1245. botMessage = message;
  1246. for (let i = resendingIndex; i >= 0; i -= 1) {
  1247. if (session.messages[i].role === "user") {
  1248. userMessage = session.messages[i];
  1249. break;
  1250. }
  1251. }
  1252. } else if (message.role === "user") {
  1253. // if it is resending a user's input, find the bot's response
  1254. userMessage = message;
  1255. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  1256. if (session.messages[i].role === "assistant") {
  1257. botMessage = session.messages[i];
  1258. break;
  1259. }
  1260. }
  1261. }
  1262. if (userMessage === undefined) {
  1263. console.error("[Chat] failed to resend", message);
  1264. return;
  1265. }
  1266. // delete the original messages
  1267. deleteMessage(userMessage.id);
  1268. deleteMessage(botMessage?.id);
  1269. // resend the message
  1270. setIsLoading(true);
  1271. const textContent = getMessageTextContent(userMessage);
  1272. const images = getMessageImages(userMessage);
  1273. chatStore.onUserInput([], textContent, images).then(() => setIsLoading(false));
  1274. inputRef.current?.focus();
  1275. };
  1276. const onPinMessage = (message: ChatMessage) => {
  1277. chatStore.updateCurrentSession((session) =>
  1278. session.mask.context.push(message),
  1279. );
  1280. showToast(Locale.Chat.Actions.PinToastContent, {
  1281. text: Locale.Chat.Actions.PinToastAction,
  1282. onClick: () => {
  1283. setShowPromptModal(true);
  1284. },
  1285. });
  1286. };
  1287. const context: RenderMessage[] = useMemo(() => {
  1288. return session.mask.hideContext ? [] : session.mask.context.slice();
  1289. }, [session.mask.context, session.mask.hideContext]);
  1290. const accessStore = useAccessStore();
  1291. if (
  1292. context.length === 0 &&
  1293. session.messages.at(0)?.content !== BOT_HELLO.content
  1294. ) {
  1295. const copiedHello = Object.assign({}, BOT_HELLO);
  1296. if (!accessStore.isAuthorized()) {
  1297. copiedHello.content = Locale.Error.Unauthorized;
  1298. }
  1299. context.push(copiedHello);
  1300. }
  1301. // preview messages
  1302. const renderMessages = useMemo(() => {
  1303. return context.concat(session.messages as RenderMessage[]).concat(
  1304. isLoading
  1305. ? [
  1306. {
  1307. ...createMessage({
  1308. role: "assistant",
  1309. content: "……",
  1310. }),
  1311. preview: true,
  1312. },
  1313. ]
  1314. : [],
  1315. ).concat(
  1316. userInput.length > 0 && config.sendPreviewBubble
  1317. ? [
  1318. {
  1319. ...createMessage({
  1320. role: "user",
  1321. content: userInput,
  1322. }),
  1323. preview: true,
  1324. },
  1325. ]
  1326. : [],
  1327. );
  1328. }, [
  1329. config.sendPreviewBubble,
  1330. context,
  1331. isLoading,
  1332. session.messages,
  1333. userInput,
  1334. ]);
  1335. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  1336. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1337. );
  1338. function setMsgRenderIndex(newIndex: number) {
  1339. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1340. newIndex = Math.max(0, newIndex);
  1341. _setMsgRenderIndex(newIndex);
  1342. }
  1343. const messages = useMemo(() => {
  1344. const endRenderIndex = Math.min(
  1345. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1346. renderMessages.length,
  1347. );
  1348. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1349. }, [msgRenderIndex, renderMessages]);
  1350. const onChatBodyScroll = (e: HTMLElement) => {
  1351. const bottomHeight = e.scrollTop + e.clientHeight;
  1352. const edgeThreshold = e.clientHeight;
  1353. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1354. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1355. const isHitBottom =
  1356. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1357. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1358. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1359. if (isTouchTopEdge && !isTouchBottomEdge) {
  1360. setMsgRenderIndex(prevPageMsgIndex);
  1361. } else if (isTouchBottomEdge) {
  1362. setMsgRenderIndex(nextPageMsgIndex);
  1363. }
  1364. setHitBottom(isHitBottom);
  1365. setAutoScroll(isHitBottom);
  1366. };
  1367. function scrollToBottom() {
  1368. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1369. scrollDomToBottom();
  1370. }
  1371. // clear context index = context length + index in messages
  1372. const clearContextIndex =
  1373. (session.clearContextIndex ?? -1) >= 0
  1374. ? session.clearContextIndex! + context.length - msgRenderIndex
  1375. : -1;
  1376. const [showPromptModal, setShowPromptModal] = useState(false);
  1377. const clientConfig = useMemo(() => getClientConfig(), []);
  1378. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1379. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1380. useCommand({
  1381. fill: setUserInput,
  1382. submit: (text) => {
  1383. doSubmit(text);
  1384. },
  1385. code: (text) => {
  1386. if (accessStore.disableFastLink) return;
  1387. console.log("[Command] got code from url: ", text);
  1388. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1389. if (res) {
  1390. accessStore.update((access) => (access.accessCode = text));
  1391. }
  1392. });
  1393. },
  1394. settings: (text) => {
  1395. if (accessStore.disableFastLink) return;
  1396. try {
  1397. const payload = JSON.parse(text) as {
  1398. key?: string;
  1399. url?: string;
  1400. };
  1401. console.log("[Command] got settings from url: ", payload);
  1402. if (payload.key || payload.url) {
  1403. showConfirm(
  1404. Locale.URLCommand.Settings +
  1405. `\n${JSON.stringify(payload, null, 4)}`,
  1406. ).then((res) => {
  1407. if (!res) return;
  1408. if (payload.key) {
  1409. accessStore.update(
  1410. (access) => (access.openaiApiKey = payload.key!),
  1411. );
  1412. }
  1413. if (payload.url) {
  1414. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1415. }
  1416. accessStore.update((access) => (access.useCustomConfig = true));
  1417. });
  1418. }
  1419. } catch {
  1420. console.error("[Command] failed to get settings from url: ", text);
  1421. }
  1422. },
  1423. });
  1424. // edit / insert message modal
  1425. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1426. // remember unfinished input
  1427. useEffect(() => {
  1428. // try to load from local storage
  1429. const key = UNFINISHED_INPUT(session.id);
  1430. const mayBeUnfinishedInput = localStorage.getItem(key);
  1431. if (mayBeUnfinishedInput && userInput.length === 0) {
  1432. setUserInput(mayBeUnfinishedInput);
  1433. localStorage.removeItem(key);
  1434. }
  1435. const dom = inputRef.current;
  1436. return () => {
  1437. localStorage.setItem(key, dom?.value ?? "");
  1438. };
  1439. // eslint-disable-next-line react-hooks/exhaustive-deps
  1440. }, []);
  1441. const handlePaste = useCallback(
  1442. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1443. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1444. if (!isVisionModel(currentModel)) {
  1445. return;
  1446. }
  1447. const items = (event.clipboardData || window.clipboardData).items;
  1448. for (const item of items) {
  1449. if (item.kind === "file" && item.type.startsWith("image/")) {
  1450. event.preventDefault();
  1451. const file = item.getAsFile();
  1452. if (file) {
  1453. const images: string[] = [];
  1454. images.push(...attachImages);
  1455. images.push(
  1456. ...(await new Promise<string[]>((res, rej) => {
  1457. setUploading(true);
  1458. const imagesData: string[] = [];
  1459. uploadImageRemote(file).then((dataUrl) => {
  1460. imagesData.push(dataUrl);
  1461. setUploading(false);
  1462. res(imagesData);
  1463. }).catch((e) => {
  1464. setUploading(false);
  1465. rej(e);
  1466. });
  1467. })),
  1468. );
  1469. const imagesLength = images.length;
  1470. if (imagesLength > 3) {
  1471. images.splice(3, imagesLength - 3);
  1472. }
  1473. setAttachImages(images);
  1474. }
  1475. }
  1476. }
  1477. },
  1478. [attachImages, chatStore],
  1479. );
  1480. async function uploadImage() {
  1481. const images: string[] = [];
  1482. images.push(...attachImages);
  1483. images.push(
  1484. ...(await new Promise<string[]>((res, rej) => {
  1485. const fileInput = document.createElement("input");
  1486. fileInput.type = "file";
  1487. fileInput.accept =
  1488. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1489. fileInput.multiple = true;
  1490. fileInput.onchange = (event: any) => {
  1491. setUploading(true);
  1492. const files = event.target.files;
  1493. const imagesData: string[] = [];
  1494. for (let i = 0; i < files.length; i++) {
  1495. const file = event.target.files[i];
  1496. uploadImageRemote(file).then((dataUrl) => {
  1497. imagesData.push(dataUrl);
  1498. if (
  1499. imagesData.length === 3 ||
  1500. imagesData.length === files.length
  1501. ) {
  1502. setUploading(false);
  1503. res(imagesData);
  1504. }
  1505. }).catch((e) => {
  1506. setUploading(false);
  1507. rej(e);
  1508. });
  1509. }
  1510. };
  1511. fileInput.click();
  1512. })),
  1513. );
  1514. const imagesLength = images.length;
  1515. if (imagesLength > 3) {
  1516. images.splice(3, imagesLength - 3);
  1517. }
  1518. setAttachImages(images);
  1519. }
  1520. const getAppName = () => {
  1521. const search = location.search;
  1522. const params = new URLSearchParams(search);
  1523. const chatMode = params.get('chatMode');
  1524. let appId = '';
  1525. if (chatMode) {
  1526. appId = globalStore.selectedAppId;
  1527. } else {
  1528. appId = appValue as string;
  1529. }
  1530. const item = appList.find(item => item.value === appId);
  1531. if (!item) {
  1532. return '';
  1533. }
  1534. return item.label;
  1535. }
  1536. const getDesc = () => {
  1537. const search = location.search;
  1538. const params = new URLSearchParams(search);
  1539. const chatMode = params.get('chatMode');
  1540. let appId = '';
  1541. if (chatMode) {
  1542. appId = globalStore.selectedAppId;
  1543. } else {
  1544. appId = appValue as string;
  1545. }
  1546. const item = appList.find(item => item.value === appId);
  1547. if (!item) {
  1548. return '';
  1549. }
  1550. return item.desc;
  1551. }
  1552. const couldStop = ChatControllerPool.hasPending();
  1553. const stopAll = () => ChatControllerPool.stopAll();
  1554. const [isClickStop, setIsClickStop] = useState(false);
  1555. useEffect(() => {
  1556. if (!couldStop) {
  1557. setIsClickStop(false)
  1558. }
  1559. }, [couldStop])
  1560. interface FileIconProps {
  1561. fileName: string;
  1562. }
  1563. const FileIcon: React.FC<FileIconProps> = (props: FileIconProps) => {
  1564. const style = {
  1565. fontSize: '30px',
  1566. color: '#3875f6',
  1567. }
  1568. let icon = <FileOutlined style={style} />
  1569. if (props.fileName) {
  1570. const suffix = props.fileName.split('.').pop() || '';
  1571. switch (suffix) {
  1572. case 'pdf':
  1573. icon = <FilePdfOutlined style={style} />
  1574. break;
  1575. case 'txt':
  1576. icon = <FileTextOutlined style={style} />
  1577. break;
  1578. case 'doc':
  1579. case 'docx':
  1580. icon = <FileWordOutlined style={style} />
  1581. break;
  1582. default:
  1583. break;
  1584. }
  1585. }
  1586. return icon;
  1587. }
  1588. const [drawerOpen, setDrawerOpen] = useState(false);
  1589. const [drawerData, setDrawerData] = useState({
  1590. knowledge_id: '',
  1591. doc_name: '',
  1592. chunk_info: {
  1593. doc_id: '',
  1594. chunk_list: [],
  1595. }
  1596. });
  1597. const SliceDrawer: React.FC = () => {
  1598. const [pageLoading, setPageLoading] = useState(false);
  1599. const [list, setList] = useState([]);
  1600. const init = async () => {
  1601. setPageLoading(true);
  1602. try {
  1603. const res: any = await api.post('/deepseek/api/slicePage', {
  1604. knowledge_id: drawerData.knowledge_id,
  1605. chunk_info: drawerData.chunk_info,
  1606. pageNum: 1,
  1607. pageSize: 9999,
  1608. });
  1609. console.log(res.rows, 'res.rows');
  1610. setList(res.rows);
  1611. } catch (error) {
  1612. console.error(error);
  1613. } finally {
  1614. setPageLoading(false);
  1615. }
  1616. }
  1617. useEffect(() => {
  1618. init()
  1619. }, [])
  1620. return (
  1621. <Drawer
  1622. title={drawerData.doc_name}
  1623. loading={pageLoading}
  1624. open={drawerOpen}
  1625. onClose={() => {
  1626. setDrawerOpen(false);
  1627. }}
  1628. >
  1629. {list.map((item: any, index) => {
  1630. const score = parseFloat(item.rerankScore);
  1631. const formattedScore = isNaN(score) ? '0.00' : score.toFixed(2);
  1632. return <div
  1633. style={{
  1634. padding: 10,
  1635. background: '#fafafa',
  1636. borderRadius: 4,
  1637. marginBottom: 10
  1638. }}
  1639. key={item.sliceId}
  1640. >
  1641. <div
  1642. style={{
  1643. display: 'flex',
  1644. justifyContent: 'space-between',
  1645. alignItems: 'center',
  1646. }}
  1647. >
  1648. <div style={{ margin: '5px 0' }}>
  1649. 片段{index + 1}
  1650. </div>
  1651. <div>
  1652. <StarTwoTone style={{ marginRight: 10 }} />
  1653. rerank得分{formattedScore}
  1654. </div>
  1655. </div>
  1656. <div>
  1657. {item.sliceText}
  1658. </div>
  1659. </div>
  1660. })}
  1661. </Drawer>
  1662. )
  1663. }
  1664. useEffect(() => {
  1665. // 当显示欢迎页面时,确保滚动到顶部
  1666. if (messages.length <= 1 && scrollRef.current) {
  1667. setTimeout(() => {
  1668. if (scrollRef.current) {
  1669. scrollRef.current.scrollTo(0, 0);
  1670. }
  1671. }, 0);
  1672. }
  1673. }, [messages.length]);
  1674. return (
  1675. <div className={styles.chat} key={session.id}>
  1676. {
  1677. <div className="window-header" data-tauri-drag-region>
  1678. <div style={{ display: 'flex', alignItems: 'center' }}
  1679. className={`window-header-title ${styles["chat-body-title"]}`}>
  1680. {
  1681. <div style={{ marginRight: 10 }}>
  1682. <Button
  1683. type='text'
  1684. icon={<MenuOutlined />}
  1685. onClick={() => {
  1686. globalStore.setShowMenu(!globalStore.showMenu);
  1687. }}
  1688. />
  1689. </div>
  1690. }
  1691. {
  1692. false &&
  1693. <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
  1694. <Select
  1695. style={{ width: '100%', height: 38, marginRight: 10 }}
  1696. value={selectedFruit}
  1697. onChange={(value: "ONLINE" | "LOCAL") => {
  1698. chatStore.clearSessions();
  1699. chatStore.updateCurrentSession((values) => {
  1700. values.appId = globalStore.selectedAppId;
  1701. });
  1702. navigate({ pathname: '/newChat' });
  1703. setSelectedFruit(value);
  1704. chatStore.setChatMode(value);
  1705. }}
  1706. >
  1707. {fruits.map(fruit => (
  1708. <Select.Option key={fruit.id} value={fruit.id}>
  1709. {fruit.name}
  1710. </Select.Option>
  1711. ))}
  1712. </Select>
  1713. {
  1714. appList.length > 0 ?
  1715. <Select
  1716. style={{ width: '100%', height: 38, marginRight: 5 }}
  1717. placeholder='请选择'
  1718. options={appList}
  1719. value={appValue}
  1720. onChange={(value) => {
  1721. setAppValue(value);
  1722. globalStore.setSelectedAppId(value);
  1723. chatStore.clearSessions();
  1724. chatStore.updateCurrentSession((values) => {
  1725. values.appId = value;
  1726. });
  1727. useChatStore.setState({
  1728. message: {
  1729. content: '',
  1730. role: 'assistant',
  1731. }
  1732. });
  1733. setSendStatus(false);
  1734. }}
  1735. />
  1736. :
  1737. null
  1738. }
  1739. </div>
  1740. }
  1741. </div>
  1742. <div className="window-actions">
  1743. <div className="window-action-button">
  1744. <Popover
  1745. trigger="click"
  1746. title="分享该应用"
  1747. content={() => {
  1748. const url = `${window.location.origin}/#/knowledgeChat?showMenu=false&chatMode=${selectedFruit}&appId=${appValue}`
  1749. return <div>
  1750. <div style={{ marginBottom: 10 }}>
  1751. {url}
  1752. </div>
  1753. <Button onClick={() => {
  1754. navigator.clipboard.writeText(url);
  1755. message.success('分享链接已复制到剪贴板');
  1756. }}>
  1757. 复制
  1758. </Button>
  1759. </div>
  1760. }
  1761. }>
  1762. <IconButton
  1763. icon={<ExportIcon />}
  1764. bordered
  1765. title='分享该应用'
  1766. />
  1767. </Popover>
  1768. </div>
  1769. {/* {showMaxIcon && (
  1770. <div className="window-action-button">
  1771. <IconButton
  1772. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1773. bordered
  1774. title={Locale.Chat.Actions.FullScreen}
  1775. aria={Locale.Chat.Actions.FullScreen}
  1776. onClick={() => {
  1777. config.update(
  1778. (config) => (config.tightBorder = !config.tightBorder),
  1779. );
  1780. }}
  1781. />
  1782. </div>
  1783. )} */}
  1784. </div>
  1785. {/* <PromptToast
  1786. showToast={!hitBottom}
  1787. showModal={showPromptModal}
  1788. setShowModal={setShowPromptModal}
  1789. /> */}
  1790. </div>
  1791. }
  1792. <div
  1793. className={styles["chat-body"]}
  1794. ref={scrollRef}
  1795. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1796. onMouseDown={() => inputRef.current?.blur()}
  1797. onTouchStart={() => {
  1798. inputRef.current?.blur();
  1799. setAutoScroll(false);
  1800. }}
  1801. >
  1802. {
  1803. messages.length > 1 ?
  1804. <>
  1805. {messages.map((message, i) => {
  1806. const isUser = message.role === "user";
  1807. const isContext = i < context.length;
  1808. const showActions =
  1809. i > 0 &&
  1810. !(message.preview || message.content.length === 0) &&
  1811. !isContext;
  1812. const showTyping = message.preview || message.streaming;
  1813. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1814. return (
  1815. <Fragment key={message.id}>
  1816. <div
  1817. className={
  1818. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1819. }
  1820. >
  1821. <div className={styles["chat-message-container"]}>
  1822. <div className={styles["chat-message-header"]}>
  1823. <div className={styles["chat-message-avatar"]}>
  1824. {isUser ? (
  1825. // 在这里换头像
  1826. <div style={{ position: 'relative' }}>
  1827. <div
  1828. style={{
  1829. position: 'absolute',
  1830. zIndex: 2,
  1831. top: '50%',
  1832. left: '50%',
  1833. transform: ' translate(-110%, -100%)',
  1834. fontSize: 14,
  1835. }}>
  1836. </div>
  1837. </div>
  1838. ) : (
  1839. <>
  1840. {["system"].includes(message.role) ? (
  1841. <Avatar avatar="2699-fe0f" />
  1842. ) : (
  1843. <MaskAvatar
  1844. avatar={session.mask.avatar}
  1845. model={
  1846. message.model || session.mask.modelConfig.model
  1847. }
  1848. />
  1849. )}
  1850. </>
  1851. )}
  1852. </div>
  1853. {/* {showActions && (
  1854. <div className={styles["chat-message-actions"]}>
  1855. <div className={styles["chat-input-actions"]}>
  1856. {message.streaming ? (
  1857. <ChatAction
  1858. text={Locale.Chat.Actions.Stop}
  1859. icon={<StopIcon />}
  1860. onClick={() => onUserStop(message.id ?? i)}
  1861. />
  1862. ) : (
  1863. <>
  1864. <ChatAction
  1865. text={Locale.Chat.Actions.Retry}
  1866. icon={<ResetIcon />}
  1867. onClick={() => onResend(message)}
  1868. />
  1869. <ChatAction
  1870. text={Locale.Chat.Actions.Delete}
  1871. icon={<DeleteIcon />}
  1872. onClick={() => onDelete(message.id ?? i)}
  1873. />
  1874. <ChatAction
  1875. text={Locale.Chat.Actions.Pin}
  1876. icon={<PinIcon />}
  1877. onClick={() => onPinMessage(message)}
  1878. />
  1879. <ChatAction
  1880. text={Locale.Chat.Actions.Copy}
  1881. icon={<CopyIcon />}
  1882. onClick={() =>
  1883. copyToClipboard(
  1884. getMessageTextContent(message),
  1885. )
  1886. }
  1887. />
  1888. </>
  1889. )}
  1890. </div>
  1891. </div>
  1892. )} */}
  1893. </div>
  1894. {
  1895. showTyping ?
  1896. <div className={styles["chat-message-status"]}>
  1897. {isUser ? '' : '正在查询文档…'}
  1898. </div>
  1899. :
  1900. <div className={styles["chat-message-status"]}>
  1901. {
  1902. message.role === 'assistant' && messages.length - 1 === i &&
  1903. <div>
  1904. <CheckCircleOutlined /> 文档搜索成功
  1905. </div>
  1906. }
  1907. </div>
  1908. }
  1909. {
  1910. message.sliceInfo &&
  1911. <div style={{ marginTop: 10 }}>
  1912. <Collapse
  1913. bordered={false}
  1914. expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
  1915. items={[
  1916. {
  1917. key: '1',
  1918. // label: `查询到“${message.sliceInfo?.doc?.length}条”相关切片`,
  1919. label: `查询到${message.sliceInfo?.doc?.length}个问答共${message.sliceInfo?.allChunkNum}条切片`,
  1920. children: <div>
  1921. {message.sliceInfo?.doc?.map((item, index) => {
  1922. return <div
  1923. style={{
  1924. padding: 10,
  1925. background: '#FFFFFF',
  1926. borderRadius: 4,
  1927. display: 'flex',
  1928. justifyContent: 'space-between',
  1929. alignItems: 'center',
  1930. marginTop: index ? 10 : 0,
  1931. cursor: 'pointer',
  1932. }}
  1933. key={item.doc_id}
  1934. onClick={() => {
  1935. setDrawerData({
  1936. knowledge_id: item!.knowledge_id,
  1937. doc_name: item.doc_name,
  1938. chunk_info: {
  1939. doc_id: item.doc_id,
  1940. chunk_list: item.chunk_info_list,
  1941. }
  1942. });
  1943. setDrawerOpen(true);
  1944. }}
  1945. >
  1946. <div style={{ display: 'flex', alignItems: 'center' }}>
  1947. <FileIcon fileName={item.doc_name} />
  1948. <div style={{ marginLeft: 10 }}>
  1949. {item.doc_name}
  1950. </div>
  1951. </div>
  1952. <div style={{
  1953. padding: 10,
  1954. background: '#FAFAFA',
  1955. borderRadius: 4,
  1956. marginLeft: 20,
  1957. }}>
  1958. {item.chunk_nums}
  1959. </div>
  1960. </div>
  1961. })}
  1962. </div>,
  1963. }
  1964. ]}
  1965. />
  1966. {
  1967. drawerOpen &&
  1968. <SliceDrawer />
  1969. }
  1970. </div>
  1971. }
  1972. <div className={styles["chat-message-item"]}>
  1973. <Markdown
  1974. key={message.streaming ? "loading" : "done"}
  1975. content={getMessageTextContent(message)}
  1976. loading={
  1977. (message.preview || message.streaming) &&
  1978. message.content.length === 0 &&
  1979. !isUser
  1980. }
  1981. // onContextMenu={(e) => onRightClick(e, message)}
  1982. onDoubleClickCapture={() => {
  1983. if (!isMobileScreen) return;
  1984. setUserInput(getMessageTextContent(message));
  1985. }}
  1986. fontSize={fontSize}
  1987. fontFamily={fontFamily}
  1988. parentRef={scrollRef}
  1989. defaultShow={i >= messages.length - 6}
  1990. />
  1991. {getMessageImages(message).length == 1 && (
  1992. <img
  1993. className={styles["chat-message-item-image"]}
  1994. src={getMessageImages(message)[0]}
  1995. alt=""
  1996. />
  1997. )}
  1998. {getMessageImages(message).length > 1 && (
  1999. <div
  2000. className={styles["chat-message-item-images"]}
  2001. style={
  2002. {
  2003. "--image-count": getMessageImages(message).length,
  2004. } as React.CSSProperties
  2005. }
  2006. >
  2007. {getMessageImages(message).map((image, index) => {
  2008. return (
  2009. <img
  2010. className={
  2011. styles["chat-message-item-image-multi"]
  2012. }
  2013. key={index}
  2014. src={image}
  2015. alt=""
  2016. />
  2017. );
  2018. })}
  2019. </div>
  2020. )}
  2021. </div>
  2022. {/* <div className={styles["chat-message-action-date"]}>
  2023. {isContext
  2024. ? Locale.Chat.IsContext
  2025. : message.date.toLocaleString()}
  2026. </div> */}
  2027. </div>
  2028. </div>
  2029. {shouldShowClearContextDivider && <ClearContextDivider />}
  2030. </Fragment>
  2031. );
  2032. })}
  2033. </>
  2034. :
  2035. <>
  2036. <div style={{ padding: '0 20px' }}>
  2037. <div style={{ display: 'flex', justifyContent: 'center' }}>
  2038. <img style={{ width: 80, height: 80 }} src={avatarSrc.src} />
  2039. </div>
  2040. <h1 style={{ textAlign: 'center' }}>
  2041. {getAppName()}
  2042. </h1>
  2043. <p style={{ textAlign: 'center' }}>
  2044. {getDesc()}
  2045. </p>
  2046. <p>我猜您可能想问:</p>
  2047. {
  2048. questionList.map((item, index) => {
  2049. return (
  2050. <div
  2051. style={{
  2052. padding: '10px',
  2053. marginBottom: '10px',
  2054. border: '1px solid #e6e8f1',
  2055. borderRadius: '10px',
  2056. fontSize: '16px',
  2057. display: 'flex',
  2058. justifyContent: 'space-between',
  2059. alignItems: 'center',
  2060. cursor: 'pointer'
  2061. }}
  2062. onClick={() => {
  2063. setUserInput(item)
  2064. doSubmit(item)
  2065. }}
  2066. key={index}
  2067. >
  2068. <div>
  2069. {item}
  2070. </div>
  2071. <RightOutlined />
  2072. </div>
  2073. )
  2074. })
  2075. }
  2076. </div>
  2077. </>
  2078. }
  2079. </div>
  2080. <div className={styles["chat-input-panel"]}>
  2081. {/* <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} /> */}
  2082. <ChatActions
  2083. isClickStop={isClickStop}
  2084. sendStatus={sendStatus}
  2085. setSendStatus={setSendStatus}
  2086. setUserInput={setUserInput}
  2087. doSubmit={doSubmit}
  2088. uploadImage={uploadImage}
  2089. setAttachImages={setAttachImages}
  2090. setUploading={setUploading}
  2091. showPromptModal={() => setShowPromptModal(true)}
  2092. scrollToBottom={scrollToBottom}
  2093. hitBottom={hitBottom}
  2094. uploading={uploading}
  2095. showPromptHints={() => {
  2096. // Click again to close
  2097. if (promptHints.length > 0) {
  2098. setPromptHints([]);
  2099. return;
  2100. }
  2101. inputRef.current?.focus();
  2102. setUserInput("/");
  2103. onSearch("");
  2104. }}
  2105. />
  2106. <label
  2107. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  2108. ? styles["chat-input-panel-inner-attach"]
  2109. : ""
  2110. }`}
  2111. htmlFor="chat-input"
  2112. >
  2113. <textarea
  2114. id="chat-input"
  2115. ref={inputRef}
  2116. className={styles["chat-input"]}
  2117. placeholder={Locale.Chat.Input(submitKey)}
  2118. onInput={(e) => onInput(e.currentTarget.value)}
  2119. value={userInput}
  2120. onKeyDown={onInputKeyDown}
  2121. onFocus={scrollToBottom}
  2122. onClick={scrollToBottom}
  2123. onPaste={handlePaste}
  2124. rows={inputRows}
  2125. autoFocus={autoFocus}
  2126. style={{
  2127. fontSize: config.fontSize,
  2128. fontFamily: config.fontFamily,
  2129. }}
  2130. />
  2131. {attachImages.length != 0 && (
  2132. <div className={styles["attach-images"]}>
  2133. {attachImages.map((image, index) => {
  2134. return (
  2135. <div
  2136. key={index}
  2137. className={styles["attach-image"]}
  2138. style={{ backgroundImage: `url("${image}")` }}
  2139. >
  2140. <div className={styles["attach-image-mask"]}>
  2141. <DeleteImageButton
  2142. deleteImage={() => {
  2143. setAttachImages(
  2144. attachImages.filter((_, i) => i !== index),
  2145. );
  2146. }}
  2147. />
  2148. </div>
  2149. </div>
  2150. );
  2151. })}
  2152. </div>
  2153. )}
  2154. <IconButton
  2155. icon={couldStop ? <div style={{ width: 13, height: 13, background: '#FFFFFF', borderRadius: 2 }}></div> : <SendWhiteIcon />}
  2156. text={couldStop ? '停止' : '发送'}
  2157. className={styles["chat-input-send"]}
  2158. type="primary"
  2159. onClick={() => {
  2160. if (couldStop) {
  2161. stopAll();
  2162. setIsClickStop(true);
  2163. } else {
  2164. doSubmit(userInput);
  2165. }
  2166. }}
  2167. />
  2168. </label>
  2169. </div>
  2170. <div style={{ paddingBottom: 20, textAlign: 'center', color: '#888888', fontSize: 12 }}>
  2171. 内容由AI生成,仅供参考
  2172. </div>
  2173. {showExport && (
  2174. <ExportMessageModal onClose={() => setShowExport(false)} />
  2175. )}
  2176. {isEditingMessage && (
  2177. <EditMessageModal
  2178. onClose={() => {
  2179. setIsEditingMessage(false);
  2180. }}
  2181. />
  2182. )}
  2183. </div>
  2184. );
  2185. }
  2186. export function Chat() {
  2187. const globalStore = useGlobalStore();
  2188. const chatStore = useChatStore();
  2189. const location = useLocation();
  2190. const sessionIndex = chatStore.currentSessionIndex;
  2191. useEffect(() => {
  2192. chatStore.setModel('BigModel');
  2193. const search = location.search;
  2194. const params = new URLSearchParams(search);
  2195. const showMenu = params.get('showMenu');
  2196. const chatMode = params.get('chatMode');
  2197. if (showMenu) {
  2198. if (showMenu === 'true') {
  2199. globalStore.setShowMenu(true);
  2200. } else if (showMenu === 'false') {
  2201. globalStore.setShowMenu(false);
  2202. }
  2203. } else {
  2204. globalStore.setShowMenu(true);
  2205. }
  2206. if (chatMode) {
  2207. chatStore.setChatMode(chatMode as "ONLINE" | "LOCAL");
  2208. }
  2209. }, []);
  2210. return <_Chat key={sessionIndex}></_Chat>;
  2211. }