chat.tsx 71 KB

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