chat.tsx 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282
  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 }}>
  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', marginTop: 10, flexWrap: 'wrap' }}>
  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 () => {
  942. setLoading(true);
  943. try {
  944. let url = null;
  945. if (selectedFruit === 'LOCAL') {
  946. url = '/deepseek/api/application/list';
  947. } else {
  948. url = '/bigmodel/api/application/list';
  949. }
  950. const res = await api.get(url);
  951. const list = res.data.filter((item: any) => item.appId !== '1234567890123456789').map((item: any) => {
  952. return {
  953. label: item.name,
  954. value: item.appId,
  955. desc: item.desc,
  956. }
  957. })
  958. setAppList(list);
  959. const search = location.search;
  960. const params = new URLSearchParams(search);
  961. const appId = params.get('appId') || '';
  962. if (appId) {
  963. setAppValue(appId);
  964. } else {
  965. setAppValue(list[0]?.value);
  966. }
  967. } catch (error) {
  968. console.error(error);
  969. } finally {
  970. setLoading(false);
  971. }
  972. }
  973. // 获取预设问题列表
  974. const fetchDefaultQuestion = async (appId: string) => {
  975. try {
  976. let url = null;
  977. if (selectedFruit === 'LOCAL') {
  978. url = '/deepseek/api/presets';
  979. } else {
  980. url = '/bigmodel/api/presets';
  981. }
  982. const res = await api.get(url + `/${appId}`);
  983. setQuestionList(res.data);
  984. } catch (error) {
  985. console.error(error);
  986. } finally {
  987. setLoading(false);
  988. }
  989. }
  990. const init = async () => {
  991. await fetchApplicationList();
  992. }
  993. useEffect(() => {
  994. const search = location.search;
  995. const params = new URLSearchParams(search);
  996. const chatMode = params.get('chatMode');
  997. if (!chatMode) {
  998. init();
  999. }
  1000. }, [selectedFruit])
  1001. useEffect(() => {
  1002. const search = location.search;
  1003. const params = new URLSearchParams(search);
  1004. const chatMode = params.get('chatMode');
  1005. if (chatMode) {
  1006. setSelectedFruit(chatMode as "ONLINE" | "LOCAL");
  1007. const appId = params.get('appId');
  1008. if (appId) {
  1009. setAppValue(appId);
  1010. globalStore.setSelectedAppId(appId);
  1011. chatStore.updateCurrentSession((session) => {
  1012. session.appId = appId;
  1013. });
  1014. }
  1015. init();
  1016. }
  1017. }, [])
  1018. useEffect(() => {
  1019. if (appValue) {
  1020. fetchDefaultQuestion(appValue);
  1021. }
  1022. }, [appValue, chatStore.chatMode])
  1023. const [inputRows, setInputRows] = useState(2);
  1024. const measure = useDebouncedCallback(
  1025. () => {
  1026. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  1027. const inputRows = Math.min(
  1028. 20,
  1029. Math.max(2 + Number(!isMobileScreen), rows),
  1030. );
  1031. setInputRows(inputRows);
  1032. },
  1033. 100,
  1034. {
  1035. leading: true,
  1036. trailing: true,
  1037. },
  1038. );
  1039. // eslint-disable-next-line react-hooks/exhaustive-deps
  1040. useEffect(measure, [userInput]);
  1041. // chat commands shortcuts
  1042. const chatCommands = useChatCommand({
  1043. new: () => chatStore.newSession(),
  1044. newm: () => navigate(Path.NewChat),
  1045. prev: () => chatStore.nextSession(-1),
  1046. next: () => chatStore.nextSession(1),
  1047. clear: () =>
  1048. chatStore.updateCurrentSession(
  1049. (session) => (session.clearContextIndex = session.messages.length),
  1050. ),
  1051. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  1052. });
  1053. // only search prompts when user input is short
  1054. const SEARCH_TEXT_LIMIT = 30;
  1055. const onInput = (text: string) => {
  1056. setUserInput(text);
  1057. const n = text.trim().length;
  1058. // clear search results
  1059. if (n === 0) {
  1060. setPromptHints([]);
  1061. } else if (text.match(ChatCommandPrefix)) {
  1062. setPromptHints(chatCommands.search(text));
  1063. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  1064. // check if need to trigger auto completion
  1065. if (text.startsWith("/")) {
  1066. let searchText = text.slice(1);
  1067. onSearch(searchText);
  1068. }
  1069. }
  1070. };
  1071. const doSubmit = (userInput: string) => {
  1072. if (userInput.trim() === "") return;
  1073. const matchCommand = chatCommands.match(userInput);
  1074. if (matchCommand.matched) {
  1075. setUserInput("");
  1076. setPromptHints([]);
  1077. matchCommand.invoke();
  1078. return;
  1079. }
  1080. setIsLoading(true);
  1081. chatStore.onUserInput([], userInput, attachImages).then(() => setIsLoading(false));
  1082. setAttachImages([]);
  1083. localStorage.setItem(LAST_INPUT_KEY, userInput);
  1084. setUserInput("");
  1085. setPromptHints([]);
  1086. if (!isMobileScreen) inputRef.current?.focus();
  1087. setAutoScroll(true);
  1088. setSendStatus(true);
  1089. };
  1090. const onPromptSelect = (prompt: RenderPrompt) => {
  1091. setTimeout(() => {
  1092. setPromptHints([]);
  1093. const matchedChatCommand = chatCommands.match(prompt.content);
  1094. if (matchedChatCommand.matched) {
  1095. // if user is selecting a chat command, just trigger it
  1096. matchedChatCommand.invoke();
  1097. setUserInput("");
  1098. } else {
  1099. // or fill the prompt
  1100. setUserInput(prompt.content);
  1101. }
  1102. inputRef.current?.focus();
  1103. }, 30);
  1104. };
  1105. // stop response
  1106. const onUserStop = (messageId: string) => {
  1107. ChatControllerPool.stop(session.id, messageId);
  1108. };
  1109. useEffect(() => {
  1110. chatStore.updateCurrentSession((session) => {
  1111. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  1112. session.messages.forEach((m) => {
  1113. // check if should stop all stale messages
  1114. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  1115. if (m.streaming) {
  1116. m.streaming = false;
  1117. }
  1118. if (m.content.length === 0) {
  1119. m.isError = true;
  1120. m.content = prettyObject({
  1121. error: true,
  1122. message: "empty response",
  1123. });
  1124. }
  1125. }
  1126. });
  1127. // auto sync mask config from global config
  1128. if (session.mask.syncGlobalConfig) {
  1129. console.log("[Mask] syncing from global, name = ", session.mask.name);
  1130. session.mask.modelConfig = { ...config.modelConfig };
  1131. }
  1132. });
  1133. // eslint-disable-next-line react-hooks/exhaustive-deps
  1134. }, []);
  1135. // check if should send message
  1136. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  1137. if (
  1138. e.key === "ArrowUp" &&
  1139. userInput.length <= 0 &&
  1140. !(e.metaKey || e.altKey || e.ctrlKey)
  1141. ) {
  1142. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  1143. e.preventDefault();
  1144. return;
  1145. }
  1146. if (shouldSubmit(e) && promptHints.length === 0) {
  1147. doSubmit(userInput);
  1148. e.preventDefault();
  1149. }
  1150. };
  1151. const onRightClick = (e: any, message: ChatMessage) => {
  1152. // copy to clipboard
  1153. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  1154. if (userInput.length === 0) {
  1155. setUserInput(getMessageTextContent(message));
  1156. }
  1157. e.preventDefault();
  1158. }
  1159. };
  1160. const deleteMessage = (msgId?: string) => {
  1161. chatStore.updateCurrentSession(
  1162. (session) =>
  1163. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  1164. );
  1165. };
  1166. const onDelete = (msgId: string) => {
  1167. deleteMessage(msgId);
  1168. };
  1169. const onResend = (message: ChatMessage) => {
  1170. // when it is resending a message
  1171. // 1. for a user's message, find the next bot response
  1172. // 2. for a bot's message, find the last user's input
  1173. // 3. delete original user input and bot's message
  1174. // 4. resend the user's input
  1175. const resendingIndex = session.messages.findIndex(
  1176. (m) => m.id === message.id,
  1177. );
  1178. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  1179. console.error("[Chat] failed to find resending message", message);
  1180. return;
  1181. }
  1182. let userMessage: ChatMessage | undefined;
  1183. let botMessage: ChatMessage | undefined;
  1184. if (message.role === "assistant") {
  1185. // if it is resending a bot's message, find the user input for it
  1186. botMessage = message;
  1187. for (let i = resendingIndex; i >= 0; i -= 1) {
  1188. if (session.messages[i].role === "user") {
  1189. userMessage = session.messages[i];
  1190. break;
  1191. }
  1192. }
  1193. } else if (message.role === "user") {
  1194. // if it is resending a user's input, find the bot's response
  1195. userMessage = message;
  1196. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  1197. if (session.messages[i].role === "assistant") {
  1198. botMessage = session.messages[i];
  1199. break;
  1200. }
  1201. }
  1202. }
  1203. if (userMessage === undefined) {
  1204. console.error("[Chat] failed to resend", message);
  1205. return;
  1206. }
  1207. // delete the original messages
  1208. deleteMessage(userMessage.id);
  1209. deleteMessage(botMessage?.id);
  1210. // resend the message
  1211. setIsLoading(true);
  1212. const textContent = getMessageTextContent(userMessage);
  1213. const images = getMessageImages(userMessage);
  1214. chatStore.onUserInput([], textContent, images).then(() => setIsLoading(false));
  1215. inputRef.current?.focus();
  1216. };
  1217. const onPinMessage = (message: ChatMessage) => {
  1218. chatStore.updateCurrentSession((session) =>
  1219. session.mask.context.push(message),
  1220. );
  1221. showToast(Locale.Chat.Actions.PinToastContent, {
  1222. text: Locale.Chat.Actions.PinToastAction,
  1223. onClick: () => {
  1224. setShowPromptModal(true);
  1225. },
  1226. });
  1227. };
  1228. const context: RenderMessage[] = useMemo(() => {
  1229. return session.mask.hideContext ? [] : session.mask.context.slice();
  1230. }, [session.mask.context, session.mask.hideContext]);
  1231. const accessStore = useAccessStore();
  1232. if (
  1233. context.length === 0 &&
  1234. session.messages.at(0)?.content !== BOT_HELLO.content
  1235. ) {
  1236. const copiedHello = Object.assign({}, BOT_HELLO);
  1237. if (!accessStore.isAuthorized()) {
  1238. copiedHello.content = Locale.Error.Unauthorized;
  1239. }
  1240. context.push(copiedHello);
  1241. }
  1242. // preview messages
  1243. const renderMessages = useMemo(() => {
  1244. return context.concat(session.messages as RenderMessage[]).concat(
  1245. isLoading
  1246. ? [
  1247. {
  1248. ...createMessage({
  1249. role: "assistant",
  1250. content: "……",
  1251. }),
  1252. preview: true,
  1253. },
  1254. ]
  1255. : [],
  1256. ).concat(
  1257. userInput.length > 0 && config.sendPreviewBubble
  1258. ? [
  1259. {
  1260. ...createMessage({
  1261. role: "user",
  1262. content: userInput,
  1263. }),
  1264. preview: true,
  1265. },
  1266. ]
  1267. : [],
  1268. );
  1269. }, [
  1270. config.sendPreviewBubble,
  1271. context,
  1272. isLoading,
  1273. session.messages,
  1274. userInput,
  1275. ]);
  1276. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  1277. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1278. );
  1279. function setMsgRenderIndex(newIndex: number) {
  1280. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1281. newIndex = Math.max(0, newIndex);
  1282. _setMsgRenderIndex(newIndex);
  1283. }
  1284. const messages = useMemo(() => {
  1285. const endRenderIndex = Math.min(
  1286. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1287. renderMessages.length,
  1288. );
  1289. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1290. }, [msgRenderIndex, renderMessages]);
  1291. const onChatBodyScroll = (e: HTMLElement) => {
  1292. const bottomHeight = e.scrollTop + e.clientHeight;
  1293. const edgeThreshold = e.clientHeight;
  1294. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1295. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1296. const isHitBottom =
  1297. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1298. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1299. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1300. if (isTouchTopEdge && !isTouchBottomEdge) {
  1301. setMsgRenderIndex(prevPageMsgIndex);
  1302. } else if (isTouchBottomEdge) {
  1303. setMsgRenderIndex(nextPageMsgIndex);
  1304. }
  1305. setHitBottom(isHitBottom);
  1306. setAutoScroll(isHitBottom);
  1307. };
  1308. function scrollToBottom() {
  1309. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1310. scrollDomToBottom();
  1311. }
  1312. // clear context index = context length + index in messages
  1313. const clearContextIndex =
  1314. (session.clearContextIndex ?? -1) >= 0
  1315. ? session.clearContextIndex! + context.length - msgRenderIndex
  1316. : -1;
  1317. const [showPromptModal, setShowPromptModal] = useState(false);
  1318. const clientConfig = useMemo(() => getClientConfig(), []);
  1319. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1320. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1321. useCommand({
  1322. fill: setUserInput,
  1323. submit: (text) => {
  1324. doSubmit(text);
  1325. },
  1326. code: (text) => {
  1327. if (accessStore.disableFastLink) return;
  1328. console.log("[Command] got code from url: ", text);
  1329. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1330. if (res) {
  1331. accessStore.update((access) => (access.accessCode = text));
  1332. }
  1333. });
  1334. },
  1335. settings: (text) => {
  1336. if (accessStore.disableFastLink) return;
  1337. try {
  1338. const payload = JSON.parse(text) as {
  1339. key?: string;
  1340. url?: string;
  1341. };
  1342. console.log("[Command] got settings from url: ", payload);
  1343. if (payload.key || payload.url) {
  1344. showConfirm(
  1345. Locale.URLCommand.Settings +
  1346. `\n${JSON.stringify(payload, null, 4)}`,
  1347. ).then((res) => {
  1348. if (!res) return;
  1349. if (payload.key) {
  1350. accessStore.update(
  1351. (access) => (access.openaiApiKey = payload.key!),
  1352. );
  1353. }
  1354. if (payload.url) {
  1355. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1356. }
  1357. accessStore.update((access) => (access.useCustomConfig = true));
  1358. });
  1359. }
  1360. } catch {
  1361. console.error("[Command] failed to get settings from url: ", text);
  1362. }
  1363. },
  1364. });
  1365. // edit / insert message modal
  1366. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1367. // remember unfinished input
  1368. useEffect(() => {
  1369. // try to load from local storage
  1370. const key = UNFINISHED_INPUT(session.id);
  1371. const mayBeUnfinishedInput = localStorage.getItem(key);
  1372. if (mayBeUnfinishedInput && userInput.length === 0) {
  1373. setUserInput(mayBeUnfinishedInput);
  1374. localStorage.removeItem(key);
  1375. }
  1376. const dom = inputRef.current;
  1377. return () => {
  1378. localStorage.setItem(key, dom?.value ?? "");
  1379. };
  1380. // eslint-disable-next-line react-hooks/exhaustive-deps
  1381. }, []);
  1382. const handlePaste = useCallback(
  1383. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1384. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1385. if (!isVisionModel(currentModel)) {
  1386. return;
  1387. }
  1388. const items = (event.clipboardData || window.clipboardData).items;
  1389. for (const item of items) {
  1390. if (item.kind === "file" && item.type.startsWith("image/")) {
  1391. event.preventDefault();
  1392. const file = item.getAsFile();
  1393. if (file) {
  1394. const images: string[] = [];
  1395. images.push(...attachImages);
  1396. images.push(
  1397. ...(await new Promise<string[]>((res, rej) => {
  1398. setUploading(true);
  1399. const imagesData: string[] = [];
  1400. uploadImageRemote(file).then((dataUrl) => {
  1401. imagesData.push(dataUrl);
  1402. setUploading(false);
  1403. res(imagesData);
  1404. }).catch((e) => {
  1405. setUploading(false);
  1406. rej(e);
  1407. });
  1408. })),
  1409. );
  1410. const imagesLength = images.length;
  1411. if (imagesLength > 3) {
  1412. images.splice(3, imagesLength - 3);
  1413. }
  1414. setAttachImages(images);
  1415. }
  1416. }
  1417. }
  1418. },
  1419. [attachImages, chatStore],
  1420. );
  1421. async function uploadImage() {
  1422. const images: string[] = [];
  1423. images.push(...attachImages);
  1424. images.push(
  1425. ...(await new Promise<string[]>((res, rej) => {
  1426. const fileInput = document.createElement("input");
  1427. fileInput.type = "file";
  1428. fileInput.accept =
  1429. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1430. fileInput.multiple = true;
  1431. fileInput.onchange = (event: any) => {
  1432. setUploading(true);
  1433. const files = event.target.files;
  1434. const imagesData: string[] = [];
  1435. for (let i = 0; i < files.length; i++) {
  1436. const file = event.target.files[i];
  1437. uploadImageRemote(file).then((dataUrl) => {
  1438. imagesData.push(dataUrl);
  1439. if (
  1440. imagesData.length === 3 ||
  1441. imagesData.length === files.length
  1442. ) {
  1443. setUploading(false);
  1444. res(imagesData);
  1445. }
  1446. }).catch((e) => {
  1447. setUploading(false);
  1448. rej(e);
  1449. });
  1450. }
  1451. };
  1452. fileInput.click();
  1453. })),
  1454. );
  1455. const imagesLength = images.length;
  1456. if (imagesLength > 3) {
  1457. images.splice(3, imagesLength - 3);
  1458. }
  1459. setAttachImages(images);
  1460. }
  1461. const getAppName = () => {
  1462. const appId = globalStore.selectedAppId;
  1463. const item = appList.find(item => item.value === appId);
  1464. if (!item) {
  1465. return '';
  1466. }
  1467. return item.label;
  1468. }
  1469. const getDesc = () => {
  1470. const appId = globalStore.selectedAppId;
  1471. const item = appList.find(item => item.value === appId);
  1472. if (!item) {
  1473. return '';
  1474. }
  1475. return item.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. {getDesc()}
  1959. </p>
  1960. <p>我猜您可能想问:</p>
  1961. {
  1962. questionList.map((item, index) => {
  1963. return (
  1964. <div
  1965. style={{
  1966. padding: '10px',
  1967. marginBottom: '10px',
  1968. border: '1px solid #e6e8f1',
  1969. borderRadius: '10px',
  1970. fontSize: '16px',
  1971. display: 'flex',
  1972. justifyContent: 'space-between',
  1973. alignItems: 'center',
  1974. cursor: 'pointer'
  1975. }}
  1976. onClick={() => {
  1977. setUserInput(item)
  1978. doSubmit(item)
  1979. }}
  1980. key={index}
  1981. >
  1982. <div>
  1983. {item}
  1984. </div>
  1985. <RightOutlined />
  1986. </div>
  1987. )
  1988. })
  1989. }
  1990. </div>
  1991. </>
  1992. }
  1993. </div>
  1994. <div className={styles["chat-input-panel"]}>
  1995. {/* <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} /> */}
  1996. <ChatActions
  1997. isClickStop={isClickStop}
  1998. sendStatus={sendStatus}
  1999. setSendStatus={setSendStatus}
  2000. setUserInput={setUserInput}
  2001. doSubmit={doSubmit}
  2002. uploadImage={uploadImage}
  2003. setAttachImages={setAttachImages}
  2004. setUploading={setUploading}
  2005. showPromptModal={() => setShowPromptModal(true)}
  2006. scrollToBottom={scrollToBottom}
  2007. hitBottom={hitBottom}
  2008. uploading={uploading}
  2009. showPromptHints={() => {
  2010. // Click again to close
  2011. if (promptHints.length > 0) {
  2012. setPromptHints([]);
  2013. return;
  2014. }
  2015. inputRef.current?.focus();
  2016. setUserInput("/");
  2017. onSearch("");
  2018. }}
  2019. />
  2020. <label
  2021. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  2022. ? styles["chat-input-panel-inner-attach"]
  2023. : ""
  2024. }`}
  2025. htmlFor="chat-input"
  2026. >
  2027. <textarea
  2028. id="chat-input"
  2029. ref={inputRef}
  2030. className={styles["chat-input"]}
  2031. placeholder={Locale.Chat.Input(submitKey)}
  2032. onInput={(e) => onInput(e.currentTarget.value)}
  2033. value={userInput}
  2034. onKeyDown={onInputKeyDown}
  2035. onFocus={scrollToBottom}
  2036. onClick={scrollToBottom}
  2037. onPaste={handlePaste}
  2038. rows={inputRows}
  2039. autoFocus={autoFocus}
  2040. style={{
  2041. fontSize: config.fontSize,
  2042. fontFamily: config.fontFamily,
  2043. }}
  2044. />
  2045. {attachImages.length != 0 && (
  2046. <div className={styles["attach-images"]}>
  2047. {attachImages.map((image, index) => {
  2048. return (
  2049. <div
  2050. key={index}
  2051. className={styles["attach-image"]}
  2052. style={{ backgroundImage: `url("${image}")` }}
  2053. >
  2054. <div className={styles["attach-image-mask"]}>
  2055. <DeleteImageButton
  2056. deleteImage={() => {
  2057. setAttachImages(
  2058. attachImages.filter((_, i) => i !== index),
  2059. );
  2060. }}
  2061. />
  2062. </div>
  2063. </div>
  2064. );
  2065. })}
  2066. </div>
  2067. )}
  2068. <IconButton
  2069. icon={couldStop ? <div style={{ width: 13, height: 13, background: '#FFFFFF', borderRadius: 2 }}></div> : <SendWhiteIcon />}
  2070. text={couldStop ? '停止' : '发送'}
  2071. className={styles["chat-input-send"]}
  2072. type="primary"
  2073. onClick={() => {
  2074. if (couldStop) {
  2075. stopAll();
  2076. setIsClickStop(true);
  2077. } else {
  2078. doSubmit(userInput);
  2079. }
  2080. }}
  2081. />
  2082. </label>
  2083. </div>
  2084. <div style={{ paddingBottom: 20, textAlign: 'center', color: '#888888', fontSize: 12 }}>
  2085. 内容由AI生成,仅供参考
  2086. </div>
  2087. {showExport && (
  2088. <ExportMessageModal onClose={() => setShowExport(false)} />
  2089. )}
  2090. {isEditingMessage && (
  2091. <EditMessageModal
  2092. onClose={() => {
  2093. setIsEditingMessage(false);
  2094. }}
  2095. />
  2096. )}
  2097. </div>
  2098. );
  2099. }
  2100. export function Chat() {
  2101. const chatStore = useChatStore();
  2102. const location = useLocation();
  2103. const sessionIndex = chatStore.currentSessionIndex;
  2104. useEffect(() => {
  2105. chatStore.setModel('BigModel');
  2106. const search = location.search;
  2107. const params = new URLSearchParams(search);
  2108. const chatMode = params.get('chatMode');
  2109. if (chatMode) {
  2110. chatStore.setChatMode(chatMode as "ONLINE" | "LOCAL");
  2111. }
  2112. }, []);
  2113. return <_Chat key={sessionIndex}></_Chat>;
  2114. }