chat.tsx 72 KB

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