chat.tsx 61 KB

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