chat.tsx 71 KB

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