chat.tsx 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  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 } from 'antd';
  105. import { RightOutlined } 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. setUserInput: (value: string) => void;
  476. doSubmit: (userInput: string) => void;
  477. uploadImage: () => void;
  478. setAttachImages: (images: string[]) => void;
  479. setUploading: (uploading: boolean) => void;
  480. showPromptModal: () => void;
  481. scrollToBottom: () => void;
  482. showPromptHints: () => void;
  483. hitBottom: boolean;
  484. uploading: boolean;
  485. }) {
  486. const config = useAppConfig();
  487. const navigate = useNavigate();
  488. const chatStore = useChatStore();
  489. // switch themes
  490. const theme = config.theme;
  491. function nextTheme() {
  492. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  493. const themeIndex = themes.indexOf(theme);
  494. const nextIndex = (themeIndex + 1) % themes.length;
  495. const nextTheme = themes[nextIndex];
  496. config.update((config) => (config.theme = nextTheme));
  497. }
  498. // stop all responses
  499. const couldStop = ChatControllerPool.hasPending();
  500. const stopAll = () => ChatControllerPool.stopAll();
  501. // switch model
  502. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  503. const currentProviderName =
  504. chatStore.currentSession().mask.modelConfig?.providerName ||
  505. ServiceProvider.OpenAI;
  506. const allModels = useAllModels();
  507. const models = useMemo(() => {
  508. const filteredModels = allModels.filter((m) => m.available);
  509. const defaultModel = filteredModels.find((m) => m.isDefault);
  510. if (defaultModel) {
  511. const arr = [
  512. defaultModel,
  513. ...filteredModels.filter((m) => m !== defaultModel),
  514. ];
  515. return arr;
  516. } else {
  517. return filteredModels;
  518. }
  519. }, [allModels]);
  520. const currentModelName = useMemo(() => {
  521. const model = models.find(
  522. (m) =>
  523. m.name == currentModel &&
  524. m?.provider?.providerName == currentProviderName,
  525. );
  526. return model?.displayName ?? "";
  527. }, [models, currentModel, currentProviderName]);
  528. const [showModelSelector, setShowModelSelector] = useState(false);
  529. const [showPluginSelector, setShowPluginSelector] = useState(false);
  530. const [showUploadImage, setShowUploadImage] = useState(false);
  531. type GuessList = string[]
  532. const [guessList, setGuessList] = useState<GuessList>([]);
  533. const [showSizeSelector, setShowSizeSelector] = useState(false);
  534. const dalle3Sizes: DalleSize[] = ["1024x1024", "1792x1024", "1024x1792"];
  535. const currentSize =
  536. chatStore.currentSession().mask.modelConfig?.size ?? "1024x1024";
  537. const session = chatStore.currentSession();
  538. useEffect(() => {
  539. const show = isVisionModel(currentModel);
  540. setShowUploadImage(show);
  541. if (!show) {
  542. props.setAttachImages([]);
  543. props.setUploading(false);
  544. }
  545. // if current model is not available
  546. // switch to first available model
  547. const isUnavaliableModel = !models.some((m) => m.name === currentModel);
  548. if (isUnavaliableModel && models.length > 0) {
  549. // show next model to default model if exist
  550. let nextModel = models.find((model) => model.isDefault) || models[0];
  551. chatStore.updateCurrentSession((session) => {
  552. session.mask.modelConfig.model = nextModel.name;
  553. session.mask.modelConfig.providerName = nextModel?.provider?.providerName as ServiceProvider;
  554. });
  555. showToast(
  556. nextModel?.provider?.providerName == "ByteDance"
  557. ? nextModel.displayName
  558. : nextModel.name,
  559. );
  560. }
  561. }, [chatStore, currentModel, models]);
  562. const fetchGuessList = async (record: ChatMessage) => {
  563. try {
  564. const data = {
  565. appId: session.appId,
  566. messages: [
  567. {
  568. content: record.content,
  569. role: record.role,
  570. }
  571. ]
  572. }
  573. const res = await api.post('/bigmodel/api/async/completions', data);
  574. setGuessList(res.data);
  575. } catch (error) {
  576. console.error(error);
  577. }
  578. }
  579. useEffect(() => {
  580. setGuessList([]);
  581. const messages = session.messages.slice();
  582. const backList = messages.reverse();
  583. const item = backList.find(item => item.content && item.role === 'assistant')
  584. if (item) {
  585. fetchGuessList(item)
  586. }
  587. }, [session.messages.length]);
  588. return (
  589. <div className={styles["chat-input-actions"]}>
  590. {guessList.length > 0 && (
  591. <div style={{ color: '#8096ca', fontSize: 13 }}>
  592. <div>
  593. 你还可以尝试提问:
  594. </div>
  595. <div style={{ display: 'flex', marginTop: 10, flexWrap: 'wrap' }}>
  596. {
  597. guessList.map((item, index) => {
  598. return (
  599. <div
  600. style={{
  601. padding: '5px 10px',
  602. background: '#f2f4f8',
  603. borderRadius: 5,
  604. margin: '0 10px 10px 0',
  605. cursor: 'pointer',
  606. }}
  607. onClick={() => {
  608. props.setUserInput(item);
  609. props.doSubmit(item)
  610. }}
  611. key={index}
  612. >
  613. {item}
  614. </div>
  615. )
  616. })
  617. }
  618. </div>
  619. </div>
  620. )}
  621. {/* {couldStop && (
  622. <ChatAction
  623. onClick={stopAll}
  624. text={Locale.Chat.InputActions.Stop}
  625. icon={<StopIcon />}
  626. />
  627. )} */}
  628. {/* {!props.hitBottom && (
  629. <ChatAction
  630. onClick={props.scrollToBottom}
  631. text={Locale.Chat.InputActions.ToBottom}
  632. icon={<BottomIcon />}
  633. />
  634. )} */}
  635. {/* {props.hitBottom && (
  636. <ChatAction
  637. onClick={props.showPromptModal}
  638. text={Locale.Chat.InputActions.Settings}
  639. icon={<SettingsIcon />}
  640. />
  641. )} */}
  642. {/* {showUploadImage && (
  643. <ChatAction
  644. onClick={props.uploadImage}
  645. text={Locale.Chat.InputActions.UploadImage}
  646. icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />}
  647. />
  648. )} */}
  649. {/* <ChatAction
  650. onClick={nextTheme}
  651. text={Locale.Chat.InputActions.Theme[theme]}
  652. icon={
  653. <>
  654. {theme === Theme.Auto ? (
  655. <AutoIcon />
  656. ) : theme === Theme.Light ? (
  657. <LightIcon />
  658. ) : theme === Theme.Dark ? (
  659. <DarkIcon />
  660. ) : null}
  661. </>
  662. }
  663. /> */}
  664. {/* <CallWord */}
  665. {/* setUserInput={props.setUserInput} */}
  666. {/* doSubmit={props.doSubmit} */}
  667. {/* /> */}
  668. {/* <ChatAction
  669. onClick={props.showPromptHints}
  670. text={Locale.Chat.InputActions.Prompt}
  671. icon={<PromptIcon />}
  672. /> */}
  673. {/* <ChatAction
  674. onClick={() => {
  675. navigate(Path.Masks);
  676. }}
  677. text={Locale.Chat.InputActions.Masks}
  678. icon={<MaskIcon />}
  679. /> */}
  680. {/* <ChatAction
  681. text={Locale.Chat.InputActions.Clear}
  682. icon={<BreakIcon />}
  683. onClick={() => {
  684. chatStore.updateCurrentSession((session) => {
  685. if (session.clearContextIndex === session.messages.length) {
  686. session.clearContextIndex = undefined;
  687. } else {
  688. session.clearContextIndex = session.messages.length;
  689. session.memoryPrompt = ""; // will clear memory
  690. }
  691. });
  692. }}
  693. /> */}
  694. {/* <ChatAction
  695. onClick={() => setShowModelSelector(true)}
  696. text={currentModelName}
  697. icon={<RobotIcon />}
  698. /> */}
  699. {showModelSelector && (
  700. <Selector
  701. defaultSelectedValue={`${currentModel}@${currentProviderName}`}
  702. items={models.map((m) => ({
  703. title: `${m.displayName}${m?.provider?.providerName
  704. ? "(" + m?.provider?.providerName + ")"
  705. : ""
  706. }`,
  707. value: `${m.name}@${m?.provider?.providerName}`,
  708. }))}
  709. onClose={() => setShowModelSelector(false)}
  710. onSelection={(s) => {
  711. if (s.length === 0) return;
  712. const [model, providerName] = s[0].split("@");
  713. chatStore.updateCurrentSession((session) => {
  714. session.mask.modelConfig.model = model as ModelType;
  715. session.mask.modelConfig.providerName =
  716. providerName as ServiceProvider;
  717. session.mask.syncGlobalConfig = false;
  718. });
  719. if (providerName == "ByteDance") {
  720. const selectedModel = models.find(
  721. (m) =>
  722. m.name == model && m?.provider?.providerName == providerName,
  723. );
  724. showToast(selectedModel?.displayName ?? "");
  725. } else {
  726. showToast(model);
  727. }
  728. }}
  729. />
  730. )}
  731. {isDalle3(currentModel) && (
  732. <ChatAction
  733. onClick={() => setShowSizeSelector(true)}
  734. text={currentSize}
  735. icon={<SizeIcon />}
  736. />
  737. )}
  738. {showSizeSelector && (
  739. <Selector
  740. defaultSelectedValue={currentSize}
  741. items={dalle3Sizes.map((m) => ({
  742. title: m,
  743. value: m,
  744. }))}
  745. onClose={() => setShowSizeSelector(false)}
  746. onSelection={(s) => {
  747. if (s.length === 0) return;
  748. const size = s[0];
  749. chatStore.updateCurrentSession((session) => {
  750. session.mask.modelConfig.size = size;
  751. });
  752. showToast(size);
  753. }}
  754. />
  755. )}
  756. {/* <ChatAction
  757. onClick={() => setShowPluginSelector(true)}
  758. text={Locale.Plugin.Name}
  759. icon={<PluginIcon />}
  760. /> */}
  761. {showPluginSelector && (
  762. <Selector
  763. multiple
  764. defaultSelectedValue={chatStore.currentSession().mask?.plugin}
  765. items={[
  766. {
  767. title: Locale.Plugin.Artifacts,
  768. value: Plugin.Artifacts,
  769. },
  770. ]}
  771. onClose={() => setShowPluginSelector(false)}
  772. onSelection={(s) => {
  773. const plugin = s[0];
  774. chatStore.updateCurrentSession((session) => {
  775. session.mask.plugin = s;
  776. });
  777. if (plugin) {
  778. showToast(plugin);
  779. }
  780. }}
  781. />
  782. )}
  783. </div>
  784. );
  785. }
  786. export function EditMessageModal(props: { onClose: () => void }) {
  787. const chatStore = useChatStore();
  788. const session = chatStore.currentSession();
  789. const [messages, setMessages] = useState(session.messages.slice());
  790. return (
  791. <div className="modal-mask">
  792. <Modal
  793. title={Locale.Chat.EditMessage.Title}
  794. onClose={props.onClose}
  795. actions={[
  796. <IconButton
  797. text={Locale.UI.Cancel}
  798. icon={<CancelIcon />}
  799. key="cancel"
  800. onClick={() => {
  801. props.onClose();
  802. }}
  803. />,
  804. <IconButton
  805. type="primary"
  806. text={Locale.UI.Confirm}
  807. icon={<ConfirmIcon />}
  808. key="ok"
  809. onClick={() => {
  810. chatStore.updateCurrentSession(
  811. (session) => (session.messages = messages),
  812. );
  813. props.onClose();
  814. }}
  815. />,
  816. ]}
  817. >
  818. <List>
  819. <ListItem
  820. title={Locale.Chat.EditMessage.Topic.Title}
  821. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  822. >
  823. <input
  824. type="text"
  825. value={session.topic}
  826. onInput={(e) =>
  827. chatStore.updateCurrentSession(
  828. (session) => (session.topic = e.currentTarget.value),
  829. )
  830. }
  831. ></input>
  832. </ListItem>
  833. </List>
  834. <ContextPrompts
  835. context={messages}
  836. updateContext={(updater) => {
  837. const newMessages = messages.slice();
  838. updater(newMessages);
  839. setMessages(newMessages);
  840. }}
  841. />
  842. </Modal>
  843. </div>
  844. );
  845. }
  846. export function DeleteImageButton(props: { deleteImage: () => void }) {
  847. return (
  848. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  849. <DeleteIcon />
  850. </div>
  851. );
  852. }
  853. function _Chat() {
  854. type RenderMessage = ChatMessage & { preview?: boolean };
  855. const chatStore = useChatStore();
  856. const session = chatStore.currentSession();
  857. const config = useAppConfig();
  858. const fontSize = config.fontSize;
  859. const fontFamily = config.fontFamily;
  860. const [showExport, setShowExport] = useState(false);
  861. const inputRef = useRef<HTMLTextAreaElement>(null);
  862. const [userInput, setUserInput] = useState("");
  863. const [isLoading, setIsLoading] = useState(false);
  864. const { submitKey, shouldSubmit } = useSubmitHandler();
  865. const scrollRef = useRef<HTMLDivElement>(null);
  866. const isScrolledToBottom = scrollRef?.current
  867. ? Math.abs(
  868. scrollRef.current.scrollHeight -
  869. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  870. ) <= 1
  871. : false;
  872. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  873. scrollRef,
  874. isScrolledToBottom,
  875. );
  876. const [hitBottom, setHitBottom] = useState(true);
  877. const isMobileScreen = useMobileScreen();
  878. const navigate = useNavigate();
  879. const [attachImages, setAttachImages] = useState<string[]>([]);
  880. const [uploading, setUploading] = useState(false);
  881. // prompt hints
  882. const promptStore = usePromptStore();
  883. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  884. const onSearch = useDebouncedCallback(
  885. (text: string) => {
  886. const matchedPrompts = promptStore.search(text);
  887. setPromptHints(matchedPrompts);
  888. },
  889. 100,
  890. { leading: true, trailing: true },
  891. );
  892. const [loading, setLoading] = useState<boolean>(false);
  893. type AppList = {
  894. label: string,
  895. value: string,
  896. }[];
  897. const [appList, setAppList] = useState<AppList>([]);
  898. const [appValue, setAppValue] = useState<string>();
  899. const globalStore = useGlobalStore();
  900. type QuestionList = string[];
  901. const [questionList, setQuestionList] = useState<QuestionList>([]);
  902. const location = useLocation();
  903. // 获取应用列表
  904. const fetchApplicationList = async () => {
  905. setLoading(true);
  906. try {
  907. const res = await api.get('/bigmodel/api/application/list');
  908. const list = res.data.filter((item: any) => item.appId !== '1234567890123456789').map((item: any) => {
  909. return {
  910. label: item.name,
  911. value: item.appId,
  912. }
  913. })
  914. setAppList(list);
  915. let appValue = '';
  916. const search = location.search;
  917. if (search.startsWith('?appId=')) {
  918. const value = search.slice(7);
  919. if (list.find((item: any) => item.value === value)) {
  920. appValue = value;
  921. } else {
  922. appValue = list[0]?.value;
  923. }
  924. } else {
  925. appValue = list[0]?.value;
  926. }
  927. setAppValue(appValue);
  928. globalStore.setSelectedAppId(appValue);
  929. chatStore.updateCurrentSession((session) => {
  930. session.appId = appValue;
  931. });
  932. } catch (error) {
  933. console.error(error);
  934. } finally {
  935. setLoading(false);
  936. }
  937. }
  938. // 获取预设问题列表
  939. const fetchDefaultQuestion = async (appId: string) => {
  940. try {
  941. const res = await api.get(`/bigmodel/api/presets/${appId}`);
  942. setQuestionList(res.data);
  943. } catch (error) {
  944. console.error(error);
  945. } finally {
  946. setLoading(false);
  947. }
  948. }
  949. const init = async () => {
  950. await fetchApplicationList();
  951. }
  952. useEffect(() => {
  953. init();
  954. }, [])
  955. useEffect(() => {
  956. if (appValue) {
  957. fetchDefaultQuestion(appValue);
  958. }
  959. }, [appValue])
  960. const [inputRows, setInputRows] = useState(2);
  961. const measure = useDebouncedCallback(
  962. () => {
  963. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  964. const inputRows = Math.min(
  965. 20,
  966. Math.max(2 + Number(!isMobileScreen), rows),
  967. );
  968. setInputRows(inputRows);
  969. },
  970. 100,
  971. {
  972. leading: true,
  973. trailing: true,
  974. },
  975. );
  976. // eslint-disable-next-line react-hooks/exhaustive-deps
  977. useEffect(measure, [userInput]);
  978. // chat commands shortcuts
  979. const chatCommands = useChatCommand({
  980. new: () => chatStore.newSession(),
  981. newm: () => navigate(Path.NewChat),
  982. prev: () => chatStore.nextSession(-1),
  983. next: () => chatStore.nextSession(1),
  984. clear: () =>
  985. chatStore.updateCurrentSession(
  986. (session) => (session.clearContextIndex = session.messages.length),
  987. ),
  988. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  989. });
  990. // only search prompts when user input is short
  991. const SEARCH_TEXT_LIMIT = 30;
  992. const onInput = (text: string) => {
  993. setUserInput(text);
  994. const n = text.trim().length;
  995. // clear search results
  996. if (n === 0) {
  997. setPromptHints([]);
  998. } else if (text.match(ChatCommandPrefix)) {
  999. setPromptHints(chatCommands.search(text));
  1000. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  1001. // check if need to trigger auto completion
  1002. if (text.startsWith("/")) {
  1003. let searchText = text.slice(1);
  1004. onSearch(searchText);
  1005. }
  1006. }
  1007. };
  1008. const doSubmit = (userInput: string) => {
  1009. if (userInput.trim() === "") return;
  1010. const matchCommand = chatCommands.match(userInput);
  1011. if (matchCommand.matched) {
  1012. setUserInput("");
  1013. setPromptHints([]);
  1014. matchCommand.invoke();
  1015. return;
  1016. }
  1017. setIsLoading(true);
  1018. chatStore.onUserInput(userInput, attachImages).then(() => setIsLoading(false));
  1019. setAttachImages([]);
  1020. localStorage.setItem(LAST_INPUT_KEY, userInput);
  1021. setUserInput("");
  1022. setPromptHints([]);
  1023. if (!isMobileScreen) inputRef.current?.focus();
  1024. setAutoScroll(true);
  1025. };
  1026. const onPromptSelect = (prompt: RenderPrompt) => {
  1027. setTimeout(() => {
  1028. setPromptHints([]);
  1029. const matchedChatCommand = chatCommands.match(prompt.content);
  1030. if (matchedChatCommand.matched) {
  1031. // if user is selecting a chat command, just trigger it
  1032. matchedChatCommand.invoke();
  1033. setUserInput("");
  1034. } else {
  1035. // or fill the prompt
  1036. setUserInput(prompt.content);
  1037. }
  1038. inputRef.current?.focus();
  1039. }, 30);
  1040. };
  1041. // stop response
  1042. const onUserStop = (messageId: string) => {
  1043. ChatControllerPool.stop(session.id, messageId);
  1044. };
  1045. useEffect(() => {
  1046. chatStore.updateCurrentSession((session) => {
  1047. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  1048. session.messages.forEach((m) => {
  1049. // check if should stop all stale messages
  1050. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  1051. if (m.streaming) {
  1052. m.streaming = false;
  1053. }
  1054. if (m.content.length === 0) {
  1055. m.isError = true;
  1056. m.content = prettyObject({
  1057. error: true,
  1058. message: "empty response",
  1059. });
  1060. }
  1061. }
  1062. });
  1063. // auto sync mask config from global config
  1064. if (session.mask.syncGlobalConfig) {
  1065. console.log("[Mask] syncing from global, name = ", session.mask.name);
  1066. session.mask.modelConfig = { ...config.modelConfig };
  1067. }
  1068. });
  1069. // eslint-disable-next-line react-hooks/exhaustive-deps
  1070. }, []);
  1071. // check if should send message
  1072. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  1073. if (
  1074. e.key === "ArrowUp" &&
  1075. userInput.length <= 0 &&
  1076. !(e.metaKey || e.altKey || e.ctrlKey)
  1077. ) {
  1078. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  1079. e.preventDefault();
  1080. return;
  1081. }
  1082. if (shouldSubmit(e) && promptHints.length === 0) {
  1083. doSubmit(userInput);
  1084. e.preventDefault();
  1085. }
  1086. };
  1087. const onRightClick = (e: any, message: ChatMessage) => {
  1088. // copy to clipboard
  1089. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  1090. if (userInput.length === 0) {
  1091. setUserInput(getMessageTextContent(message));
  1092. }
  1093. e.preventDefault();
  1094. }
  1095. };
  1096. const deleteMessage = (msgId?: string) => {
  1097. chatStore.updateCurrentSession(
  1098. (session) =>
  1099. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  1100. );
  1101. };
  1102. const onDelete = (msgId: string) => {
  1103. deleteMessage(msgId);
  1104. };
  1105. const onResend = (message: ChatMessage) => {
  1106. // when it is resending a message
  1107. // 1. for a user's message, find the next bot response
  1108. // 2. for a bot's message, find the last user's input
  1109. // 3. delete original user input and bot's message
  1110. // 4. resend the user's input
  1111. const resendingIndex = session.messages.findIndex(
  1112. (m) => m.id === message.id,
  1113. );
  1114. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  1115. console.error("[Chat] failed to find resending message", message);
  1116. return;
  1117. }
  1118. let userMessage: ChatMessage | undefined;
  1119. let botMessage: ChatMessage | undefined;
  1120. if (message.role === "assistant") {
  1121. // if it is resending a bot's message, find the user input for it
  1122. botMessage = message;
  1123. for (let i = resendingIndex; i >= 0; i -= 1) {
  1124. if (session.messages[i].role === "user") {
  1125. userMessage = session.messages[i];
  1126. break;
  1127. }
  1128. }
  1129. } else if (message.role === "user") {
  1130. // if it is resending a user's input, find the bot's response
  1131. userMessage = message;
  1132. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  1133. if (session.messages[i].role === "assistant") {
  1134. botMessage = session.messages[i];
  1135. break;
  1136. }
  1137. }
  1138. }
  1139. if (userMessage === undefined) {
  1140. console.error("[Chat] failed to resend", message);
  1141. return;
  1142. }
  1143. // delete the original messages
  1144. deleteMessage(userMessage.id);
  1145. deleteMessage(botMessage?.id);
  1146. // resend the message
  1147. setIsLoading(true);
  1148. const textContent = getMessageTextContent(userMessage);
  1149. const images = getMessageImages(userMessage);
  1150. chatStore.onUserInput(textContent, images).then(() => setIsLoading(false));
  1151. inputRef.current?.focus();
  1152. };
  1153. const onPinMessage = (message: ChatMessage) => {
  1154. chatStore.updateCurrentSession((session) =>
  1155. session.mask.context.push(message),
  1156. );
  1157. showToast(Locale.Chat.Actions.PinToastContent, {
  1158. text: Locale.Chat.Actions.PinToastAction,
  1159. onClick: () => {
  1160. setShowPromptModal(true);
  1161. },
  1162. });
  1163. };
  1164. const context: RenderMessage[] = useMemo(() => {
  1165. return session.mask.hideContext ? [] : session.mask.context.slice();
  1166. }, [session.mask.context, session.mask.hideContext]);
  1167. const accessStore = useAccessStore();
  1168. if (
  1169. context.length === 0 &&
  1170. session.messages.at(0)?.content !== BOT_HELLO.content
  1171. ) {
  1172. const copiedHello = Object.assign({}, BOT_HELLO);
  1173. if (!accessStore.isAuthorized()) {
  1174. copiedHello.content = Locale.Error.Unauthorized;
  1175. }
  1176. context.push(copiedHello);
  1177. }
  1178. // preview messages
  1179. const renderMessages = useMemo(() => {
  1180. return context.concat(session.messages as RenderMessage[]).concat(
  1181. isLoading
  1182. ? [
  1183. {
  1184. ...createMessage({
  1185. role: "assistant",
  1186. content: "……",
  1187. }),
  1188. preview: true,
  1189. },
  1190. ]
  1191. : [],
  1192. ).concat(
  1193. userInput.length > 0 && config.sendPreviewBubble
  1194. ? [
  1195. {
  1196. ...createMessage({
  1197. role: "user",
  1198. content: userInput,
  1199. }),
  1200. preview: true,
  1201. },
  1202. ]
  1203. : [],
  1204. );
  1205. }, [
  1206. config.sendPreviewBubble,
  1207. context,
  1208. isLoading,
  1209. session.messages,
  1210. userInput,
  1211. ]);
  1212. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  1213. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1214. );
  1215. function setMsgRenderIndex(newIndex: number) {
  1216. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1217. newIndex = Math.max(0, newIndex);
  1218. _setMsgRenderIndex(newIndex);
  1219. }
  1220. const messages = useMemo(() => {
  1221. const endRenderIndex = Math.min(
  1222. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1223. renderMessages.length,
  1224. );
  1225. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1226. }, [msgRenderIndex, renderMessages]);
  1227. const onChatBodyScroll = (e: HTMLElement) => {
  1228. const bottomHeight = e.scrollTop + e.clientHeight;
  1229. const edgeThreshold = e.clientHeight;
  1230. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1231. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1232. const isHitBottom =
  1233. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1234. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1235. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1236. if (isTouchTopEdge && !isTouchBottomEdge) {
  1237. setMsgRenderIndex(prevPageMsgIndex);
  1238. } else if (isTouchBottomEdge) {
  1239. setMsgRenderIndex(nextPageMsgIndex);
  1240. }
  1241. setHitBottom(isHitBottom);
  1242. setAutoScroll(isHitBottom);
  1243. };
  1244. function scrollToBottom() {
  1245. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1246. scrollDomToBottom();
  1247. }
  1248. // clear context index = context length + index in messages
  1249. const clearContextIndex =
  1250. (session.clearContextIndex ?? -1) >= 0
  1251. ? session.clearContextIndex! + context.length - msgRenderIndex
  1252. : -1;
  1253. const [showPromptModal, setShowPromptModal] = useState(false);
  1254. const clientConfig = useMemo(() => getClientConfig(), []);
  1255. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1256. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1257. useCommand({
  1258. fill: setUserInput,
  1259. submit: (text) => {
  1260. doSubmit(text);
  1261. },
  1262. code: (text) => {
  1263. if (accessStore.disableFastLink) return;
  1264. console.log("[Command] got code from url: ", text);
  1265. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1266. if (res) {
  1267. accessStore.update((access) => (access.accessCode = text));
  1268. }
  1269. });
  1270. },
  1271. settings: (text) => {
  1272. if (accessStore.disableFastLink) return;
  1273. try {
  1274. const payload = JSON.parse(text) as {
  1275. key?: string;
  1276. url?: string;
  1277. };
  1278. console.log("[Command] got settings from url: ", payload);
  1279. if (payload.key || payload.url) {
  1280. showConfirm(
  1281. Locale.URLCommand.Settings +
  1282. `\n${JSON.stringify(payload, null, 4)}`,
  1283. ).then((res) => {
  1284. if (!res) return;
  1285. if (payload.key) {
  1286. accessStore.update(
  1287. (access) => (access.openaiApiKey = payload.key!),
  1288. );
  1289. }
  1290. if (payload.url) {
  1291. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1292. }
  1293. accessStore.update((access) => (access.useCustomConfig = true));
  1294. });
  1295. }
  1296. } catch {
  1297. console.error("[Command] failed to get settings from url: ", text);
  1298. }
  1299. },
  1300. });
  1301. // edit / insert message modal
  1302. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1303. // remember unfinished input
  1304. useEffect(() => {
  1305. // try to load from local storage
  1306. const key = UNFINISHED_INPUT(session.id);
  1307. const mayBeUnfinishedInput = localStorage.getItem(key);
  1308. if (mayBeUnfinishedInput && userInput.length === 0) {
  1309. setUserInput(mayBeUnfinishedInput);
  1310. localStorage.removeItem(key);
  1311. }
  1312. const dom = inputRef.current;
  1313. return () => {
  1314. localStorage.setItem(key, dom?.value ?? "");
  1315. };
  1316. // eslint-disable-next-line react-hooks/exhaustive-deps
  1317. }, []);
  1318. const handlePaste = useCallback(
  1319. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1320. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1321. if (!isVisionModel(currentModel)) {
  1322. return;
  1323. }
  1324. const items = (event.clipboardData || window.clipboardData).items;
  1325. for (const item of items) {
  1326. if (item.kind === "file" && item.type.startsWith("image/")) {
  1327. event.preventDefault();
  1328. const file = item.getAsFile();
  1329. if (file) {
  1330. const images: string[] = [];
  1331. images.push(...attachImages);
  1332. images.push(
  1333. ...(await new Promise<string[]>((res, rej) => {
  1334. setUploading(true);
  1335. const imagesData: string[] = [];
  1336. uploadImageRemote(file).then((dataUrl) => {
  1337. imagesData.push(dataUrl);
  1338. setUploading(false);
  1339. res(imagesData);
  1340. }).catch((e) => {
  1341. setUploading(false);
  1342. rej(e);
  1343. });
  1344. })),
  1345. );
  1346. const imagesLength = images.length;
  1347. if (imagesLength > 3) {
  1348. images.splice(3, imagesLength - 3);
  1349. }
  1350. setAttachImages(images);
  1351. }
  1352. }
  1353. }
  1354. },
  1355. [attachImages, chatStore],
  1356. );
  1357. async function uploadImage() {
  1358. const images: string[] = [];
  1359. images.push(...attachImages);
  1360. images.push(
  1361. ...(await new Promise<string[]>((res, rej) => {
  1362. const fileInput = document.createElement("input");
  1363. fileInput.type = "file";
  1364. fileInput.accept =
  1365. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1366. fileInput.multiple = true;
  1367. fileInput.onchange = (event: any) => {
  1368. setUploading(true);
  1369. const files = event.target.files;
  1370. const imagesData: string[] = [];
  1371. for (let i = 0; i < files.length; i++) {
  1372. const file = event.target.files[i];
  1373. uploadImageRemote(file).then((dataUrl) => {
  1374. imagesData.push(dataUrl);
  1375. if (
  1376. imagesData.length === 3 ||
  1377. imagesData.length === files.length
  1378. ) {
  1379. setUploading(false);
  1380. res(imagesData);
  1381. }
  1382. }).catch((e) => {
  1383. setUploading(false);
  1384. rej(e);
  1385. });
  1386. }
  1387. };
  1388. fileInput.click();
  1389. })),
  1390. );
  1391. const imagesLength = images.length;
  1392. if (imagesLength > 3) {
  1393. images.splice(3, imagesLength - 3);
  1394. }
  1395. setAttachImages(images);
  1396. }
  1397. const getAppName = () => {
  1398. const item = appList.find(item => item.value === appValue);
  1399. if (!item) {
  1400. return
  1401. }
  1402. return item.label;
  1403. }
  1404. return (
  1405. <div className={styles.chat} key={session.id}>
  1406. <div className="window-header" data-tauri-drag-region>
  1407. <div style={{ display: 'flex', alignItems: 'center' }}
  1408. className={`window-header-title ${styles["chat-body-title"]}`}>
  1409. <div>
  1410. {
  1411. isMobileScreen &&
  1412. <IconButton
  1413. style={{ padding: 0, marginRight: 20 }}
  1414. icon={<LeftIcon />}
  1415. text={Locale.NewChat.Return}
  1416. onClick={() => navigate('/knowledgeChat')}
  1417. />
  1418. }
  1419. </div>
  1420. <div>
  1421. {
  1422. appList.length > 1 ?
  1423. <Select
  1424. style={{ width: '100%', height: 38, marginRight: 5 }}
  1425. placeholder='请选择'
  1426. options={appList}
  1427. value={appValue}
  1428. onChange={(value) => {
  1429. setAppValue(value);
  1430. globalStore.setSelectedAppId(value);
  1431. chatStore.clearSessions();
  1432. chatStore.updateCurrentSession((values) => {
  1433. values.appId = value;
  1434. });
  1435. }}
  1436. />
  1437. :
  1438. null
  1439. }
  1440. </div>
  1441. </div>
  1442. <div className="window-actions">
  1443. <div className="window-action-button">
  1444. <Popover
  1445. trigger="click"
  1446. title="分享"
  1447. content={() => {
  1448. const url = `${window.location.origin}/#/knowledgeChat?appId=${appValue}`
  1449. return <div>
  1450. <div style={{ marginBottom: 10 }}>
  1451. {url}
  1452. </div>
  1453. <Button onClick={() => {
  1454. navigator.clipboard.writeText(url);
  1455. message.success('分享链接已复制到剪贴板');
  1456. }}>
  1457. 复制
  1458. </Button>
  1459. </div>
  1460. }
  1461. }>
  1462. <IconButton
  1463. icon={<ExportIcon />}
  1464. bordered
  1465. title={Locale.Chat.Actions.Export}
  1466. />
  1467. </Popover>
  1468. </div>
  1469. {/* {showMaxIcon && (
  1470. <div className="window-action-button">
  1471. <IconButton
  1472. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1473. bordered
  1474. title={Locale.Chat.Actions.FullScreen}
  1475. aria={Locale.Chat.Actions.FullScreen}
  1476. onClick={() => {
  1477. config.update(
  1478. (config) => (config.tightBorder = !config.tightBorder),
  1479. );
  1480. }}
  1481. />
  1482. </div>
  1483. )} */}
  1484. </div>
  1485. {/* <PromptToast
  1486. showToast={!hitBottom}
  1487. showModal={showPromptModal}
  1488. setShowModal={setShowPromptModal}
  1489. /> */}
  1490. </div>
  1491. <div
  1492. className={styles["chat-body"]}
  1493. ref={scrollRef}
  1494. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1495. onMouseDown={() => inputRef.current?.blur()}
  1496. onTouchStart={() => {
  1497. inputRef.current?.blur();
  1498. setAutoScroll(false);
  1499. }}
  1500. >
  1501. {
  1502. messages.length > 1 ?
  1503. <>
  1504. {messages.map((message, i) => {
  1505. const isUser = message.role === "user";
  1506. const isContext = i < context.length;
  1507. const showActions =
  1508. i > 0 &&
  1509. !(message.preview || message.content.length === 0) &&
  1510. !isContext;
  1511. const showTyping = message.preview || message.streaming;
  1512. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1513. return (
  1514. <Fragment key={message.id}>
  1515. <div
  1516. className={
  1517. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1518. }
  1519. >
  1520. <div className={styles["chat-message-container"]}>
  1521. <div className={styles["chat-message-header"]}>
  1522. <div className={styles["chat-message-avatar"]}>
  1523. {/* <div className={styles["chat-message-edit"]}>
  1524. <IconButton
  1525. icon={<EditIcon />}
  1526. aria={Locale.Chat.Actions.Edit}
  1527. onClick={async () => {
  1528. const newMessage = await showPrompt(
  1529. Locale.Chat.Actions.Edit,
  1530. getMessageTextContent(message),
  1531. 10,
  1532. );
  1533. let newContent: string | MultimodalContent[] =
  1534. newMessage;
  1535. const images = getMessageImages(message);
  1536. if (images.length > 0) {
  1537. newContent = [{ type: "text", text: newMessage }];
  1538. for (let i = 0; i < images.length; i++) {
  1539. newContent.push({
  1540. type: "image_url",
  1541. image_url: {
  1542. url: images[i],
  1543. },
  1544. });
  1545. }
  1546. }
  1547. chatStore.updateCurrentSession((session) => {
  1548. const m = session.mask.context
  1549. .concat(session.messages)
  1550. .find((m) => m.id === message.id);
  1551. if (m) {
  1552. m.content = newContent;
  1553. }
  1554. });
  1555. }}
  1556. ></IconButton>
  1557. </div> */}
  1558. {isUser ? (
  1559. // 在这里换头像
  1560. <div style={{ position: 'relative' }}>
  1561. {/* <MaskAvatar */}
  1562. {/* avatar={session.mask.avatar} */}
  1563. {/* /> */}
  1564. {/* <div */}
  1565. {/* style={{ */}
  1566. {/* position: 'absolute', */}
  1567. {/* zIndex: 2, */}
  1568. {/* top: '50%', */}
  1569. {/* left: '50%', */}
  1570. {/* transform: ' translate(-50%, -50%)', */}
  1571. {/* fontSize: 14, */}
  1572. {/* }}> */}
  1573. {/* 我 */}
  1574. {/* </div> */}
  1575. <div
  1576. style={{
  1577. position: 'absolute',
  1578. zIndex: 2,
  1579. top: '50%',
  1580. left: '50%',
  1581. transform: ' translate(-110%, -100%)',
  1582. fontSize: 14,
  1583. }}>
  1584. </div>
  1585. </div>
  1586. ) : (
  1587. <>
  1588. {["system"].includes(message.role) ? (
  1589. <Avatar avatar="2699-fe0f" />
  1590. ) : (
  1591. <MaskAvatar
  1592. avatar={session.mask.avatar}
  1593. model={
  1594. message.model || session.mask.modelConfig.model
  1595. }
  1596. />
  1597. )}
  1598. </>
  1599. )}
  1600. </div>
  1601. {/* {showActions && (
  1602. <div className={styles["chat-message-actions"]}>
  1603. <div className={styles["chat-input-actions"]}>
  1604. {message.streaming ? (
  1605. <ChatAction
  1606. text={Locale.Chat.Actions.Stop}
  1607. icon={<StopIcon />}
  1608. onClick={() => onUserStop(message.id ?? i)}
  1609. />
  1610. ) : (
  1611. <>
  1612. <ChatAction
  1613. text={Locale.Chat.Actions.Retry}
  1614. icon={<ResetIcon />}
  1615. onClick={() => onResend(message)}
  1616. />
  1617. <ChatAction
  1618. text={Locale.Chat.Actions.Delete}
  1619. icon={<DeleteIcon />}
  1620. onClick={() => onDelete(message.id ?? i)}
  1621. />
  1622. <ChatAction
  1623. text={Locale.Chat.Actions.Pin}
  1624. icon={<PinIcon />}
  1625. onClick={() => onPinMessage(message)}
  1626. />
  1627. <ChatAction
  1628. text={Locale.Chat.Actions.Copy}
  1629. icon={<CopyIcon />}
  1630. onClick={() =>
  1631. copyToClipboard(
  1632. getMessageTextContent(message),
  1633. )
  1634. }
  1635. />
  1636. </>
  1637. )}
  1638. </div>
  1639. </div>
  1640. )} */}
  1641. </div>
  1642. {showTyping && (
  1643. <div className={styles["chat-message-status"]}>
  1644. {Locale.Chat.Typing}
  1645. </div>
  1646. )}
  1647. <div className={styles["chat-message-item"]}>
  1648. <Markdown
  1649. key={message.streaming ? "loading" : "done"}
  1650. content={getMessageTextContent(message)}
  1651. loading={
  1652. (message.preview || message.streaming) &&
  1653. message.content.length === 0 &&
  1654. !isUser
  1655. }
  1656. // onContextMenu={(e) => onRightClick(e, message)}
  1657. onDoubleClickCapture={() => {
  1658. if (!isMobileScreen) return;
  1659. setUserInput(getMessageTextContent(message));
  1660. }}
  1661. fontSize={fontSize}
  1662. fontFamily={fontFamily}
  1663. parentRef={scrollRef}
  1664. defaultShow={i >= messages.length - 6}
  1665. />
  1666. {getMessageImages(message).length == 1 && (
  1667. <img
  1668. className={styles["chat-message-item-image"]}
  1669. src={getMessageImages(message)[0]}
  1670. alt=""
  1671. />
  1672. )}
  1673. {getMessageImages(message).length > 1 && (
  1674. <div
  1675. className={styles["chat-message-item-images"]}
  1676. style={
  1677. {
  1678. "--image-count": getMessageImages(message).length,
  1679. } as React.CSSProperties
  1680. }
  1681. >
  1682. {getMessageImages(message).map((image, index) => {
  1683. return (
  1684. <img
  1685. className={
  1686. styles["chat-message-item-image-multi"]
  1687. }
  1688. key={index}
  1689. src={image}
  1690. alt=""
  1691. />
  1692. );
  1693. })}
  1694. </div>
  1695. )}
  1696. </div>
  1697. {/* <div className={styles["chat-message-action-date"]}>
  1698. {isContext
  1699. ? Locale.Chat.IsContext
  1700. : message.date.toLocaleString()}
  1701. </div> */}
  1702. </div>
  1703. </div>
  1704. {shouldShowClearContextDivider && <ClearContextDivider />}
  1705. </Fragment>
  1706. );
  1707. })}
  1708. </>
  1709. :
  1710. <>
  1711. <div style={{ padding: '0 20px' }}>
  1712. <div style={{ display: 'flex', justifyContent: 'center' }}>
  1713. <img style={{ width: 80, height: 80 }} src={avatarSrc.src} />
  1714. </div>
  1715. <h1 style={{ textAlign: 'center' }}>
  1716. {getAppName()}
  1717. </h1>
  1718. <p style={{ textAlign: 'center' }}>创建人: admin</p>
  1719. <p style={{ textAlign: 'center' }}>
  1720. 您好,欢迎使用建科·小智使用知识库创建的{getAppName()}
  1721. </p>
  1722. <p style={{ textAlign: 'center' }}>如果需要问本企业相关的其他问题请点击左上角,选中切换的知识库问答应用使用</p>
  1723. <p>我猜您可能想问:</p>
  1724. {
  1725. questionList.map((item, index) => {
  1726. return (
  1727. <div
  1728. style={{
  1729. padding: '10px',
  1730. marginBottom: '10px',
  1731. border: '1px solid #e6e8f1',
  1732. borderRadius: '10px',
  1733. fontSize: '16px',
  1734. display: 'flex',
  1735. justifyContent: 'space-between',
  1736. alignItems: 'center',
  1737. cursor: 'pointer'
  1738. }}
  1739. onClick={() => {
  1740. setUserInput(item)
  1741. doSubmit(item)
  1742. }}
  1743. key={index}
  1744. >
  1745. <div>
  1746. {item}
  1747. </div>
  1748. <RightOutlined />
  1749. </div>
  1750. )
  1751. })
  1752. }
  1753. </div>
  1754. </>
  1755. }
  1756. </div>
  1757. <div className={styles["chat-input-panel"]}>
  1758. {/* <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} /> */}
  1759. <ChatActions
  1760. setUserInput={setUserInput}
  1761. doSubmit={doSubmit}
  1762. uploadImage={uploadImage}
  1763. setAttachImages={setAttachImages}
  1764. setUploading={setUploading}
  1765. showPromptModal={() => setShowPromptModal(true)}
  1766. scrollToBottom={scrollToBottom}
  1767. hitBottom={hitBottom}
  1768. uploading={uploading}
  1769. showPromptHints={() => {
  1770. // Click again to close
  1771. if (promptHints.length > 0) {
  1772. setPromptHints([]);
  1773. return;
  1774. }
  1775. inputRef.current?.focus();
  1776. setUserInput("/");
  1777. onSearch("");
  1778. }}
  1779. />
  1780. <label
  1781. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  1782. ? styles["chat-input-panel-inner-attach"]
  1783. : ""
  1784. }`}
  1785. htmlFor="chat-input"
  1786. >
  1787. <textarea
  1788. id="chat-input"
  1789. ref={inputRef}
  1790. className={styles["chat-input"]}
  1791. placeholder={Locale.Chat.Input(submitKey)}
  1792. onInput={(e) => onInput(e.currentTarget.value)}
  1793. value={userInput}
  1794. onKeyDown={onInputKeyDown}
  1795. onFocus={scrollToBottom}
  1796. onClick={scrollToBottom}
  1797. onPaste={handlePaste}
  1798. rows={inputRows}
  1799. autoFocus={autoFocus}
  1800. style={{
  1801. fontSize: config.fontSize,
  1802. fontFamily: config.fontFamily,
  1803. }}
  1804. />
  1805. {attachImages.length != 0 && (
  1806. <div className={styles["attach-images"]}>
  1807. {attachImages.map((image, index) => {
  1808. return (
  1809. <div
  1810. key={index}
  1811. className={styles["attach-image"]}
  1812. style={{ backgroundImage: `url("${image}")` }}
  1813. >
  1814. <div className={styles["attach-image-mask"]}>
  1815. <DeleteImageButton
  1816. deleteImage={() => {
  1817. setAttachImages(
  1818. attachImages.filter((_, i) => i !== index),
  1819. );
  1820. }}
  1821. />
  1822. </div>
  1823. </div>
  1824. );
  1825. })}
  1826. </div>
  1827. )}
  1828. <IconButton
  1829. icon={<SendWhiteIcon />}
  1830. text='发送'
  1831. className={styles["chat-input-send"]}
  1832. type="primary"
  1833. onClick={() => doSubmit(userInput)}
  1834. />
  1835. </label>
  1836. </div>
  1837. {showExport && (
  1838. <ExportMessageModal onClose={() => setShowExport(false)} />
  1839. )}
  1840. {isEditingMessage && (
  1841. <EditMessageModal
  1842. onClose={() => {
  1843. setIsEditingMessage(false);
  1844. }}
  1845. />
  1846. )}
  1847. </div>
  1848. );
  1849. }
  1850. export function Chat() {
  1851. const chatStore = useChatStore();
  1852. const sessionIndex = chatStore.currentSessionIndex;
  1853. useEffect(() => {
  1854. chatStore.setModel('BigModel');
  1855. }, []);
  1856. return <_Chat key={sessionIndex}></_Chat>;
  1857. }