chat.tsx 75 KB

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