chat.tsx 70 KB

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