chat.tsx 74 KB

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