chat.tsx 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033
  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. const messages = session.messages.slice();
  579. if (messages.length > 1) {
  580. const backList = messages.reverse();
  581. const item = backList.find(item => item.content && item.role === 'assistant')
  582. if (!item) {
  583. return
  584. }
  585. fetchGuessList(item)
  586. }
  587. }, [session.messages]);
  588. return (
  589. <div className={styles["chat-input-actions"]}>
  590. {guessList.length > 0 && (
  591. <div style={{ color: '#8096ca', fontSize: 13 }}>
  592. <div>
  593. 你还可以尝试提问:
  594. </div>
  595. <div style={{ display: 'flex', marginTop: 10, flexWrap: 'wrap' }}>
  596. {
  597. guessList.map((item, index) => {
  598. return (
  599. <div
  600. style={{
  601. padding: '5px 10px',
  602. background: '#f2f4f8',
  603. borderRadius: 5,
  604. margin: '0 10px 10px 0',
  605. cursor: 'pointer',
  606. }}
  607. onClick={() => {
  608. props.setUserInput(item);
  609. }}
  610. key={index}
  611. >
  612. {item}
  613. </div>
  614. )
  615. })
  616. }
  617. </div>
  618. </div>
  619. )}
  620. {/* {couldStop && (
  621. <ChatAction
  622. onClick={stopAll}
  623. text={Locale.Chat.InputActions.Stop}
  624. icon={<StopIcon />}
  625. />
  626. )} */}
  627. {/* {!props.hitBottom && (
  628. <ChatAction
  629. onClick={props.scrollToBottom}
  630. text={Locale.Chat.InputActions.ToBottom}
  631. icon={<BottomIcon />}
  632. />
  633. )} */}
  634. {/* {props.hitBottom && (
  635. <ChatAction
  636. onClick={props.showPromptModal}
  637. text={Locale.Chat.InputActions.Settings}
  638. icon={<SettingsIcon />}
  639. />
  640. )} */}
  641. {/* {showUploadImage && (
  642. <ChatAction
  643. onClick={props.uploadImage}
  644. text={Locale.Chat.InputActions.UploadImage}
  645. icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />}
  646. />
  647. )} */}
  648. {/* <ChatAction
  649. onClick={nextTheme}
  650. text={Locale.Chat.InputActions.Theme[theme]}
  651. icon={
  652. <>
  653. {theme === Theme.Auto ? (
  654. <AutoIcon />
  655. ) : theme === Theme.Light ? (
  656. <LightIcon />
  657. ) : theme === Theme.Dark ? (
  658. <DarkIcon />
  659. ) : null}
  660. </>
  661. }
  662. /> */}
  663. {/* <CallWord */}
  664. {/* setUserInput={props.setUserInput} */}
  665. {/* doSubmit={props.doSubmit} */}
  666. {/* /> */}
  667. {/* <ChatAction
  668. onClick={props.showPromptHints}
  669. text={Locale.Chat.InputActions.Prompt}
  670. icon={<PromptIcon />}
  671. /> */}
  672. {/* <ChatAction
  673. onClick={() => {
  674. navigate(Path.Masks);
  675. }}
  676. text={Locale.Chat.InputActions.Masks}
  677. icon={<MaskIcon />}
  678. /> */}
  679. {/* <ChatAction
  680. text={Locale.Chat.InputActions.Clear}
  681. icon={<BreakIcon />}
  682. onClick={() => {
  683. chatStore.updateCurrentSession((session) => {
  684. if (session.clearContextIndex === session.messages.length) {
  685. session.clearContextIndex = undefined;
  686. } else {
  687. session.clearContextIndex = session.messages.length;
  688. session.memoryPrompt = ""; // will clear memory
  689. }
  690. });
  691. }}
  692. /> */}
  693. {/* <ChatAction
  694. onClick={() => setShowModelSelector(true)}
  695. text={currentModelName}
  696. icon={<RobotIcon />}
  697. /> */}
  698. {showModelSelector && (
  699. <Selector
  700. defaultSelectedValue={`${currentModel}@${currentProviderName}`}
  701. items={models.map((m) => ({
  702. title: `${m.displayName}${m?.provider?.providerName
  703. ? "(" + m?.provider?.providerName + ")"
  704. : ""
  705. }`,
  706. value: `${m.name}@${m?.provider?.providerName}`,
  707. }))}
  708. onClose={() => setShowModelSelector(false)}
  709. onSelection={(s) => {
  710. if (s.length === 0) return;
  711. const [model, providerName] = s[0].split("@");
  712. chatStore.updateCurrentSession((session) => {
  713. session.mask.modelConfig.model = model as ModelType;
  714. session.mask.modelConfig.providerName =
  715. providerName as ServiceProvider;
  716. session.mask.syncGlobalConfig = false;
  717. });
  718. if (providerName == "ByteDance") {
  719. const selectedModel = models.find(
  720. (m) =>
  721. m.name == model && m?.provider?.providerName == providerName,
  722. );
  723. showToast(selectedModel?.displayName ?? "");
  724. } else {
  725. showToast(model);
  726. }
  727. }}
  728. />
  729. )}
  730. {isDalle3(currentModel) && (
  731. <ChatAction
  732. onClick={() => setShowSizeSelector(true)}
  733. text={currentSize}
  734. icon={<SizeIcon />}
  735. />
  736. )}
  737. {showSizeSelector && (
  738. <Selector
  739. defaultSelectedValue={currentSize}
  740. items={dalle3Sizes.map((m) => ({
  741. title: m,
  742. value: m,
  743. }))}
  744. onClose={() => setShowSizeSelector(false)}
  745. onSelection={(s) => {
  746. if (s.length === 0) return;
  747. const size = s[0];
  748. chatStore.updateCurrentSession((session) => {
  749. session.mask.modelConfig.size = size;
  750. });
  751. showToast(size);
  752. }}
  753. />
  754. )}
  755. {/* <ChatAction
  756. onClick={() => setShowPluginSelector(true)}
  757. text={Locale.Plugin.Name}
  758. icon={<PluginIcon />}
  759. /> */}
  760. {showPluginSelector && (
  761. <Selector
  762. multiple
  763. defaultSelectedValue={chatStore.currentSession().mask?.plugin}
  764. items={[
  765. {
  766. title: Locale.Plugin.Artifacts,
  767. value: Plugin.Artifacts,
  768. },
  769. ]}
  770. onClose={() => setShowPluginSelector(false)}
  771. onSelection={(s) => {
  772. const plugin = s[0];
  773. chatStore.updateCurrentSession((session) => {
  774. session.mask.plugin = s;
  775. });
  776. if (plugin) {
  777. showToast(plugin);
  778. }
  779. }}
  780. />
  781. )}
  782. </div>
  783. );
  784. }
  785. export function EditMessageModal(props: { onClose: () => void }) {
  786. const chatStore = useChatStore();
  787. const session = chatStore.currentSession();
  788. const [messages, setMessages] = useState(session.messages.slice());
  789. return (
  790. <div className="modal-mask">
  791. <Modal
  792. title={Locale.Chat.EditMessage.Title}
  793. onClose={props.onClose}
  794. actions={[
  795. <IconButton
  796. text={Locale.UI.Cancel}
  797. icon={<CancelIcon />}
  798. key="cancel"
  799. onClick={() => {
  800. props.onClose();
  801. }}
  802. />,
  803. <IconButton
  804. type="primary"
  805. text={Locale.UI.Confirm}
  806. icon={<ConfirmIcon />}
  807. key="ok"
  808. onClick={() => {
  809. chatStore.updateCurrentSession(
  810. (session) => (session.messages = messages),
  811. );
  812. props.onClose();
  813. }}
  814. />,
  815. ]}
  816. >
  817. <List>
  818. <ListItem
  819. title={Locale.Chat.EditMessage.Topic.Title}
  820. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  821. >
  822. <input
  823. type="text"
  824. value={session.topic}
  825. onInput={(e) =>
  826. chatStore.updateCurrentSession(
  827. (session) => (session.topic = e.currentTarget.value),
  828. )
  829. }
  830. ></input>
  831. </ListItem>
  832. </List>
  833. <ContextPrompts
  834. context={messages}
  835. updateContext={(updater) => {
  836. const newMessages = messages.slice();
  837. updater(newMessages);
  838. setMessages(newMessages);
  839. }}
  840. />
  841. </Modal>
  842. </div>
  843. );
  844. }
  845. export function DeleteImageButton(props: { deleteImage: () => void }) {
  846. return (
  847. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  848. <DeleteIcon />
  849. </div>
  850. );
  851. }
  852. function _Chat() {
  853. type RenderMessage = ChatMessage & { preview?: boolean };
  854. const chatStore = useChatStore();
  855. const session = chatStore.currentSession();
  856. const config = useAppConfig();
  857. const fontSize = config.fontSize;
  858. const fontFamily = config.fontFamily;
  859. const [showExport, setShowExport] = useState(false);
  860. const inputRef = useRef<HTMLTextAreaElement>(null);
  861. const [userInput, setUserInput] = useState("");
  862. const [isLoading, setIsLoading] = useState(false);
  863. const { submitKey, shouldSubmit } = useSubmitHandler();
  864. const scrollRef = useRef<HTMLDivElement>(null);
  865. const isScrolledToBottom = scrollRef?.current
  866. ? Math.abs(
  867. scrollRef.current.scrollHeight -
  868. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  869. ) <= 1
  870. : false;
  871. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  872. scrollRef,
  873. isScrolledToBottom,
  874. );
  875. const [hitBottom, setHitBottom] = useState(true);
  876. const isMobileScreen = useMobileScreen();
  877. const navigate = useNavigate();
  878. const [attachImages, setAttachImages] = useState<string[]>([]);
  879. const [uploading, setUploading] = useState(false);
  880. // prompt hints
  881. const promptStore = usePromptStore();
  882. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  883. const onSearch = useDebouncedCallback(
  884. (text: string) => {
  885. const matchedPrompts = promptStore.search(text);
  886. setPromptHints(matchedPrompts);
  887. },
  888. 100,
  889. { leading: true, trailing: true },
  890. );
  891. const [loading, setLoading] = useState<boolean>(false);
  892. type AppList = {
  893. label: string,
  894. value: string,
  895. }[];
  896. const [appList, setAppList] = useState<AppList>([]);
  897. const [appValue, setAppValue] = useState<string>();
  898. const globalStore = useGlobalStore();
  899. type QuestionList = {
  900. key: string,
  901. title: string,
  902. content: string,
  903. }[];
  904. const [questionList, setQuestionList] = useState<QuestionList>([]);
  905. const location = useLocation();
  906. // 获取应用列表
  907. const fetchApplicationList = async () => {
  908. setLoading(true);
  909. try {
  910. const res = await api.get('/bigmodel/api/application/list');
  911. const list = res.data.filter((item: any) => item.appId !== '1234567890123456789').map((item: any) => {
  912. return {
  913. label: item.name,
  914. value: item.appId,
  915. }
  916. })
  917. setAppList(list);
  918. let appValue = '';
  919. const search = location.search;
  920. if (search.startsWith('?appId=')) {
  921. const value = search.slice(7);
  922. if (list.find((item: any) => item.value === value)) {
  923. appValue = value;
  924. } else {
  925. appValue = list[0]?.value;
  926. }
  927. } else {
  928. appValue = list[0]?.value;
  929. }
  930. setAppValue(appValue);
  931. globalStore.setSelectedAppId(appValue);
  932. chatStore.updateCurrentSession((session) => {
  933. session.appId = appValue;
  934. });
  935. } catch (error) {
  936. console.error(error);
  937. } finally {
  938. setLoading(false);
  939. }
  940. }
  941. const fetchDefaultQuestion = async () => {
  942. try {
  943. const res = await api.get('/bigmodel/api/presets');
  944. setQuestionList(res.data);
  945. } catch (error) {
  946. console.error(error);
  947. } finally {
  948. setLoading(false);
  949. }
  950. }
  951. const init = async () => {
  952. await fetchApplicationList();
  953. await fetchDefaultQuestion();
  954. }
  955. useEffect(() => {
  956. init();
  957. }, [])
  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.content)
  1772. }}
  1773. key={index}
  1774. >
  1775. <div>
  1776. {item.title}
  1777. </div>
  1778. <RightOutlined />
  1779. </div>
  1780. )
  1781. })
  1782. }
  1783. </div>
  1784. </>
  1785. }
  1786. </div>
  1787. <div className={styles["chat-input-panel"]}>
  1788. {/* <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} /> */}
  1789. <ChatActions
  1790. setUserInput={setUserInput}
  1791. doSubmit={doSubmit}
  1792. uploadImage={uploadImage}
  1793. setAttachImages={setAttachImages}
  1794. setUploading={setUploading}
  1795. showPromptModal={() => setShowPromptModal(true)}
  1796. scrollToBottom={scrollToBottom}
  1797. hitBottom={hitBottom}
  1798. uploading={uploading}
  1799. showPromptHints={() => {
  1800. // Click again to close
  1801. if (promptHints.length > 0) {
  1802. setPromptHints([]);
  1803. return;
  1804. }
  1805. inputRef.current?.focus();
  1806. setUserInput("/");
  1807. onSearch("");
  1808. }}
  1809. />
  1810. <label
  1811. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  1812. ? styles["chat-input-panel-inner-attach"]
  1813. : ""
  1814. }`}
  1815. htmlFor="chat-input"
  1816. >
  1817. <textarea
  1818. id="chat-input"
  1819. ref={inputRef}
  1820. className={styles["chat-input"]}
  1821. placeholder={Locale.Chat.Input(submitKey)}
  1822. onInput={(e) => onInput(e.currentTarget.value)}
  1823. value={userInput}
  1824. onKeyDown={onInputKeyDown}
  1825. onFocus={scrollToBottom}
  1826. onClick={scrollToBottom}
  1827. onPaste={handlePaste}
  1828. rows={inputRows}
  1829. autoFocus={autoFocus}
  1830. style={{
  1831. fontSize: config.fontSize,
  1832. fontFamily: config.fontFamily,
  1833. }}
  1834. />
  1835. {attachImages.length != 0 && (
  1836. <div className={styles["attach-images"]}>
  1837. {attachImages.map((image, index) => {
  1838. return (
  1839. <div
  1840. key={index}
  1841. className={styles["attach-image"]}
  1842. style={{ backgroundImage: `url("${image}")` }}
  1843. >
  1844. <div className={styles["attach-image-mask"]}>
  1845. <DeleteImageButton
  1846. deleteImage={() => {
  1847. setAttachImages(
  1848. attachImages.filter((_, i) => i !== index),
  1849. );
  1850. }}
  1851. />
  1852. </div>
  1853. </div>
  1854. );
  1855. })}
  1856. </div>
  1857. )}
  1858. <IconButton
  1859. icon={<SendWhiteIcon />}
  1860. text='发送'
  1861. className={styles["chat-input-send"]}
  1862. type="primary"
  1863. onClick={() => doSubmit(userInput)}
  1864. />
  1865. </label>
  1866. </div>
  1867. {showExport && (
  1868. <ExportMessageModal onClose={() => setShowExport(false)} />
  1869. )}
  1870. {isEditingMessage && (
  1871. <EditMessageModal
  1872. onClose={() => {
  1873. setIsEditingMessage(false);
  1874. }}
  1875. />
  1876. )}
  1877. </div>
  1878. );
  1879. }
  1880. export function Chat() {
  1881. const chatStore = useChatStore();
  1882. const sessionIndex = chatStore.currentSessionIndex;
  1883. return <_Chat key={sessionIndex}></_Chat>;
  1884. }