DeepSeekChat.tsx 55 KB

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