DeepSeekChat.tsx 58 KB

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