chat.tsx 74 KB

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