chat.tsx 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312
  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. chat_id: session.chat_id,
  582. }
  583. let url = '';
  584. if (chatStore.chatMode === 'LOCAL') {
  585. url = '/deepseek/api/async/completions';
  586. } else {
  587. url = '/bigmodel/api/async/completions';
  588. }
  589. const res = await api.post(url, data);
  590. setGuessList(res.data);
  591. } catch (error) {
  592. console.error(error);
  593. }
  594. }
  595. useEffect(() => {
  596. setGuessList([]);
  597. if (chatStore.message.content) {
  598. fetchGuessList(chatStore.message);
  599. }
  600. }, [chatStore.message]);
  601. useEffect(() => {
  602. if (props.isClickStop) {
  603. props.setSendStatus(false);
  604. setGuessList([]);
  605. }
  606. }, [props.isClickStop])
  607. return (
  608. <div className={styles["chat-input-actions"]}>
  609. {
  610. props.sendStatus &&
  611. <div style={{ color: '#8096ca', fontSize: 13, overflowX: 'auto' }}>
  612. <div>
  613. 你还可以尝试提问:
  614. </div>
  615. {
  616. guessList.length === 0 ?
  617. <Space style={{ margin: '10px 0' }}>
  618. <Skeleton.Button size="small" active={true} />
  619. <Skeleton.Button size="small" active={true} />
  620. <Skeleton.Button size="small" active={true} />
  621. </Space>
  622. :
  623. <div style={{ display: 'flex', margin: '10px 0', overflowX: 'auto' }}>
  624. {
  625. guessList.map((item, index) => {
  626. return (
  627. <div
  628. style={{
  629. padding: '5px 10px',
  630. background: '#f2f4f8',
  631. borderRadius: 5,
  632. margin: '0 10px 10px 0',
  633. cursor: 'pointer',
  634. }}
  635. onClick={() => {
  636. props.setUserInput(item);
  637. props.doSubmit(item)
  638. }}
  639. key={index}
  640. >
  641. {item}
  642. </div>
  643. )
  644. })
  645. }
  646. </div>
  647. }
  648. </div>
  649. }
  650. {/* {couldStop && (
  651. <ChatAction
  652. onClick={stopAll}
  653. text={Locale.Chat.InputActions.Stop}
  654. icon={<StopIcon />}
  655. />
  656. )} */}
  657. {/* {!props.hitBottom && (
  658. <ChatAction
  659. onClick={props.scrollToBottom}
  660. text={Locale.Chat.InputActions.ToBottom}
  661. icon={<BottomIcon />}
  662. />
  663. )} */}
  664. {/* {props.hitBottom && (
  665. <ChatAction
  666. onClick={props.showPromptModal}
  667. text={Locale.Chat.InputActions.Settings}
  668. icon={<SettingsIcon />}
  669. />
  670. )} */}
  671. {/* {showUploadImage && (
  672. <ChatAction
  673. onClick={props.uploadImage}
  674. text={Locale.Chat.InputActions.UploadImage}
  675. icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />}
  676. />
  677. )} */}
  678. {/* <ChatAction
  679. onClick={nextTheme}
  680. text={Locale.Chat.InputActions.Theme[theme]}
  681. icon={
  682. <>
  683. {theme === Theme.Auto ? (
  684. <AutoIcon />
  685. ) : theme === Theme.Light ? (
  686. <LightIcon />
  687. ) : theme === Theme.Dark ? (
  688. <DarkIcon />
  689. ) : null}
  690. </>
  691. }
  692. /> */}
  693. {/* <CallWord */}
  694. {/* setUserInput={props.setUserInput} */}
  695. {/* doSubmit={props.doSubmit} */}
  696. {/* /> */}
  697. {/* <ChatAction
  698. onClick={props.showPromptHints}
  699. text={Locale.Chat.InputActions.Prompt}
  700. icon={<PromptIcon />}
  701. /> */}
  702. {/* <ChatAction
  703. onClick={() => {
  704. navigate(Path.Masks);
  705. }}
  706. text={Locale.Chat.InputActions.Masks}
  707. icon={<MaskIcon />}
  708. /> */}
  709. {/* <ChatAction
  710. text={Locale.Chat.InputActions.Clear}
  711. icon={<BreakIcon />}
  712. onClick={() => {
  713. chatStore.updateCurrentSession((session) => {
  714. if (session.clearContextIndex === session.messages.length) {
  715. session.clearContextIndex = undefined;
  716. } else {
  717. session.clearContextIndex = session.messages.length;
  718. session.memoryPrompt = ""; // will clear memory
  719. }
  720. });
  721. }}
  722. /> */}
  723. {/* <ChatAction
  724. onClick={() => setShowModelSelector(true)}
  725. text={currentModelName}
  726. icon={<RobotIcon />}
  727. /> */}
  728. {showModelSelector && (
  729. <Selector
  730. defaultSelectedValue={`${currentModel}@${currentProviderName}`}
  731. items={models.map((m) => ({
  732. title: `${m.displayName}${m?.provider?.providerName
  733. ? "(" + m?.provider?.providerName + ")"
  734. : ""
  735. }`,
  736. value: `${m.name}@${m?.provider?.providerName}`,
  737. }))}
  738. onClose={() => setShowModelSelector(false)}
  739. onSelection={(s) => {
  740. if (s.length === 0) return;
  741. const [model, providerName] = s[0].split("@");
  742. chatStore.updateCurrentSession((session) => {
  743. session.mask.modelConfig.model = model as ModelType;
  744. session.mask.modelConfig.providerName =
  745. providerName as ServiceProvider;
  746. session.mask.syncGlobalConfig = false;
  747. });
  748. if (providerName == "ByteDance") {
  749. const selectedModel = models.find(
  750. (m) =>
  751. m.name == model && m?.provider?.providerName == providerName,
  752. );
  753. showToast(selectedModel?.displayName ?? "");
  754. } else {
  755. showToast(model);
  756. }
  757. }}
  758. />
  759. )}
  760. {isDalle3(currentModel) && (
  761. <ChatAction
  762. onClick={() => setShowSizeSelector(true)}
  763. text={currentSize}
  764. icon={<SizeIcon />}
  765. />
  766. )}
  767. {showSizeSelector && (
  768. <Selector
  769. defaultSelectedValue={currentSize}
  770. items={dalle3Sizes.map((m) => ({
  771. title: m,
  772. value: m,
  773. }))}
  774. onClose={() => setShowSizeSelector(false)}
  775. onSelection={(s) => {
  776. if (s.length === 0) return;
  777. const size = s[0];
  778. chatStore.updateCurrentSession((session) => {
  779. session.mask.modelConfig.size = size;
  780. });
  781. showToast(size);
  782. }}
  783. />
  784. )}
  785. {/* <ChatAction
  786. onClick={() => setShowPluginSelector(true)}
  787. text={Locale.Plugin.Name}
  788. icon={<PluginIcon />}
  789. /> */}
  790. {showPluginSelector && (
  791. <Selector
  792. multiple
  793. defaultSelectedValue={chatStore.currentSession().mask?.plugin}
  794. items={[
  795. {
  796. title: Locale.Plugin.Artifacts,
  797. value: Plugin.Artifacts,
  798. },
  799. ]}
  800. onClose={() => setShowPluginSelector(false)}
  801. onSelection={(s) => {
  802. const plugin = s[0];
  803. chatStore.updateCurrentSession((session) => {
  804. session.mask.plugin = s;
  805. });
  806. if (plugin) {
  807. showToast(plugin);
  808. }
  809. }}
  810. />
  811. )}
  812. </div>
  813. );
  814. }
  815. export function EditMessageModal(props: { onClose: () => void }) {
  816. const chatStore = useChatStore();
  817. const session = chatStore.currentSession();
  818. const [messages, setMessages] = useState(session.messages.slice());
  819. return (
  820. <div className="modal-mask">
  821. <Modal
  822. title={Locale.Chat.EditMessage.Title}
  823. onClose={props.onClose}
  824. actions={[
  825. <IconButton
  826. text={Locale.UI.Cancel}
  827. icon={<CancelIcon />}
  828. key="cancel"
  829. onClick={() => {
  830. props.onClose();
  831. }}
  832. />,
  833. <IconButton
  834. type="primary"
  835. text={Locale.UI.Confirm}
  836. icon={<ConfirmIcon />}
  837. key="ok"
  838. onClick={() => {
  839. chatStore.updateCurrentSession(
  840. (session) => (session.messages = messages),
  841. );
  842. props.onClose();
  843. }}
  844. />,
  845. ]}
  846. >
  847. <List>
  848. <ListItem
  849. title={Locale.Chat.EditMessage.Topic.Title}
  850. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  851. >
  852. <input
  853. type="text"
  854. value={session.topic}
  855. onInput={(e) =>
  856. chatStore.updateCurrentSession(
  857. (session) => (session.topic = e.currentTarget.value),
  858. )
  859. }
  860. ></input>
  861. </ListItem>
  862. </List>
  863. <ContextPrompts
  864. context={messages}
  865. updateContext={(updater) => {
  866. const newMessages = messages.slice();
  867. updater(newMessages);
  868. setMessages(newMessages);
  869. }}
  870. />
  871. </Modal>
  872. </div>
  873. );
  874. }
  875. export function DeleteImageButton(props: { deleteImage: () => void }) {
  876. return (
  877. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  878. <DeleteIcon />
  879. </div>
  880. );
  881. }
  882. function _Chat() {
  883. type RenderMessage = ChatMessage & { preview?: boolean };
  884. const chatStore = useChatStore();
  885. const session = chatStore.currentSession();
  886. const config = useAppConfig();
  887. config.sendPreviewBubble = false;
  888. const fontSize = config.fontSize;
  889. const fontFamily = config.fontFamily;
  890. const [showExport, setShowExport] = useState(false);
  891. const inputRef = useRef<HTMLTextAreaElement>(null);
  892. const [userInput, setUserInput] = useState("");
  893. const [isLoading, setIsLoading] = useState(false);
  894. const [sendStatus, setSendStatus] = useState(false);
  895. const { submitKey, shouldSubmit } = useSubmitHandler();
  896. const scrollRef = useRef<HTMLDivElement>(null);
  897. const isScrolledToBottom = scrollRef?.current
  898. ? Math.abs(
  899. scrollRef.current.scrollHeight -
  900. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  901. ) <= 1
  902. : false;
  903. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  904. scrollRef,
  905. isScrolledToBottom,
  906. );
  907. const [hitBottom, setHitBottom] = useState(true);
  908. const isMobileScreen = useMobileScreen();
  909. const navigate = useNavigate();
  910. const [attachImages, setAttachImages] = useState<string[]>([]);
  911. const [uploading, setUploading] = useState(false);
  912. // prompt hints
  913. const promptStore = usePromptStore();
  914. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  915. const onSearch = useDebouncedCallback(
  916. (text: string) => {
  917. const matchedPrompts = promptStore.search(text);
  918. setPromptHints(matchedPrompts);
  919. },
  920. 100,
  921. { leading: true, trailing: true },
  922. );
  923. type AppList = {
  924. label: string,
  925. value: string,
  926. desc: string,
  927. }[];
  928. const [appList, setAppList] = useState<AppList>([]);
  929. const [appValue, setAppValue] = useState<string>();
  930. const globalStore = useGlobalStore();
  931. type QuestionList = string[];
  932. const [questionList, setQuestionList] = useState<QuestionList>([]);
  933. const location = useLocation();
  934. const [loading, setLoading] = useState<boolean>(false);
  935. const fruits = [
  936. { id: 'LOCAL', name: 'deepseek' },
  937. { id: 'ONLINE', name: '智谱AI' },
  938. ];
  939. const [selectedFruit, setSelectedFruit] = React.useState(chatStore.chatMode);
  940. // 获取应用列表
  941. const fetchApplicationList = async (chatMode?: string) => {
  942. let mode = chatMode || selectedFruit;
  943. setLoading(true);
  944. try {
  945. let url = null;
  946. if (mode === 'LOCAL') {
  947. url = '/deepseek/api/application/list';
  948. } else {
  949. url = '/bigmodel/api/application/list';
  950. }
  951. const res = await api.get(url);
  952. const list = res.data.filter((item: any) => item.appId !== '1234567890123456789').map((item: any) => {
  953. return {
  954. label: item.name,
  955. value: item.appId,
  956. desc: item.desc,
  957. }
  958. })
  959. setAppList(list);
  960. const search = location.search;
  961. const params = new URLSearchParams(search);
  962. const appId = params.get('appId') || '';
  963. if (appId) {
  964. setAppValue(appId);
  965. } else {
  966. setAppValue(list[0]?.value);
  967. }
  968. } catch (error) {
  969. console.error(error);
  970. } finally {
  971. setLoading(false);
  972. }
  973. }
  974. // 获取预设问题列表
  975. const fetchDefaultQuestion = async (appId: string) => {
  976. try {
  977. let url = null;
  978. if (selectedFruit === 'LOCAL') {
  979. url = '/deepseek/api/presets';
  980. } else {
  981. url = '/bigmodel/api/presets';
  982. }
  983. const res = await api.get(url + `/${appId}`);
  984. setQuestionList(res.data);
  985. } catch (error) {
  986. console.error(error);
  987. } finally {
  988. setLoading(false);
  989. }
  990. }
  991. const init = async (chatMode?: string) => {
  992. await fetchApplicationList(chatMode);
  993. }
  994. useEffect(() => {
  995. const search = location.search;
  996. const params = new URLSearchParams(search);
  997. const chatMode = params.get('chatMode');
  998. if (!chatMode) {
  999. init();
  1000. }
  1001. }, [selectedFruit])
  1002. useEffect(() => {
  1003. const search = location.search;
  1004. const params = new URLSearchParams(search);
  1005. const chatMode = params.get('chatMode');
  1006. if (chatMode) {
  1007. setSelectedFruit(chatMode as "ONLINE" | "LOCAL");
  1008. const appId = params.get('appId');
  1009. if (appId) {
  1010. setAppValue(appId);
  1011. globalStore.setSelectedAppId(appId);
  1012. chatStore.updateCurrentSession((session) => {
  1013. session.appId = appId;
  1014. });
  1015. }
  1016. init(chatMode);
  1017. }
  1018. }, [])
  1019. useEffect(() => {
  1020. if (appValue) {
  1021. fetchDefaultQuestion(appValue);
  1022. }
  1023. }, [appValue, chatStore.chatMode])
  1024. const [inputRows, setInputRows] = useState(2);
  1025. const measure = useDebouncedCallback(
  1026. () => {
  1027. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  1028. const inputRows = Math.min(
  1029. 20,
  1030. Math.max(2 + Number(!isMobileScreen), rows),
  1031. );
  1032. setInputRows(inputRows);
  1033. },
  1034. 100,
  1035. {
  1036. leading: true,
  1037. trailing: true,
  1038. },
  1039. );
  1040. // eslint-disable-next-line react-hooks/exhaustive-deps
  1041. useEffect(measure, [userInput]);
  1042. // chat commands shortcuts
  1043. const chatCommands = useChatCommand({
  1044. new: () => chatStore.newSession(),
  1045. newm: () => navigate(Path.NewChat),
  1046. prev: () => chatStore.nextSession(-1),
  1047. next: () => chatStore.nextSession(1),
  1048. clear: () =>
  1049. chatStore.updateCurrentSession(
  1050. (session) => (session.clearContextIndex = session.messages.length),
  1051. ),
  1052. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  1053. });
  1054. // only search prompts when user input is short
  1055. const SEARCH_TEXT_LIMIT = 30;
  1056. const onInput = (text: string) => {
  1057. setUserInput(text);
  1058. const n = text.trim().length;
  1059. // clear search results
  1060. if (n === 0) {
  1061. setPromptHints([]);
  1062. } else if (text.match(ChatCommandPrefix)) {
  1063. setPromptHints(chatCommands.search(text));
  1064. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  1065. // check if need to trigger auto completion
  1066. if (text.startsWith("/")) {
  1067. let searchText = text.slice(1);
  1068. onSearch(searchText);
  1069. }
  1070. }
  1071. };
  1072. const doSubmit = (userInput: string) => {
  1073. if (userInput.trim() === "") return;
  1074. const matchCommand = chatCommands.match(userInput);
  1075. if (matchCommand.matched) {
  1076. setUserInput("");
  1077. setPromptHints([]);
  1078. matchCommand.invoke();
  1079. return;
  1080. }
  1081. setIsLoading(true);
  1082. chatStore.onUserInput([], userInput, attachImages).then(() => setIsLoading(false));
  1083. setAttachImages([]);
  1084. localStorage.setItem(LAST_INPUT_KEY, userInput);
  1085. setUserInput("");
  1086. setPromptHints([]);
  1087. if (!isMobileScreen) inputRef.current?.focus();
  1088. setAutoScroll(true);
  1089. setSendStatus(true);
  1090. };
  1091. const onPromptSelect = (prompt: RenderPrompt) => {
  1092. setTimeout(() => {
  1093. setPromptHints([]);
  1094. const matchedChatCommand = chatCommands.match(prompt.content);
  1095. if (matchedChatCommand.matched) {
  1096. // if user is selecting a chat command, just trigger it
  1097. matchedChatCommand.invoke();
  1098. setUserInput("");
  1099. } else {
  1100. // or fill the prompt
  1101. setUserInput(prompt.content);
  1102. }
  1103. inputRef.current?.focus();
  1104. }, 30);
  1105. };
  1106. // stop response
  1107. const onUserStop = (messageId: string) => {
  1108. ChatControllerPool.stop(session.id, messageId);
  1109. };
  1110. useEffect(() => {
  1111. chatStore.updateCurrentSession((session) => {
  1112. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  1113. session.messages.forEach((m) => {
  1114. // check if should stop all stale messages
  1115. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  1116. if (m.streaming) {
  1117. m.streaming = false;
  1118. }
  1119. if (m.content.length === 0) {
  1120. m.isError = true;
  1121. m.content = prettyObject({
  1122. error: true,
  1123. message: "empty response",
  1124. });
  1125. }
  1126. }
  1127. });
  1128. // auto sync mask config from global config
  1129. if (session.mask.syncGlobalConfig) {
  1130. console.log("[Mask] syncing from global, name = ", session.mask.name);
  1131. session.mask.modelConfig = { ...config.modelConfig };
  1132. }
  1133. });
  1134. // eslint-disable-next-line react-hooks/exhaustive-deps
  1135. }, []);
  1136. // check if should send message
  1137. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  1138. if (
  1139. e.key === "ArrowUp" &&
  1140. userInput.length <= 0 &&
  1141. !(e.metaKey || e.altKey || e.ctrlKey)
  1142. ) {
  1143. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  1144. e.preventDefault();
  1145. return;
  1146. }
  1147. if (shouldSubmit(e) && promptHints.length === 0) {
  1148. doSubmit(userInput);
  1149. e.preventDefault();
  1150. }
  1151. };
  1152. const onRightClick = (e: any, message: ChatMessage) => {
  1153. // copy to clipboard
  1154. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  1155. if (userInput.length === 0) {
  1156. setUserInput(getMessageTextContent(message));
  1157. }
  1158. e.preventDefault();
  1159. }
  1160. };
  1161. const deleteMessage = (msgId?: string) => {
  1162. chatStore.updateCurrentSession(
  1163. (session) =>
  1164. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  1165. );
  1166. };
  1167. const onDelete = (msgId: string) => {
  1168. deleteMessage(msgId);
  1169. };
  1170. const onResend = (message: ChatMessage) => {
  1171. // when it is resending a message
  1172. // 1. for a user's message, find the next bot response
  1173. // 2. for a bot's message, find the last user's input
  1174. // 3. delete original user input and bot's message
  1175. // 4. resend the user's input
  1176. const resendingIndex = session.messages.findIndex(
  1177. (m) => m.id === message.id,
  1178. );
  1179. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  1180. console.error("[Chat] failed to find resending message", message);
  1181. return;
  1182. }
  1183. let userMessage: ChatMessage | undefined;
  1184. let botMessage: ChatMessage | undefined;
  1185. if (message.role === "assistant") {
  1186. // if it is resending a bot's message, find the user input for it
  1187. botMessage = message;
  1188. for (let i = resendingIndex; i >= 0; i -= 1) {
  1189. if (session.messages[i].role === "user") {
  1190. userMessage = session.messages[i];
  1191. break;
  1192. }
  1193. }
  1194. } else if (message.role === "user") {
  1195. // if it is resending a user's input, find the bot's response
  1196. userMessage = message;
  1197. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  1198. if (session.messages[i].role === "assistant") {
  1199. botMessage = session.messages[i];
  1200. break;
  1201. }
  1202. }
  1203. }
  1204. if (userMessage === undefined) {
  1205. console.error("[Chat] failed to resend", message);
  1206. return;
  1207. }
  1208. // delete the original messages
  1209. deleteMessage(userMessage.id);
  1210. deleteMessage(botMessage?.id);
  1211. // resend the message
  1212. setIsLoading(true);
  1213. const textContent = getMessageTextContent(userMessage);
  1214. const images = getMessageImages(userMessage);
  1215. chatStore.onUserInput([], textContent, images).then(() => setIsLoading(false));
  1216. inputRef.current?.focus();
  1217. };
  1218. const onPinMessage = (message: ChatMessage) => {
  1219. chatStore.updateCurrentSession((session) =>
  1220. session.mask.context.push(message),
  1221. );
  1222. showToast(Locale.Chat.Actions.PinToastContent, {
  1223. text: Locale.Chat.Actions.PinToastAction,
  1224. onClick: () => {
  1225. setShowPromptModal(true);
  1226. },
  1227. });
  1228. };
  1229. const context: RenderMessage[] = useMemo(() => {
  1230. return session.mask.hideContext ? [] : session.mask.context.slice();
  1231. }, [session.mask.context, session.mask.hideContext]);
  1232. const accessStore = useAccessStore();
  1233. if (
  1234. context.length === 0 &&
  1235. session.messages.at(0)?.content !== BOT_HELLO.content
  1236. ) {
  1237. const copiedHello = Object.assign({}, BOT_HELLO);
  1238. if (!accessStore.isAuthorized()) {
  1239. copiedHello.content = Locale.Error.Unauthorized;
  1240. }
  1241. context.push(copiedHello);
  1242. }
  1243. // preview messages
  1244. const renderMessages = useMemo(() => {
  1245. return context.concat(session.messages as RenderMessage[]).concat(
  1246. isLoading
  1247. ? [
  1248. {
  1249. ...createMessage({
  1250. role: "assistant",
  1251. content: "……",
  1252. }),
  1253. preview: true,
  1254. },
  1255. ]
  1256. : [],
  1257. ).concat(
  1258. userInput.length > 0 && config.sendPreviewBubble
  1259. ? [
  1260. {
  1261. ...createMessage({
  1262. role: "user",
  1263. content: userInput,
  1264. }),
  1265. preview: true,
  1266. },
  1267. ]
  1268. : [],
  1269. );
  1270. }, [
  1271. config.sendPreviewBubble,
  1272. context,
  1273. isLoading,
  1274. session.messages,
  1275. userInput,
  1276. ]);
  1277. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  1278. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1279. );
  1280. function setMsgRenderIndex(newIndex: number) {
  1281. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1282. newIndex = Math.max(0, newIndex);
  1283. _setMsgRenderIndex(newIndex);
  1284. }
  1285. const messages = useMemo(() => {
  1286. const endRenderIndex = Math.min(
  1287. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1288. renderMessages.length,
  1289. );
  1290. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1291. }, [msgRenderIndex, renderMessages]);
  1292. const onChatBodyScroll = (e: HTMLElement) => {
  1293. const bottomHeight = e.scrollTop + e.clientHeight;
  1294. const edgeThreshold = e.clientHeight;
  1295. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1296. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1297. const isHitBottom =
  1298. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1299. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1300. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1301. if (isTouchTopEdge && !isTouchBottomEdge) {
  1302. setMsgRenderIndex(prevPageMsgIndex);
  1303. } else if (isTouchBottomEdge) {
  1304. setMsgRenderIndex(nextPageMsgIndex);
  1305. }
  1306. setHitBottom(isHitBottom);
  1307. setAutoScroll(isHitBottom);
  1308. };
  1309. function scrollToBottom() {
  1310. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1311. scrollDomToBottom();
  1312. }
  1313. // clear context index = context length + index in messages
  1314. const clearContextIndex =
  1315. (session.clearContextIndex ?? -1) >= 0
  1316. ? session.clearContextIndex! + context.length - msgRenderIndex
  1317. : -1;
  1318. const [showPromptModal, setShowPromptModal] = useState(false);
  1319. const clientConfig = useMemo(() => getClientConfig(), []);
  1320. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1321. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1322. useCommand({
  1323. fill: setUserInput,
  1324. submit: (text) => {
  1325. doSubmit(text);
  1326. },
  1327. code: (text) => {
  1328. if (accessStore.disableFastLink) return;
  1329. console.log("[Command] got code from url: ", text);
  1330. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1331. if (res) {
  1332. accessStore.update((access) => (access.accessCode = text));
  1333. }
  1334. });
  1335. },
  1336. settings: (text) => {
  1337. if (accessStore.disableFastLink) return;
  1338. try {
  1339. const payload = JSON.parse(text) as {
  1340. key?: string;
  1341. url?: string;
  1342. };
  1343. console.log("[Command] got settings from url: ", payload);
  1344. if (payload.key || payload.url) {
  1345. showConfirm(
  1346. Locale.URLCommand.Settings +
  1347. `\n${JSON.stringify(payload, null, 4)}`,
  1348. ).then((res) => {
  1349. if (!res) return;
  1350. if (payload.key) {
  1351. accessStore.update(
  1352. (access) => (access.openaiApiKey = payload.key!),
  1353. );
  1354. }
  1355. if (payload.url) {
  1356. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1357. }
  1358. accessStore.update((access) => (access.useCustomConfig = true));
  1359. });
  1360. }
  1361. } catch {
  1362. console.error("[Command] failed to get settings from url: ", text);
  1363. }
  1364. },
  1365. });
  1366. // edit / insert message modal
  1367. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1368. // remember unfinished input
  1369. useEffect(() => {
  1370. // try to load from local storage
  1371. const key = UNFINISHED_INPUT(session.id);
  1372. const mayBeUnfinishedInput = localStorage.getItem(key);
  1373. if (mayBeUnfinishedInput && userInput.length === 0) {
  1374. setUserInput(mayBeUnfinishedInput);
  1375. localStorage.removeItem(key);
  1376. }
  1377. const dom = inputRef.current;
  1378. return () => {
  1379. localStorage.setItem(key, dom?.value ?? "");
  1380. };
  1381. // eslint-disable-next-line react-hooks/exhaustive-deps
  1382. }, []);
  1383. const handlePaste = useCallback(
  1384. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1385. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1386. if (!isVisionModel(currentModel)) {
  1387. return;
  1388. }
  1389. const items = (event.clipboardData || window.clipboardData).items;
  1390. for (const item of items) {
  1391. if (item.kind === "file" && item.type.startsWith("image/")) {
  1392. event.preventDefault();
  1393. const file = item.getAsFile();
  1394. if (file) {
  1395. const images: string[] = [];
  1396. images.push(...attachImages);
  1397. images.push(
  1398. ...(await new Promise<string[]>((res, rej) => {
  1399. setUploading(true);
  1400. const imagesData: string[] = [];
  1401. uploadImageRemote(file).then((dataUrl) => {
  1402. imagesData.push(dataUrl);
  1403. setUploading(false);
  1404. res(imagesData);
  1405. }).catch((e) => {
  1406. setUploading(false);
  1407. rej(e);
  1408. });
  1409. })),
  1410. );
  1411. const imagesLength = images.length;
  1412. if (imagesLength > 3) {
  1413. images.splice(3, imagesLength - 3);
  1414. }
  1415. setAttachImages(images);
  1416. }
  1417. }
  1418. }
  1419. },
  1420. [attachImages, chatStore],
  1421. );
  1422. async function uploadImage() {
  1423. const images: string[] = [];
  1424. images.push(...attachImages);
  1425. images.push(
  1426. ...(await new Promise<string[]>((res, rej) => {
  1427. const fileInput = document.createElement("input");
  1428. fileInput.type = "file";
  1429. fileInput.accept =
  1430. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1431. fileInput.multiple = true;
  1432. fileInput.onchange = (event: any) => {
  1433. setUploading(true);
  1434. const files = event.target.files;
  1435. const imagesData: string[] = [];
  1436. for (let i = 0; i < files.length; i++) {
  1437. const file = event.target.files[i];
  1438. uploadImageRemote(file).then((dataUrl) => {
  1439. imagesData.push(dataUrl);
  1440. if (
  1441. imagesData.length === 3 ||
  1442. imagesData.length === files.length
  1443. ) {
  1444. setUploading(false);
  1445. res(imagesData);
  1446. }
  1447. }).catch((e) => {
  1448. setUploading(false);
  1449. rej(e);
  1450. });
  1451. }
  1452. };
  1453. fileInput.click();
  1454. })),
  1455. );
  1456. const imagesLength = images.length;
  1457. if (imagesLength > 3) {
  1458. images.splice(3, imagesLength - 3);
  1459. }
  1460. setAttachImages(images);
  1461. }
  1462. const getAppName = () => {
  1463. const search = location.search;
  1464. const params = new URLSearchParams(search);
  1465. const chatMode = params.get('chatMode');
  1466. let appId = '';
  1467. if (chatMode) {
  1468. appId = globalStore.selectedAppId;
  1469. } else {
  1470. appId = appValue as string;
  1471. }
  1472. const item = appList.find(item => item.value === appId);
  1473. if (!item) {
  1474. return '';
  1475. }
  1476. return item.label;
  1477. }
  1478. const getDesc = () => {
  1479. const search = location.search;
  1480. const params = new URLSearchParams(search);
  1481. const chatMode = params.get('chatMode');
  1482. let appId = '';
  1483. if (chatMode) {
  1484. appId = globalStore.selectedAppId;
  1485. } else {
  1486. appId = appValue as string;
  1487. }
  1488. const item = appList.find(item => item.value === appId);
  1489. if (!item) {
  1490. return '';
  1491. }
  1492. return item.desc;
  1493. }
  1494. const couldStop = ChatControllerPool.hasPending();
  1495. const stopAll = () => ChatControllerPool.stopAll();
  1496. const [isClickStop, setIsClickStop] = useState(false);
  1497. useEffect(() => {
  1498. if (!couldStop) {
  1499. setIsClickStop(false)
  1500. }
  1501. }, [couldStop])
  1502. interface FileIconProps {
  1503. fileName: string;
  1504. }
  1505. const FileIcon: React.FC<FileIconProps> = (props: FileIconProps) => {
  1506. const style = {
  1507. fontSize: '30px',
  1508. color: '#3875f6',
  1509. }
  1510. let icon = <FileOutlined style={style} />
  1511. if (props.fileName) {
  1512. const suffix = props.fileName.split('.').pop() || '';
  1513. switch (suffix) {
  1514. case 'pdf':
  1515. icon = <FilePdfOutlined style={style} />
  1516. break;
  1517. case 'txt':
  1518. icon = <FileTextOutlined style={style} />
  1519. break;
  1520. case 'doc':
  1521. case 'docx':
  1522. icon = <FileWordOutlined style={style} />
  1523. break;
  1524. default:
  1525. break;
  1526. }
  1527. }
  1528. return icon;
  1529. }
  1530. const [drawerOpen, setDrawerOpen] = useState(false);
  1531. const [drawerData, setDrawerData] = useState({
  1532. knowledge_id: '',
  1533. doc_name: '',
  1534. chunk_info: {
  1535. doc_id: '',
  1536. chunk_list: [],
  1537. }
  1538. });
  1539. const SliceDrawer: React.FC = () => {
  1540. const [pageLoading, setPageLoading] = useState(false);
  1541. const [list, setList] = useState([]);
  1542. const init = async () => {
  1543. setPageLoading(true);
  1544. try {
  1545. const res: any = await api.post('/deepseek/api/slicePage', {
  1546. knowledge_id: drawerData.knowledge_id,
  1547. chunk_info: drawerData.chunk_info,
  1548. pageNum: 1,
  1549. pageSize: 9999,
  1550. });
  1551. console.log(res.rows, 'res.rows');
  1552. setList(res.rows);
  1553. } catch (error) {
  1554. console.error(error);
  1555. } finally {
  1556. setPageLoading(false);
  1557. }
  1558. }
  1559. useEffect(() => {
  1560. init()
  1561. }, [])
  1562. return (
  1563. <Drawer
  1564. title={drawerData.doc_name}
  1565. loading={pageLoading}
  1566. open={drawerOpen}
  1567. onClose={() => {
  1568. setDrawerOpen(false);
  1569. }}
  1570. >
  1571. {list.map((item: any, index) => {
  1572. const score = parseFloat(item.rerankScore);
  1573. const formattedScore = isNaN(score) ? '0.00' : score.toFixed(2);
  1574. return <div
  1575. style={{
  1576. padding: 10,
  1577. background: '#fafafa',
  1578. borderRadius: 4,
  1579. marginBottom: 10
  1580. }}
  1581. key={item.sliceId}
  1582. >
  1583. <div
  1584. style={{
  1585. display: 'flex',
  1586. justifyContent: 'space-between',
  1587. alignItems: 'center',
  1588. }}
  1589. >
  1590. <div style={{ margin: '5px 0' }}>
  1591. 片段{index + 1}
  1592. </div>
  1593. <div>
  1594. <StarTwoTone style={{ marginRight: 10 }} />
  1595. rerank得分{formattedScore}
  1596. </div>
  1597. </div>
  1598. <div>
  1599. {item.sliceText}
  1600. </div>
  1601. </div>
  1602. })}
  1603. </Drawer>
  1604. )
  1605. }
  1606. return (
  1607. <div className={styles.chat} key={session.id}>
  1608. {
  1609. !location.search.includes('showMenu=false') &&
  1610. <></>
  1611. // <div className="window-header" data-tauri-drag-region>
  1612. // <div style={{ display: 'flex', alignItems: 'center' }}
  1613. // className={`window-header-title ${styles["chat-body-title"]}`}>
  1614. // <div>
  1615. // {
  1616. // isMobileScreen &&
  1617. // <IconButton
  1618. // style={{ padding: 0, marginRight: 20 }}
  1619. // icon={<LeftIcon />}
  1620. // text={Locale.NewChat.Return}
  1621. // onClick={() => navigate('/knowledgeChat')}
  1622. // />
  1623. // }
  1624. // </div>
  1625. // <div>
  1626. // <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
  1627. // <Select
  1628. // style={{ width: '100%', height: 38, marginRight: 5 }}
  1629. // value={selectedFruit}
  1630. // onChange={(value: "ONLINE" | "LOCAL") => {
  1631. // chatStore.clearSessions();
  1632. // chatStore.updateCurrentSession((values) => {
  1633. // values.appId = globalStore.selectedAppId;
  1634. // });
  1635. // navigate({ pathname: '/newChat' });
  1636. // setSelectedFruit(value);
  1637. // chatStore.setChatMode(value);
  1638. // }}
  1639. // >
  1640. // {fruits.map(fruit => (
  1641. // <Select.Option key={fruit.id} value={fruit.id}>
  1642. // {fruit.name}
  1643. // </Select.Option>
  1644. // ))}
  1645. // </Select>
  1646. // {
  1647. // appList.length > 0 ?
  1648. // <Select
  1649. // style={{ width: '100%', height: 38, marginRight: 5 }}
  1650. // placeholder='请选择'
  1651. // options={appList}
  1652. // value={appValue}
  1653. // onChange={(value) => {
  1654. // setAppValue(value);
  1655. // globalStore.setSelectedAppId(value);
  1656. // chatStore.clearSessions();
  1657. // chatStore.updateCurrentSession((values) => {
  1658. // values.appId = value;
  1659. // });
  1660. // useChatStore.setState({
  1661. // message: {
  1662. // content: '',
  1663. // role: 'assistant',
  1664. // }
  1665. // });
  1666. // setSendStatus(false);
  1667. // }}
  1668. // />
  1669. // :
  1670. // null
  1671. // }
  1672. // </div>
  1673. // </div>
  1674. // </div>
  1675. // <div className="window-actions">
  1676. // <div className="window-action-button">
  1677. // <Popover
  1678. // trigger="click"
  1679. // title="分享该应用"
  1680. // content={() => {
  1681. // const url = `${window.location.origin}/#/knowledgeChat?showMenu=false&chatMode=${selectedFruit}&appId=${appValue}`
  1682. // return <div>
  1683. // <div style={{ marginBottom: 10 }}>
  1684. // {url}
  1685. // </div>
  1686. // <Button onClick={() => {
  1687. // navigator.clipboard.writeText(url);
  1688. // message.success('分享链接已复制到剪贴板');
  1689. // }}>
  1690. // 复制
  1691. // </Button>
  1692. // </div>
  1693. // }
  1694. // }>
  1695. // <IconButton
  1696. // icon={<ExportIcon />}
  1697. // bordered
  1698. // title='分享该应用'
  1699. // />
  1700. // </Popover>
  1701. // </div>
  1702. // {/* {showMaxIcon && (
  1703. // <div className="window-action-button">
  1704. // <IconButton
  1705. // icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1706. // bordered
  1707. // title={Locale.Chat.Actions.FullScreen}
  1708. // aria={Locale.Chat.Actions.FullScreen}
  1709. // onClick={() => {
  1710. // config.update(
  1711. // (config) => (config.tightBorder = !config.tightBorder),
  1712. // );
  1713. // }}
  1714. // />
  1715. // </div>
  1716. // )} */}
  1717. // </div>
  1718. // {/* <PromptToast
  1719. // showToast={!hitBottom}
  1720. // showModal={showPromptModal}
  1721. // setShowModal={setShowPromptModal}
  1722. // /> */}
  1723. // </div>
  1724. }
  1725. <div className="window-header" data-tauri-drag-region>
  1726. <div></div>
  1727. <div className="window-actions">
  1728. <div className="window-action-button">
  1729. <Button type="primary" ghost onClick={() => {
  1730. window.open('https://llm.jkec.info:11432', "_self");
  1731. }}>
  1732. 登录
  1733. </Button>
  1734. </div>
  1735. </div>
  1736. </div>
  1737. <div
  1738. className={styles["chat-body"]}
  1739. ref={scrollRef}
  1740. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1741. onMouseDown={() => inputRef.current?.blur()}
  1742. onTouchStart={() => {
  1743. inputRef.current?.blur();
  1744. setAutoScroll(false);
  1745. }}
  1746. >
  1747. {
  1748. messages.length > 1 ?
  1749. <>
  1750. {messages.map((message, i) => {
  1751. const isUser = message.role === "user";
  1752. const isContext = i < context.length;
  1753. const showActions =
  1754. i > 0 &&
  1755. !(message.preview || message.content.length === 0) &&
  1756. !isContext;
  1757. const showTyping = message.preview || message.streaming;
  1758. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1759. return (
  1760. <Fragment key={message.id}>
  1761. <div
  1762. className={
  1763. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1764. }
  1765. >
  1766. <div className={styles["chat-message-container"]}>
  1767. <div className={styles["chat-message-header"]}>
  1768. <div className={styles["chat-message-avatar"]}>
  1769. {isUser ? (
  1770. // 在这里换头像
  1771. <div style={{ position: 'relative' }}>
  1772. <div
  1773. style={{
  1774. position: 'absolute',
  1775. zIndex: 2,
  1776. top: '50%',
  1777. left: '50%',
  1778. transform: ' translate(-110%, -100%)',
  1779. fontSize: 14,
  1780. }}>
  1781. </div>
  1782. </div>
  1783. ) : (
  1784. <>
  1785. {["system"].includes(message.role) ? (
  1786. <Avatar avatar="2699-fe0f" />
  1787. ) : (
  1788. <MaskAvatar
  1789. avatar={session.mask.avatar}
  1790. model={
  1791. message.model || session.mask.modelConfig.model
  1792. }
  1793. />
  1794. )}
  1795. </>
  1796. )}
  1797. </div>
  1798. {/* {showActions && (
  1799. <div className={styles["chat-message-actions"]}>
  1800. <div className={styles["chat-input-actions"]}>
  1801. {message.streaming ? (
  1802. <ChatAction
  1803. text={Locale.Chat.Actions.Stop}
  1804. icon={<StopIcon />}
  1805. onClick={() => onUserStop(message.id ?? i)}
  1806. />
  1807. ) : (
  1808. <>
  1809. <ChatAction
  1810. text={Locale.Chat.Actions.Retry}
  1811. icon={<ResetIcon />}
  1812. onClick={() => onResend(message)}
  1813. />
  1814. <ChatAction
  1815. text={Locale.Chat.Actions.Delete}
  1816. icon={<DeleteIcon />}
  1817. onClick={() => onDelete(message.id ?? i)}
  1818. />
  1819. <ChatAction
  1820. text={Locale.Chat.Actions.Pin}
  1821. icon={<PinIcon />}
  1822. onClick={() => onPinMessage(message)}
  1823. />
  1824. <ChatAction
  1825. text={Locale.Chat.Actions.Copy}
  1826. icon={<CopyIcon />}
  1827. onClick={() =>
  1828. copyToClipboard(
  1829. getMessageTextContent(message),
  1830. )
  1831. }
  1832. />
  1833. </>
  1834. )}
  1835. </div>
  1836. </div>
  1837. )} */}
  1838. </div>
  1839. {
  1840. showTyping ?
  1841. <div className={styles["chat-message-status"]}>
  1842. {isUser ? '' : '正在查询文档…'}
  1843. </div>
  1844. :
  1845. <div className={styles["chat-message-status"]}>
  1846. {
  1847. message.role === 'assistant' && messages.length - 1 === i &&
  1848. <div>
  1849. <CheckCircleOutlined /> 文档搜索成功
  1850. </div>
  1851. }
  1852. </div>
  1853. }
  1854. {
  1855. message.sliceInfo &&
  1856. <div style={{ marginTop: 10 }}>
  1857. <Collapse
  1858. bordered={false}
  1859. expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
  1860. items={[
  1861. {
  1862. key: '1',
  1863. label: `查询到“${message.sliceInfo.doc.length}条”相关切片`,
  1864. children: <div>
  1865. {message.sliceInfo.doc.map((item, index) => {
  1866. return <div
  1867. style={{
  1868. padding: 10,
  1869. background: '#FFFFFF',
  1870. borderRadius: 4,
  1871. display: 'flex',
  1872. justifyContent: 'space-between',
  1873. alignItems: 'center',
  1874. marginTop: index ? 10 : 0,
  1875. cursor: 'pointer',
  1876. }}
  1877. key={item.doc_id}
  1878. onClick={() => {
  1879. setDrawerData({
  1880. knowledge_id: message.sliceInfo!.knowledge_id,
  1881. doc_name: item.doc_name,
  1882. chunk_info: {
  1883. doc_id: item.doc_id,
  1884. chunk_list: item.chunk_info_list,
  1885. }
  1886. });
  1887. setDrawerOpen(true);
  1888. }}
  1889. >
  1890. <div style={{ display: 'flex', alignItems: 'center' }}>
  1891. <FileIcon fileName={item.doc_name} />
  1892. <div style={{ marginLeft: 10 }}>
  1893. {item.doc_name}
  1894. </div>
  1895. </div>
  1896. <div style={{
  1897. padding: 10,
  1898. background: '#FAFAFA',
  1899. borderRadius: 4,
  1900. marginLeft: 20,
  1901. }}>
  1902. {item.chunk_nums}
  1903. </div>
  1904. </div>
  1905. })}
  1906. </div>,
  1907. }
  1908. ]}
  1909. />
  1910. {
  1911. drawerOpen &&
  1912. <SliceDrawer />
  1913. }
  1914. </div>
  1915. }
  1916. <div className={styles["chat-message-item"]}>
  1917. <Markdown
  1918. key={message.streaming ? "loading" : "done"}
  1919. content={getMessageTextContent(message)}
  1920. loading={
  1921. (message.preview || message.streaming) &&
  1922. message.content.length === 0 &&
  1923. !isUser
  1924. }
  1925. // onContextMenu={(e) => onRightClick(e, message)}
  1926. onDoubleClickCapture={() => {
  1927. if (!isMobileScreen) return;
  1928. setUserInput(getMessageTextContent(message));
  1929. }}
  1930. fontSize={fontSize}
  1931. fontFamily={fontFamily}
  1932. parentRef={scrollRef}
  1933. defaultShow={i >= messages.length - 6}
  1934. />
  1935. {getMessageImages(message).length == 1 && (
  1936. <img
  1937. className={styles["chat-message-item-image"]}
  1938. src={getMessageImages(message)[0]}
  1939. alt=""
  1940. />
  1941. )}
  1942. {getMessageImages(message).length > 1 && (
  1943. <div
  1944. className={styles["chat-message-item-images"]}
  1945. style={
  1946. {
  1947. "--image-count": getMessageImages(message).length,
  1948. } as React.CSSProperties
  1949. }
  1950. >
  1951. {getMessageImages(message).map((image, index) => {
  1952. return (
  1953. <img
  1954. className={
  1955. styles["chat-message-item-image-multi"]
  1956. }
  1957. key={index}
  1958. src={image}
  1959. alt=""
  1960. />
  1961. );
  1962. })}
  1963. </div>
  1964. )}
  1965. </div>
  1966. {/* <div className={styles["chat-message-action-date"]}>
  1967. {isContext
  1968. ? Locale.Chat.IsContext
  1969. : message.date.toLocaleString()}
  1970. </div> */}
  1971. </div>
  1972. </div>
  1973. {shouldShowClearContextDivider && <ClearContextDivider />}
  1974. </Fragment>
  1975. );
  1976. })}
  1977. </>
  1978. :
  1979. <>
  1980. <div style={{ padding: '0 20px' }}>
  1981. <div style={{ display: 'flex', justifyContent: 'center' }}>
  1982. <img style={{ width: 80, height: 80 }} src={avatarSrc.src} />
  1983. </div>
  1984. <h1 style={{ textAlign: 'center' }}>
  1985. {getAppName()}
  1986. </h1>
  1987. <p style={{ textAlign: 'center' }}>
  1988. {getDesc()}
  1989. </p>
  1990. <p>我猜您可能想问:</p>
  1991. {
  1992. questionList.map((item, index) => {
  1993. return (
  1994. <div
  1995. style={{
  1996. padding: '10px',
  1997. marginBottom: '10px',
  1998. border: '1px solid #e6e8f1',
  1999. borderRadius: '10px',
  2000. fontSize: '16px',
  2001. display: 'flex',
  2002. justifyContent: 'space-between',
  2003. alignItems: 'center',
  2004. cursor: 'pointer'
  2005. }}
  2006. onClick={() => {
  2007. setUserInput(item)
  2008. doSubmit(item)
  2009. }}
  2010. key={index}
  2011. >
  2012. <div>
  2013. {item}
  2014. </div>
  2015. <RightOutlined />
  2016. </div>
  2017. )
  2018. })
  2019. }
  2020. </div>
  2021. </>
  2022. }
  2023. </div>
  2024. <div className={styles["chat-input-panel"]}>
  2025. {/* <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} /> */}
  2026. <ChatActions
  2027. isClickStop={isClickStop}
  2028. sendStatus={sendStatus}
  2029. setSendStatus={setSendStatus}
  2030. setUserInput={setUserInput}
  2031. doSubmit={doSubmit}
  2032. uploadImage={uploadImage}
  2033. setAttachImages={setAttachImages}
  2034. setUploading={setUploading}
  2035. showPromptModal={() => setShowPromptModal(true)}
  2036. scrollToBottom={scrollToBottom}
  2037. hitBottom={hitBottom}
  2038. uploading={uploading}
  2039. showPromptHints={() => {
  2040. // Click again to close
  2041. if (promptHints.length > 0) {
  2042. setPromptHints([]);
  2043. return;
  2044. }
  2045. inputRef.current?.focus();
  2046. setUserInput("/");
  2047. onSearch("");
  2048. }}
  2049. />
  2050. <label
  2051. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  2052. ? styles["chat-input-panel-inner-attach"]
  2053. : ""
  2054. }`}
  2055. htmlFor="chat-input"
  2056. >
  2057. <textarea
  2058. id="chat-input"
  2059. ref={inputRef}
  2060. className={styles["chat-input"]}
  2061. placeholder={Locale.Chat.Input(submitKey)}
  2062. onInput={(e) => onInput(e.currentTarget.value)}
  2063. value={userInput}
  2064. onKeyDown={onInputKeyDown}
  2065. onFocus={scrollToBottom}
  2066. onClick={scrollToBottom}
  2067. onPaste={handlePaste}
  2068. rows={inputRows}
  2069. autoFocus={autoFocus}
  2070. style={{
  2071. fontSize: config.fontSize,
  2072. fontFamily: config.fontFamily,
  2073. }}
  2074. />
  2075. {attachImages.length != 0 && (
  2076. <div className={styles["attach-images"]}>
  2077. {attachImages.map((image, index) => {
  2078. return (
  2079. <div
  2080. key={index}
  2081. className={styles["attach-image"]}
  2082. style={{ backgroundImage: `url("${image}")` }}
  2083. >
  2084. <div className={styles["attach-image-mask"]}>
  2085. <DeleteImageButton
  2086. deleteImage={() => {
  2087. setAttachImages(
  2088. attachImages.filter((_, i) => i !== index),
  2089. );
  2090. }}
  2091. />
  2092. </div>
  2093. </div>
  2094. );
  2095. })}
  2096. </div>
  2097. )}
  2098. <IconButton
  2099. icon={couldStop ? <div style={{ width: 13, height: 13, background: '#FFFFFF', borderRadius: 2 }}></div> : <SendWhiteIcon />}
  2100. text={couldStop ? '停止' : '发送'}
  2101. className={styles["chat-input-send"]}
  2102. type="primary"
  2103. onClick={() => {
  2104. if (couldStop) {
  2105. stopAll();
  2106. setIsClickStop(true);
  2107. } else {
  2108. doSubmit(userInput);
  2109. }
  2110. }}
  2111. />
  2112. </label>
  2113. </div>
  2114. <div style={{ paddingBottom: 20, textAlign: 'center', color: '#888888', fontSize: 12 }}>
  2115. 内容由AI生成,仅供参考
  2116. </div>
  2117. {showExport && (
  2118. <ExportMessageModal onClose={() => setShowExport(false)} />
  2119. )}
  2120. {isEditingMessage && (
  2121. <EditMessageModal
  2122. onClose={() => {
  2123. setIsEditingMessage(false);
  2124. }}
  2125. />
  2126. )}
  2127. </div>
  2128. );
  2129. }
  2130. export function Chat() {
  2131. const chatStore = useChatStore();
  2132. const location = useLocation();
  2133. const sessionIndex = chatStore.currentSessionIndex;
  2134. useEffect(() => {
  2135. chatStore.setModel('BigModel');
  2136. const search = location.search;
  2137. const params = new URLSearchParams(search);
  2138. const chatMode = params.get('chatMode');
  2139. if (chatMode) {
  2140. chatStore.setChatMode(chatMode as "ONLINE" | "LOCAL");
  2141. }
  2142. }, []);
  2143. return <_Chat key={sessionIndex}></_Chat>;
  2144. }