chat.tsx 65 KB

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