chat.tsx 63 KB

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