DeepSeekChat.tsx 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  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. // 切换聊天窗口后清理上传文件信息
  1242. useEffect(() => {
  1243. setWebSearch(false);
  1244. }, [chatStore.currentSession()])
  1245. const [webSearch, setWebSearch] = useState<boolean>(chatStore.web_search);
  1246. return (
  1247. <div className={styles.chat} key={session.id}>
  1248. {
  1249. isMobileScreen && location.pathname !== '/' &&
  1250. <div className="window-header" data-tauri-drag-region>
  1251. <div style={{ display: 'flex', alignItems: 'center' }}
  1252. className={`window-header-title ${styles["chat-body-title"]}`}>
  1253. <div>
  1254. <IconButton
  1255. style={{ padding: 0, marginRight: 20 }}
  1256. icon={<LeftIcon />}
  1257. text={Locale.NewChat.Return}
  1258. onClick={() => navigate('/deepseekChat')}
  1259. />
  1260. </div>
  1261. </div>
  1262. </div>
  1263. }
  1264. <div
  1265. className={styles["chat-body"]}
  1266. ref={scrollRef}
  1267. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1268. onMouseDown={() => inputRef.current?.blur()}
  1269. onTouchStart={() => {
  1270. inputRef.current?.blur();
  1271. setAutoScroll(false);
  1272. }}
  1273. >
  1274. <>
  1275. {messages.map((message, i) => {
  1276. const isUser = message.role === "user";
  1277. const isContext = i < context.length;
  1278. const showActions =
  1279. i > 0 &&
  1280. !(message.preview || message.content.length === 0) &&
  1281. !isContext;
  1282. const showTyping = message.preview || message.streaming;
  1283. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1284. return (
  1285. <Fragment key={message.id}>
  1286. <div
  1287. className={
  1288. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1289. }
  1290. >
  1291. <div className={styles["chat-message-container"]}
  1292. style={{ display: 'flex', flexDirection: 'column' }}>
  1293. <div className={styles["chat-message-header"]}>
  1294. <div className={styles["chat-message-avatar"]}>
  1295. {isUser ? (
  1296. // 在这里换头像
  1297. <div style={{ position: 'relative' }}>
  1298. <div
  1299. style={{
  1300. position: 'absolute',
  1301. zIndex: 2,
  1302. top: '50%',
  1303. left: '50%',
  1304. transform: ' translate(-110%, -100%)',
  1305. fontSize: 14,
  1306. }}>
  1307. </div>
  1308. </div>
  1309. ) : (
  1310. <>
  1311. {["system"].includes(message.role) ? (
  1312. <Avatar avatar="2699-fe0f" />
  1313. ) : (
  1314. <MaskAvatar
  1315. avatar={session.mask.avatar}
  1316. model={
  1317. message.model || session.mask.modelConfig.model
  1318. }
  1319. />
  1320. )}
  1321. </>
  1322. )}
  1323. </div>
  1324. </div>
  1325. {
  1326. isUser && message.document && message.document.id &&
  1327. <a style={{
  1328. padding: '10px',
  1329. background: '#f7f7f7',
  1330. borderRadius: '10px',
  1331. textDecoration: 'none',
  1332. color: '#24292f',
  1333. display: 'flex',
  1334. alignItems: 'center'
  1335. }} href={message.document.url} target="_blank">
  1336. <FileIcon fileName={message.document.name} />
  1337. <div style={{ marginLeft: 8, fontSize: '14px' }}>
  1338. {message.document.name}
  1339. </div>
  1340. </a>
  1341. }
  1342. {/* {showTyping && (
  1343. <div className={styles["chat-message-status"]}>
  1344. 正在输入…
  1345. </div>
  1346. )} */}
  1347. <div className={styles["chat-message-item"]}>
  1348. <Markdown
  1349. key={message.streaming ? "loading" : "done"}
  1350. content={getMessageTextContent(message)}
  1351. loading={
  1352. (message.preview || message.streaming) &&
  1353. message.content.length === 0 &&
  1354. !isUser
  1355. }
  1356. onDoubleClickCapture={() => {
  1357. if (!isMobileScreen) return;
  1358. setUserInput(getMessageTextContent(message));
  1359. }}
  1360. fontSize={fontSize}
  1361. fontFamily={fontFamily}
  1362. parentRef={scrollRef}
  1363. defaultShow={i >= messages.length - 6}
  1364. />
  1365. {getMessageImages(message).length == 1 && (
  1366. <img
  1367. className={styles["chat-message-item-image"]}
  1368. src={getMessageImages(message)[0]}
  1369. alt=""
  1370. />
  1371. )}
  1372. {getMessageImages(message).length > 1 && (
  1373. <div
  1374. className={styles["chat-message-item-images"]}
  1375. style={
  1376. {
  1377. "--image-count": getMessageImages(message).length,
  1378. } as React.CSSProperties
  1379. }
  1380. >
  1381. {getMessageImages(message).map((image, index) => {
  1382. return (
  1383. <img
  1384. className={
  1385. styles["chat-message-item-image-multi"]
  1386. }
  1387. key={index}
  1388. src={image}
  1389. alt=""
  1390. />
  1391. );
  1392. })}
  1393. </div>
  1394. )}
  1395. </div>
  1396. </div>
  1397. </div>
  1398. {shouldShowClearContextDivider && <ClearContextDivider />}
  1399. </Fragment>
  1400. );
  1401. })}
  1402. </>
  1403. </div>
  1404. <div className={styles["chat-input-panel"]}>
  1405. <ChatActions
  1406. setUserInput={setUserInput}
  1407. doSubmit={doSubmit}
  1408. uploadImage={uploadImage}
  1409. setAttachImages={setAttachImages}
  1410. setUploading={setUploading}
  1411. showPromptModal={() => setShowPromptModal(true)}
  1412. scrollToBottom={scrollToBottom}
  1413. hitBottom={hitBottom}
  1414. uploading={uploading}
  1415. showPromptHints={() => {
  1416. if (promptHints.length > 0) {
  1417. setPromptHints([]);
  1418. return;
  1419. }
  1420. inputRef.current?.focus();
  1421. setUserInput("/");
  1422. onSearch("");
  1423. }}
  1424. />
  1425. {
  1426. fileList.length > 0 &&
  1427. <div style={{ marginBottom: 20 }}>
  1428. <Upload
  1429. fileList={fileList}
  1430. onRemove={(file) => {
  1431. setFileList(fileList.filter(item => item.uid !== file.uid));
  1432. }}
  1433. />
  1434. </div>
  1435. }
  1436. <label
  1437. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  1438. ? styles["chat-input-panel-inner-attach"]
  1439. : ""
  1440. }`}
  1441. htmlFor="chat-input"
  1442. >
  1443. <textarea
  1444. id="chat-input"
  1445. ref={inputRef}
  1446. className={styles["chat-input2"]}
  1447. placeholder={Locale.Chat.Input(submitKey)}
  1448. onInput={(e) => onInput(e.currentTarget.value)}
  1449. value={userInput}
  1450. onKeyDown={onInputKeyDown}
  1451. onFocus={scrollToBottom}
  1452. onClick={scrollToBottom}
  1453. onPaste={handlePaste}
  1454. rows={inputRows}
  1455. autoFocus={autoFocus}
  1456. style={{
  1457. fontSize: config.fontSize,
  1458. fontFamily: config.fontFamily,
  1459. }}
  1460. />
  1461. {attachImages.length != 0 && (
  1462. <div className={styles["attach-images"]}>
  1463. {attachImages.map((image, index) => {
  1464. return (
  1465. <div
  1466. key={index}
  1467. className={styles["attach-image"]}
  1468. style={{ backgroundImage: `url("${image}")` }}
  1469. >
  1470. <div className={styles["attach-image-mask"]}>
  1471. <DeleteImageButton
  1472. deleteImage={() => {
  1473. setAttachImages(
  1474. attachImages.filter((_, i) => i !== index),
  1475. );
  1476. }}
  1477. />
  1478. </div>
  1479. </div>
  1480. );
  1481. })}
  1482. </div>
  1483. )}
  1484. </label>
  1485. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 10 }}>
  1486. <div style={{ display: 'flex', alignItems: 'center' }}>
  1487. {/*深度思考R1按钮*/}
  1488. <Tooltip
  1489. title={
  1490. <span style={{
  1491. fontSize: 12,
  1492. lineHeight: 1.4,
  1493. minHeight: 24,
  1494. padding: '4px 8px',
  1495. }}>
  1496. {isDeepThink ? '关闭深度思考模式' : '启用深度思考模式 (R1模型)'}
  1497. </span>
  1498. }
  1499. placement="left"
  1500. >
  1501. <div
  1502. style={{
  1503. padding: '0 12px',
  1504. height: 28,
  1505. borderRadius: 18,
  1506. fontSize: 12,
  1507. display: 'flex',
  1508. justifyContent: 'center',
  1509. alignItems: 'center',
  1510. marginRight: 10,
  1511. cursor: 'pointer',
  1512. background: isDeepThink ? '#dee9fc' : '#f3f4f6',
  1513. color: isDeepThink ? '#3875f6' : '#000000',
  1514. border: `1px solid ${isDeepThink ? '#3875f6' : 'transparent'}`,
  1515. transition: 'all 0.2s ease',
  1516. userSelect: 'none'
  1517. }}
  1518. onClick={() => {
  1519. setIsDeepThink(!isDeepThink);
  1520. chatStore.setIsDeepThink(!isDeepThink);
  1521. }}
  1522. >
  1523. <img
  1524. src={isDeepThink ? sdsk_selected.src : sdsk.src}
  1525. style={{
  1526. width: 18,
  1527. height: 18,
  1528. }}
  1529. />
  1530. <div style={{ marginLeft: 5 }}>
  1531. 深度思考 (R1)
  1532. </div>
  1533. </div>
  1534. </Tooltip>
  1535. {/*联网搜索按钮*/}
  1536. <div style={{
  1537. padding: '0 12px',
  1538. height: 28,
  1539. borderRadius: 18,
  1540. fontSize: 12,
  1541. display: 'flex',
  1542. justifyContent: 'center',
  1543. alignItems: 'center',
  1544. marginRight: 10,
  1545. cursor: 'pointer',
  1546. background: webSearch ? '#dee9fc' : '#f3f4f6',
  1547. color: webSearch ? '#3875f6' : '#000000',
  1548. border: `1px solid ${webSearch ? '#3875f6' : 'transparent'}`,
  1549. transition: 'all 0.2s ease',
  1550. userSelect: 'none'
  1551. }}
  1552. onClick={() => {
  1553. setWebSearch(!webSearch);
  1554. chatStore.setWebSearch(!webSearch);
  1555. }}
  1556. >
  1557. <img
  1558. src={hlw.src}
  1559. style={{
  1560. width: 18,
  1561. height: 18,
  1562. }}
  1563. />
  1564. <div style={{ marginLeft: 5 }}>
  1565. 联网搜索
  1566. </div>
  1567. </div>
  1568. </div>
  1569. <div style={{ display: 'flex', alignItems: 'center' }}>
  1570. <div style={{ marginRight: 10 }}>
  1571. <Upload
  1572. {...uploadConfig}
  1573. showUploadList={false}
  1574. maxCount={1}
  1575. onChange={(info) => {
  1576. const fileList = info.fileList.map((file) => {
  1577. const data = file.response;
  1578. return {
  1579. ...file,
  1580. url: data?.document_url || file.url,
  1581. documentId: data?.document_id || '',
  1582. }
  1583. });
  1584. setFileList(fileList);
  1585. if (info.file.status === 'done') {// 上传成功
  1586. const { code, message: msg } = info.file.response;
  1587. if (code === 200) {
  1588. message.success('上传成功');
  1589. } else {
  1590. message.error(msg);
  1591. }
  1592. } else if (info.file.status === 'error') {// 上传失败
  1593. message.error('上传失败');
  1594. }
  1595. }}
  1596. >
  1597. <Tooltip
  1598. title={
  1599. <div style={{ padding: '4px 8px' }}>
  1600. <div style={{
  1601. fontSize: 12,
  1602. lineHeight: 1.4,
  1603. marginBottom: 6,
  1604. }}>
  1605. 上传附件 (识别文本和图表中的内容)
  1606. </div>
  1607. <div style={{
  1608. fontSize: 10,
  1609. color: '#8c8c8c',
  1610. lineHeight: 1.4,
  1611. }}>
  1612. <span>
  1613. 仅支持单个PDF/Word/TXT文件格式
  1614. </span>
  1615. <span>
  1616. (单个文件≤50MB)
  1617. </span>
  1618. </div>
  1619. </div>
  1620. }
  1621. placement="top"
  1622. >
  1623. <div
  1624. style={{
  1625. width: 28,
  1626. height: 28,
  1627. borderRadius: '50%',
  1628. background: '#4357d2',
  1629. display: 'flex',
  1630. justifyContent: 'center',
  1631. alignItems: 'center',
  1632. cursor: 'pointer',
  1633. transition: 'all 0.2s ease',
  1634. userSelect: 'none'
  1635. }}
  1636. >
  1637. <PaperClipOutlined style={{ color: '#FFFFFF', fontSize: '18px' }} />
  1638. </div>
  1639. </Tooltip>
  1640. </Upload>
  1641. </div>
  1642. <div
  1643. style={{
  1644. width: 28,
  1645. height: 28,
  1646. borderRadius: '50%',
  1647. background: '#4357d2',
  1648. display: 'flex',
  1649. justifyContent: 'center',
  1650. alignItems: 'center',
  1651. cursor: 'pointer',
  1652. }}
  1653. onClick={() => {
  1654. if (couldStop) {
  1655. stopAll();
  1656. } else {
  1657. doSubmit(userInput);
  1658. }
  1659. }}
  1660. >
  1661. {
  1662. couldStop ?
  1663. <div style={{ width: 13, height: 13, background: '#FFFFFF', borderRadius: 2 }}></div>
  1664. :
  1665. <div style={{ transform: 'rotate(-45deg)', padding: '0px 0px 3px 5px' }}>
  1666. <SendOutlined style={{ color: '#FFFFFF' }} />
  1667. </div>
  1668. }
  1669. <div>
  1670. </div>
  1671. </div>
  1672. </div>
  1673. </div>
  1674. <div style={{ marginTop: 10, textAlign: 'center', color: '#888888', fontSize: 12 }}>
  1675. 内容由AI生成,仅供参考
  1676. </div>
  1677. </div>
  1678. {
  1679. showExport && (
  1680. <ExportMessageModal onClose={() => setShowExport(false)} />
  1681. )
  1682. }
  1683. {
  1684. isEditingMessage && (
  1685. <EditMessageModal
  1686. onClose={() => {
  1687. setIsEditingMessage(false);
  1688. }}
  1689. />
  1690. )
  1691. }
  1692. </div >
  1693. );
  1694. }
  1695. export function Chat() {
  1696. const chatStore = useChatStore();
  1697. const sessionIndex = chatStore.currentSessionIndex;
  1698. useEffect(() => {
  1699. chatStore.setModel('DeepSeek');
  1700. }, []);
  1701. return <_Chat key={sessionIndex}></_Chat>;
  1702. }