DeepSeekChat.tsx 58 KB

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