DeepSeekChat.tsx 51 KB

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