chat.tsx 64 KB

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