DeepSeekChat.tsx 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  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 hlw from "../icons/hlw.png";
  24. import {
  25. SubmitKey,
  26. useChatStore,
  27. useAccessStore,
  28. Theme,
  29. useAppConfig,
  30. DEFAULT_TOPIC,
  31. ModelType,
  32. } from "../store";
  33. import {
  34. copyToClipboard,
  35. selectOrCopy,
  36. autoGrowTextArea,
  37. useMobileScreen,
  38. getMessageTextContent,
  39. getMessageImages,
  40. isVisionModel,
  41. isDalle3,
  42. } from "../utils";
  43. import { uploadImage as uploadImageRemote } from "@/app/utils/chat";
  44. import dynamic from "next/dynamic";
  45. import { ChatControllerPool } from "../client/controller";
  46. import { DalleSize } from "../typing";
  47. import type { RequestMessage } from "../client/api";
  48. import { Prompt, usePromptStore } from "../store/prompt";
  49. import { useGlobalStore } from "../store";
  50. import Locale from "../locales";
  51. import { IconButton } from "./button";
  52. import styles from "./chat.module.scss";
  53. import {
  54. List,
  55. ListItem,
  56. Modal,
  57. Selector,
  58. showConfirm,
  59. showToast,
  60. } from "./ui-lib";
  61. import { useNavigate, useLocation } from "react-router-dom";
  62. import {
  63. CHAT_PAGE_SIZE,
  64. LAST_INPUT_KEY,
  65. Path,
  66. REQUEST_TIMEOUT_MS,
  67. UNFINISHED_INPUT,
  68. ServiceProvider,
  69. Plugin,
  70. } from "../constant";
  71. import { ContextPrompts, MaskConfig } from "./mask";
  72. import { useMaskStore } from "../store/mask";
  73. import { ChatCommandPrefix, useChatCommand, useCommand } from "../command";
  74. import { prettyObject } from "../utils/format";
  75. import { ExportMessageModal } from "./exporter";
  76. import { getClientConfig } from "../config/client";
  77. import { useAllModels } from "../utils/hooks";
  78. import { nanoid } from "nanoid";
  79. import { message, Upload, UploadProps } from "antd";
  80. import { PaperClipOutlined, SendOutlined } from '@ant-design/icons';
  81. export function createMessage(override: Partial<ChatMessage>): ChatMessage {
  82. return {
  83. id: nanoid(),
  84. date: new Date().toLocaleString(),
  85. role: "user",
  86. content: "",
  87. ...override,
  88. };
  89. }
  90. export type ChatMessage = RequestMessage & {
  91. date: string;
  92. streaming?: boolean;
  93. isError?: boolean;
  94. id: string;
  95. model?: ModelType;
  96. };
  97. export const BOT_HELLO: ChatMessage = createMessage({
  98. role: "assistant",
  99. content: '您好,我是小智',
  100. });
  101. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  102. loading: () => <LoadingIcon />,
  103. });
  104. export function SessionConfigModel(props: { onClose: () => void }) {
  105. const chatStore = useChatStore();
  106. const session = chatStore.currentSession();
  107. const maskStore = useMaskStore();
  108. const navigate = useNavigate();
  109. return (
  110. <div className="modal-mask">
  111. <Modal
  112. title={Locale.Context.Edit}
  113. onClose={() => props.onClose()}
  114. actions={[
  115. <IconButton
  116. key="reset"
  117. icon={<ResetIcon />}
  118. bordered
  119. text={Locale.Chat.Config.Reset}
  120. onClick={async () => {
  121. if (await showConfirm(Locale.Memory.ResetConfirm)) {
  122. chatStore.updateCurrentSession(
  123. (session) => (session.memoryPrompt = ""),
  124. );
  125. }
  126. }}
  127. />,
  128. <IconButton
  129. key="copy"
  130. icon={<CopyIcon />}
  131. bordered
  132. text={Locale.Chat.Config.SaveAs}
  133. onClick={() => {
  134. navigate(Path.Masks);
  135. setTimeout(() => {
  136. maskStore.create(session.mask);
  137. }, 500);
  138. }}
  139. />,
  140. ]}
  141. >
  142. <MaskConfig
  143. mask={session.mask}
  144. updateMask={(updater) => {
  145. const mask = { ...session.mask };
  146. updater(mask);
  147. chatStore.updateCurrentSession((session) => (session.mask = mask));
  148. }}
  149. shouldSyncFromGlobal
  150. extraListItems={
  151. session.mask.modelConfig.sendMemory ? (
  152. <ListItem
  153. className="copyable"
  154. title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`}
  155. subTitle={session.memoryPrompt || Locale.Memory.EmptyContent}
  156. ></ListItem>
  157. ) : (
  158. <></>
  159. )
  160. }
  161. ></MaskConfig>
  162. </Modal>
  163. </div>
  164. );
  165. }
  166. // 提示词
  167. const CallWord = (props: {
  168. setUserInput: (value: string) => void,
  169. doSubmit: (userInput: string) => void,
  170. }) => {
  171. const { setUserInput, doSubmit } = props
  172. const list = [
  173. {
  174. title: '信息公布',
  175. // text: '在哪里查看招聘信息?',
  176. text: '今年上海建科工程咨询的校园招聘什么时候开始?如何查阅相关招聘信息?',
  177. },
  178. {
  179. title: '招聘岗位',
  180. // text: '今年招聘的岗位有哪些?',
  181. text: '今年招聘的岗位有哪些?',
  182. },
  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. return (
  210. <>
  211. {
  212. list.map((item, index) => {
  213. return <span
  214. key={index}
  215. style={{
  216. padding: '5px 10px',
  217. background: '#f6f7f8',
  218. color: '#5e5e66',
  219. borderRadius: 4,
  220. margin: '0 5px 10px 0',
  221. cursor: 'pointer',
  222. fontSize: 12
  223. }}
  224. onClick={() => {
  225. const plan: string = '2';
  226. if (plan === '1') {
  227. // 方案1.点击后出现在输入框内,用户自己点击发送
  228. setUserInput(item.text);
  229. } else {
  230. // 方案2.点击后直接发送
  231. doSubmit(item.text)
  232. }
  233. }}
  234. >
  235. {item.title}
  236. </span>
  237. })
  238. }
  239. </>
  240. )
  241. }
  242. function PromptToast(props: {
  243. showToast?: boolean;
  244. showModal?: boolean;
  245. setShowModal: (_: boolean) => void;
  246. }) {
  247. const chatStore = useChatStore();
  248. const session = chatStore.currentSession();
  249. const context = session.mask.context;
  250. return (
  251. <div className={styles["prompt-toast"]} key="prompt-toast">
  252. {props.showToast && (
  253. <div
  254. className={styles["prompt-toast-inner"] + " clickable"}
  255. role="button"
  256. onClick={() => props.setShowModal(true)}
  257. >
  258. <BrainIcon />
  259. <span className={styles["prompt-toast-content"]}>
  260. {Locale.Context.Toast(context.length)}
  261. </span>
  262. </div>
  263. )}
  264. {props.showModal && (
  265. <SessionConfigModel onClose={() => props.setShowModal(false)} />
  266. )}
  267. </div>
  268. );
  269. }
  270. function useSubmitHandler() {
  271. const config = useAppConfig();
  272. const submitKey = config.submitKey;
  273. const isComposing = useRef(false);
  274. useEffect(() => {
  275. const onCompositionStart = () => {
  276. isComposing.current = true;
  277. };
  278. const onCompositionEnd = () => {
  279. isComposing.current = false;
  280. };
  281. window.addEventListener("compositionstart", onCompositionStart);
  282. window.addEventListener("compositionend", onCompositionEnd);
  283. return () => {
  284. window.removeEventListener("compositionstart", onCompositionStart);
  285. window.removeEventListener("compositionend", onCompositionEnd);
  286. };
  287. }, []);
  288. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  289. // Fix Chinese input method "Enter" on Safari
  290. if (e.keyCode == 229) return false;
  291. if (e.key !== "Enter") return false;
  292. if (e.key === "Enter" && (e.nativeEvent.isComposing || isComposing.current))
  293. return false;
  294. return (
  295. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  296. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  297. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  298. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  299. (config.submitKey === SubmitKey.Enter &&
  300. !e.altKey &&
  301. !e.ctrlKey &&
  302. !e.shiftKey &&
  303. !e.metaKey)
  304. );
  305. };
  306. return {
  307. submitKey,
  308. shouldSubmit,
  309. };
  310. }
  311. export type RenderPrompt = Pick<Prompt, "title" | "content">;
  312. export function PromptHints(props: {
  313. prompts: RenderPrompt[];
  314. onPromptSelect: (prompt: RenderPrompt) => void;
  315. }) {
  316. const noPrompts = props.prompts.length === 0;
  317. const [selectIndex, setSelectIndex] = useState(0);
  318. const selectedRef = useRef<HTMLDivElement>(null);
  319. useEffect(() => {
  320. setSelectIndex(0);
  321. }, [props.prompts.length]);
  322. useEffect(() => {
  323. const onKeyDown = (e: KeyboardEvent) => {
  324. if (noPrompts || e.metaKey || e.altKey || e.ctrlKey) {
  325. return;
  326. }
  327. // arrow up / down to select prompt
  328. const changeIndex = (delta: number) => {
  329. e.stopPropagation();
  330. e.preventDefault();
  331. const nextIndex = Math.max(
  332. 0,
  333. Math.min(props.prompts.length - 1, selectIndex + delta),
  334. );
  335. setSelectIndex(nextIndex);
  336. selectedRef.current?.scrollIntoView({
  337. block: "center",
  338. });
  339. };
  340. if (e.key === "ArrowUp") {
  341. changeIndex(1);
  342. } else if (e.key === "ArrowDown") {
  343. changeIndex(-1);
  344. } else if (e.key === "Enter") {
  345. const selectedPrompt = props.prompts.at(selectIndex);
  346. if (selectedPrompt) {
  347. props.onPromptSelect(selectedPrompt);
  348. }
  349. }
  350. };
  351. window.addEventListener("keydown", onKeyDown);
  352. return () => window.removeEventListener("keydown", onKeyDown);
  353. // eslint-disable-next-line react-hooks/exhaustive-deps
  354. }, [props.prompts.length, selectIndex]);
  355. if (noPrompts) return null;
  356. return (
  357. <div className={styles["prompt-hints"]}>
  358. {props.prompts.map((prompt, i) => (
  359. <div
  360. ref={i === selectIndex ? selectedRef : null}
  361. className={
  362. styles["prompt-hint"] +
  363. ` ${i === selectIndex ? styles["prompt-hint-selected"] : ""}`
  364. }
  365. key={prompt.title + i.toString()}
  366. onClick={() => props.onPromptSelect(prompt)}
  367. onMouseEnter={() => setSelectIndex(i)}
  368. >
  369. <div className={styles["hint-title"]}>{prompt.title}</div>
  370. <div className={styles["hint-content"]}>{prompt.content}</div>
  371. </div>
  372. ))}
  373. </div>
  374. );
  375. }
  376. function ClearContextDivider() {
  377. const chatStore = useChatStore();
  378. return (
  379. <div
  380. className={styles["clear-context"]}
  381. onClick={() =>
  382. chatStore.updateCurrentSession(
  383. (session) => (session.clearContextIndex = undefined),
  384. )
  385. }
  386. >
  387. <div className={styles["clear-context-tips"]}>{Locale.Context.Clear}</div>
  388. <div className={styles["clear-context-revert-btn"]}>
  389. {Locale.Context.Revert}
  390. </div>
  391. </div>
  392. );
  393. }
  394. export function ChatAction(props: {
  395. text: string;
  396. icon: JSX.Element;
  397. onClick: () => void;
  398. }) {
  399. const iconRef = useRef<HTMLDivElement>(null);
  400. const textRef = useRef<HTMLDivElement>(null);
  401. const [width, setWidth] = useState({
  402. full: 16,
  403. icon: 16,
  404. });
  405. function updateWidth() {
  406. if (!iconRef.current || !textRef.current) return;
  407. const getWidth = (dom: HTMLDivElement) => dom.getBoundingClientRect().width;
  408. const textWidth = getWidth(textRef.current);
  409. const iconWidth = getWidth(iconRef.current);
  410. setWidth({
  411. full: textWidth + iconWidth,
  412. icon: iconWidth,
  413. });
  414. }
  415. return (
  416. <div
  417. className={`${styles["chat-input-action"]} clickable`}
  418. onClick={() => {
  419. props.onClick();
  420. setTimeout(updateWidth, 1);
  421. }}
  422. onMouseEnter={updateWidth}
  423. onTouchStart={updateWidth}
  424. style={
  425. {
  426. "--icon-width": `${width.icon}px`,
  427. "--full-width": `${width.full}px`,
  428. } as React.CSSProperties
  429. }
  430. >
  431. <div ref={iconRef} className={styles["icon"]}>
  432. {props.icon}
  433. </div>
  434. <div className={styles["text"]} ref={textRef}>
  435. {props.text}
  436. </div>
  437. </div>
  438. );
  439. }
  440. function useScrollToBottom(
  441. scrollRef: RefObject<HTMLDivElement>,
  442. detach: boolean = false,
  443. ) {
  444. // for auto-scroll
  445. const [autoScroll, setAutoScroll] = useState(true);
  446. function scrollDomToBottom() {
  447. const dom = scrollRef.current;
  448. if (dom) {
  449. requestAnimationFrame(() => {
  450. setAutoScroll(true);
  451. dom.scrollTo(0, dom.scrollHeight);
  452. });
  453. }
  454. }
  455. // auto scroll
  456. useEffect(() => {
  457. if (autoScroll && !detach) {
  458. scrollDomToBottom();
  459. }
  460. });
  461. return {
  462. scrollRef,
  463. autoScroll,
  464. setAutoScroll,
  465. scrollDomToBottom,
  466. };
  467. }
  468. export function ChatActions(props: {
  469. setUserInput: (value: string) => void;
  470. doSubmit: (userInput: string) => void;
  471. uploadImage: () => void;
  472. setAttachImages: (images: string[]) => void;
  473. setUploading: (uploading: boolean) => void;
  474. showPromptModal: () => void;
  475. scrollToBottom: () => void;
  476. showPromptHints: () => void;
  477. hitBottom: boolean;
  478. uploading: boolean;
  479. }) {
  480. const config = useAppConfig();
  481. const navigate = useNavigate();
  482. const chatStore = useChatStore();
  483. // switch themes
  484. const theme = config.theme;
  485. function nextTheme() {
  486. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  487. const themeIndex = themes.indexOf(theme);
  488. const nextIndex = (themeIndex + 1) % themes.length;
  489. const nextTheme = themes[nextIndex];
  490. config.update((config) => (config.theme = nextTheme));
  491. }
  492. // stop all responses
  493. const couldStop = ChatControllerPool.hasPending();
  494. const stopAll = () => ChatControllerPool.stopAll();
  495. // switch model
  496. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  497. const currentProviderName =
  498. chatStore.currentSession().mask.modelConfig?.providerName ||
  499. ServiceProvider.OpenAI;
  500. const allModels = useAllModels();
  501. const models = useMemo(() => {
  502. const filteredModels = allModels.filter((m) => m.available);
  503. const defaultModel = filteredModels.find((m) => m.isDefault);
  504. if (defaultModel) {
  505. const arr = [
  506. defaultModel,
  507. ...filteredModels.filter((m) => m !== defaultModel),
  508. ];
  509. return arr;
  510. } else {
  511. return filteredModels;
  512. }
  513. }, [allModels]);
  514. const currentModelName = useMemo(() => {
  515. const model = models.find(
  516. (m) =>
  517. m.name == currentModel &&
  518. m?.provider?.providerName == currentProviderName,
  519. );
  520. return model?.displayName ?? "";
  521. }, [models, currentModel, currentProviderName]);
  522. const [showModelSelector, setShowModelSelector] = useState(false);
  523. const [showPluginSelector, setShowPluginSelector] = useState(false);
  524. const [showUploadImage, setShowUploadImage] = useState(false);
  525. type GuessList = string[]
  526. const [guessList, setGuessList] = useState<GuessList>([]);
  527. const [showSizeSelector, setShowSizeSelector] = useState(false);
  528. const dalle3Sizes: DalleSize[] = ["1024x1024", "1792x1024", "1024x1792"];
  529. const currentSize =
  530. chatStore.currentSession().mask.modelConfig?.size ?? "1024x1024";
  531. const session = chatStore.currentSession();
  532. useEffect(() => {
  533. const show = isVisionModel(currentModel);
  534. setShowUploadImage(show);
  535. if (!show) {
  536. props.setAttachImages([]);
  537. props.setUploading(false);
  538. }
  539. // if current model is not available
  540. // switch to first available model
  541. const isUnavaliableModel = !models.some((m) => m.name === currentModel);
  542. if (isUnavaliableModel && models.length > 0) {
  543. // show next model to default model if exist
  544. let nextModel = models.find((model) => model.isDefault) || models[0];
  545. chatStore.updateCurrentSession((session) => {
  546. session.mask.modelConfig.model = nextModel.name;
  547. session.mask.modelConfig.providerName = nextModel?.provider?.providerName as ServiceProvider;
  548. });
  549. showToast(
  550. nextModel?.provider?.providerName == "ByteDance"
  551. ? nextModel.displayName
  552. : nextModel.name,
  553. );
  554. }
  555. }, [chatStore, currentModel, models]);
  556. return (
  557. <div className={styles["chat-input-actions"]}>
  558. {showModelSelector && (
  559. <Selector
  560. defaultSelectedValue={`${currentModel}@${currentProviderName}`}
  561. items={models.map((m) => ({
  562. title: `${m.displayName}${m?.provider?.providerName
  563. ? "(" + m?.provider?.providerName + ")"
  564. : ""
  565. }`,
  566. value: `${m.name}@${m?.provider?.providerName}`,
  567. }))}
  568. onClose={() => setShowModelSelector(false)}
  569. onSelection={(s) => {
  570. if (s.length === 0) return;
  571. const [model, providerName] = s[0].split("@");
  572. chatStore.updateCurrentSession((session) => {
  573. session.mask.modelConfig.model = model as ModelType;
  574. session.mask.modelConfig.providerName =
  575. providerName as ServiceProvider;
  576. session.mask.syncGlobalConfig = false;
  577. });
  578. if (providerName == "ByteDance") {
  579. const selectedModel = models.find(
  580. (m) =>
  581. m.name == model && m?.provider?.providerName == providerName,
  582. );
  583. showToast(selectedModel?.displayName ?? "");
  584. } else {
  585. showToast(model);
  586. }
  587. }}
  588. />
  589. )}
  590. {isDalle3(currentModel) && (
  591. <ChatAction
  592. onClick={() => setShowSizeSelector(true)}
  593. text={currentSize}
  594. icon={<SizeIcon />}
  595. />
  596. )}
  597. {showSizeSelector && (
  598. <Selector
  599. defaultSelectedValue={currentSize}
  600. items={dalle3Sizes.map((m) => ({
  601. title: m,
  602. value: m,
  603. }))}
  604. onClose={() => setShowSizeSelector(false)}
  605. onSelection={(s) => {
  606. if (s.length === 0) return;
  607. const size = s[0];
  608. chatStore.updateCurrentSession((session) => {
  609. session.mask.modelConfig.size = size;
  610. });
  611. showToast(size);
  612. }}
  613. />
  614. )}
  615. {showPluginSelector && (
  616. <Selector
  617. multiple
  618. defaultSelectedValue={chatStore.currentSession().mask?.plugin}
  619. items={[
  620. {
  621. title: Locale.Plugin.Artifacts,
  622. value: Plugin.Artifacts,
  623. },
  624. ]}
  625. onClose={() => setShowPluginSelector(false)}
  626. onSelection={(s) => {
  627. const plugin = s[0];
  628. chatStore.updateCurrentSession((session) => {
  629. session.mask.plugin = s;
  630. });
  631. if (plugin) {
  632. showToast(plugin);
  633. }
  634. }}
  635. />
  636. )}
  637. </div>
  638. );
  639. }
  640. export function EditMessageModal(props: { onClose: () => void }) {
  641. const chatStore = useChatStore();
  642. const session = chatStore.currentSession();
  643. const [messages, setMessages] = useState(session.messages.slice());
  644. return (
  645. <div className="modal-mask">
  646. <Modal
  647. title={Locale.Chat.EditMessage.Title}
  648. onClose={props.onClose}
  649. actions={[
  650. <IconButton
  651. text={Locale.UI.Cancel}
  652. icon={<CancelIcon />}
  653. key="cancel"
  654. onClick={() => {
  655. props.onClose();
  656. }}
  657. />,
  658. <IconButton
  659. type="primary"
  660. text={Locale.UI.Confirm}
  661. icon={<ConfirmIcon />}
  662. key="ok"
  663. onClick={() => {
  664. chatStore.updateCurrentSession(
  665. (session) => (session.messages = messages),
  666. );
  667. props.onClose();
  668. }}
  669. />,
  670. ]}
  671. >
  672. <List>
  673. <ListItem
  674. title={Locale.Chat.EditMessage.Topic.Title}
  675. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  676. >
  677. <input
  678. type="text"
  679. value={session.topic}
  680. onInput={(e) =>
  681. chatStore.updateCurrentSession(
  682. (session) => (session.topic = e.currentTarget.value),
  683. )
  684. }
  685. ></input>
  686. </ListItem>
  687. </List>
  688. <ContextPrompts
  689. context={messages}
  690. updateContext={(updater) => {
  691. const newMessages = messages.slice();
  692. updater(newMessages);
  693. setMessages(newMessages);
  694. }}
  695. />
  696. </Modal>
  697. </div>
  698. );
  699. }
  700. export function DeleteImageButton(props: { deleteImage: () => void }) {
  701. return (
  702. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  703. <DeleteIcon />
  704. </div>
  705. );
  706. }
  707. function _Chat() {
  708. type RenderMessage = ChatMessage & { preview?: boolean };
  709. const chatStore = useChatStore();
  710. const session = chatStore.currentSession();
  711. const config = useAppConfig();
  712. const fontSize = config.fontSize;
  713. const fontFamily = config.fontFamily;
  714. const [showExport, setShowExport] = useState(false);
  715. const inputRef = useRef<HTMLTextAreaElement>(null);
  716. const [userInput, setUserInput] = useState("");
  717. const [isLoading, setIsLoading] = useState(false);
  718. const { submitKey, shouldSubmit } = useSubmitHandler();
  719. const scrollRef = useRef<HTMLDivElement>(null);
  720. const isScrolledToBottom = scrollRef?.current
  721. ? Math.abs(
  722. scrollRef.current.scrollHeight -
  723. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  724. ) <= 1
  725. : false;
  726. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  727. scrollRef,
  728. isScrolledToBottom,
  729. );
  730. const [hitBottom, setHitBottom] = useState(true);
  731. const isMobileScreen = useMobileScreen();
  732. const navigate = useNavigate();
  733. const [attachImages, setAttachImages] = useState<string[]>([]);
  734. const [uploading, setUploading] = useState(false);
  735. // prompt hints
  736. const promptStore = usePromptStore();
  737. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  738. const onSearch = useDebouncedCallback(
  739. (text: string) => {
  740. const matchedPrompts = promptStore.search(text);
  741. setPromptHints(matchedPrompts);
  742. },
  743. 100,
  744. { leading: true, trailing: true },
  745. );
  746. useEffect(() => {
  747. chatStore.updateCurrentSession((session) => {
  748. session.appId = '1881269958412521255';
  749. });
  750. }, [])
  751. const [inputRows, setInputRows] = useState(2);
  752. const measure = useDebouncedCallback(
  753. () => {
  754. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  755. const inputRows = Math.min(
  756. 20,
  757. Math.max(2 + Number(!isMobileScreen), rows),
  758. );
  759. setInputRows(inputRows);
  760. },
  761. 100,
  762. {
  763. leading: true,
  764. trailing: true,
  765. },
  766. );
  767. // eslint-disable-next-line react-hooks/exhaustive-deps
  768. useEffect(measure, [userInput]);
  769. // chat commands shortcuts
  770. const chatCommands = useChatCommand({
  771. new: () => chatStore.newSession(),
  772. newm: () => navigate(Path.NewChat),
  773. prev: () => chatStore.nextSession(-1),
  774. next: () => chatStore.nextSession(1),
  775. clear: () =>
  776. chatStore.updateCurrentSession(
  777. (session) => (session.clearContextIndex = session.messages.length),
  778. ),
  779. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  780. });
  781. // only search prompts when user input is short
  782. const SEARCH_TEXT_LIMIT = 30;
  783. const onInput = (text: string) => {
  784. setUserInput(text);
  785. const n = text.trim().length;
  786. // clear search results
  787. if (n === 0) {
  788. setPromptHints([]);
  789. } else if (text.match(ChatCommandPrefix)) {
  790. setPromptHints(chatCommands.search(text));
  791. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  792. // check if need to trigger auto completion
  793. if (text.startsWith("/")) {
  794. let searchText = text.slice(1);
  795. onSearch(searchText);
  796. }
  797. }
  798. };
  799. const doSubmit = (userInput: string, fileList?: any[]) => {
  800. if (userInput.trim() === "") return;
  801. const matchCommand = chatCommands.match(userInput);
  802. if (matchCommand.matched) {
  803. setUserInput("");
  804. setPromptHints([]);
  805. matchCommand.invoke();
  806. return;
  807. }
  808. setIsLoading(true);
  809. chatStore.onUserInput(fileList || [], userInput, attachImages).then(() => setIsLoading(false));
  810. setAttachImages([]);
  811. localStorage.setItem(LAST_INPUT_KEY, userInput);
  812. setUserInput("");
  813. setPromptHints([]);
  814. if (!isMobileScreen) inputRef.current?.focus();
  815. setFileList([]);
  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. return (
  1197. <div className={styles.chat} key={session.id}>
  1198. {
  1199. isMobileScreen &&
  1200. <div className="window-header" data-tauri-drag-region>
  1201. <div style={{ display: 'flex', alignItems: 'center' }}
  1202. className={`window-header-title ${styles["chat-body-title"]}`}>
  1203. <div>
  1204. <IconButton
  1205. style={{ padding: 0, marginRight: 20 }}
  1206. icon={<LeftIcon />}
  1207. text={Locale.NewChat.Return}
  1208. onClick={() => navigate('/deepseekChat')}
  1209. />
  1210. </div>
  1211. </div>
  1212. </div>
  1213. }
  1214. <div
  1215. className={styles["chat-body"]}
  1216. ref={scrollRef}
  1217. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1218. onMouseDown={() => inputRef.current?.blur()}
  1219. onTouchStart={() => {
  1220. inputRef.current?.blur();
  1221. setAutoScroll(false);
  1222. }}
  1223. >
  1224. <>
  1225. {messages.map((message, i) => {
  1226. const isUser = message.role === "user";
  1227. const isContext = i < context.length;
  1228. const showActions =
  1229. i > 0 &&
  1230. !(message.preview || message.content.length === 0) &&
  1231. !isContext;
  1232. const showTyping = message.preview || message.streaming;
  1233. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1234. return (
  1235. <Fragment key={message.id}>
  1236. <div
  1237. className={
  1238. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1239. }
  1240. >
  1241. <div className={styles["chat-message-container"]} style={{ display: 'flex', flexDirection: 'row' }}>
  1242. <div className={styles["chat-message-header"]}>
  1243. <div className={styles["chat-message-avatar"]}>
  1244. {isUser ? null : (
  1245. <img src={avatar.src} style={{ width: 40, marginRight: 10 }} />
  1246. )}
  1247. </div>
  1248. </div>
  1249. {/* {
  1250. isUser && message.document && message.document.url &&
  1251. <div>
  1252. {message.document.url}
  1253. </div>
  1254. } */}
  1255. {/* {showTyping && (
  1256. <div className={styles["chat-message-status"]}>
  1257. 正在输入…
  1258. </div>
  1259. )} */}
  1260. <div className={styles["chat-message-item"]} style={{ marginTop: 20 }}>
  1261. <Markdown
  1262. key={message.streaming ? "loading" : "done"}
  1263. content={getMessageTextContent(message)}
  1264. loading={
  1265. (message.preview || message.streaming) &&
  1266. message.content.length === 0 &&
  1267. !isUser
  1268. }
  1269. onDoubleClickCapture={() => {
  1270. if (!isMobileScreen) return;
  1271. setUserInput(getMessageTextContent(message));
  1272. }}
  1273. fontSize={fontSize}
  1274. fontFamily={fontFamily}
  1275. parentRef={scrollRef}
  1276. defaultShow={i >= messages.length - 6}
  1277. />
  1278. {getMessageImages(message).length == 1 && (
  1279. <img
  1280. className={styles["chat-message-item-image"]}
  1281. src={getMessageImages(message)[0]}
  1282. alt=""
  1283. />
  1284. )}
  1285. {getMessageImages(message).length > 1 && (
  1286. <div
  1287. className={styles["chat-message-item-images"]}
  1288. style={
  1289. {
  1290. "--image-count": getMessageImages(message).length,
  1291. } as React.CSSProperties
  1292. }
  1293. >
  1294. {getMessageImages(message).map((image, index) => {
  1295. return (
  1296. <img
  1297. className={
  1298. styles["chat-message-item-image-multi"]
  1299. }
  1300. key={index}
  1301. src={image}
  1302. alt=""
  1303. />
  1304. );
  1305. })}
  1306. </div>
  1307. )}
  1308. </div>
  1309. </div>
  1310. </div>
  1311. {shouldShowClearContextDivider && <ClearContextDivider />}
  1312. </Fragment>
  1313. );
  1314. })}
  1315. </>
  1316. </div>
  1317. <div className={styles["chat-input-panel"]}>
  1318. <ChatActions
  1319. setUserInput={setUserInput}
  1320. doSubmit={doSubmit}
  1321. uploadImage={uploadImage}
  1322. setAttachImages={setAttachImages}
  1323. setUploading={setUploading}
  1324. showPromptModal={() => setShowPromptModal(true)}
  1325. scrollToBottom={scrollToBottom}
  1326. hitBottom={hitBottom}
  1327. uploading={uploading}
  1328. showPromptHints={() => {
  1329. if (promptHints.length > 0) {
  1330. setPromptHints([]);
  1331. return;
  1332. }
  1333. inputRef.current?.focus();
  1334. setUserInput("/");
  1335. onSearch("");
  1336. }}
  1337. />
  1338. {
  1339. fileList.length > 0 &&
  1340. <div style={{ marginBottom: 20 }}>
  1341. <Upload
  1342. fileList={fileList}
  1343. onRemove={(file) => {
  1344. setFileList(fileList.filter(item => item.uid !== file.uid));
  1345. }}
  1346. />
  1347. </div>
  1348. }
  1349. <label
  1350. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  1351. ? styles["chat-input-panel-inner-attach"]
  1352. : ""
  1353. }`}
  1354. htmlFor="chat-input"
  1355. >
  1356. <textarea
  1357. id="chat-input"
  1358. ref={inputRef}
  1359. className={styles["chat-input2"]}
  1360. placeholder={Locale.Chat.Input(submitKey)}
  1361. onInput={(e) => onInput(e.currentTarget.value)}
  1362. value={userInput}
  1363. onKeyDown={onInputKeyDown}
  1364. onFocus={scrollToBottom}
  1365. onClick={scrollToBottom}
  1366. onPaste={handlePaste}
  1367. rows={inputRows}
  1368. autoFocus={autoFocus}
  1369. style={{
  1370. fontSize: config.fontSize,
  1371. fontFamily: config.fontFamily,
  1372. }}
  1373. />
  1374. {attachImages.length != 0 && (
  1375. <div className={styles["attach-images"]}>
  1376. {attachImages.map((image, index) => {
  1377. return (
  1378. <div
  1379. key={index}
  1380. className={styles["attach-image"]}
  1381. style={{ backgroundImage: `url("${image}")` }}
  1382. >
  1383. <div className={styles["attach-image-mask"]}>
  1384. <DeleteImageButton
  1385. deleteImage={() => {
  1386. setAttachImages(
  1387. attachImages.filter((_, i) => i !== index),
  1388. );
  1389. }}
  1390. />
  1391. </div>
  1392. </div>
  1393. );
  1394. })}
  1395. </div>
  1396. )}
  1397. </label>
  1398. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 10 }}>
  1399. <div style={{ display: 'flex', alignItems: 'center' }}>
  1400. <div
  1401. style={{ padding: '0 10px', height: 30, borderRadius: 30, fontSize: 12, background: '#f3f4f6', display: 'flex', justifyContent: 'center', alignItems: 'center', marginRight: 20 }}
  1402. >
  1403. <img src={sdsk.src} style={{ height: 23 }} />
  1404. <div style={{ marginLeft: 5 }}>
  1405. 深度思考(R1)
  1406. </div>
  1407. </div>
  1408. <div
  1409. style={{ padding: '0 10px', height: 30, borderRadius: 30, fontSize: 12, background: '#f3f4f6', display: 'flex', justifyContent: 'center', alignItems: 'center' }}
  1410. >
  1411. <img src={hlw.src} style={{ height: 23 }} />
  1412. <div style={{ marginLeft: 5 }}>
  1413. 联网搜索
  1414. </div>
  1415. </div>
  1416. </div>
  1417. <div style={{ display: 'flex', alignItems: 'center' }}>
  1418. <div style={{ marginRight: 20 }}>
  1419. <Upload
  1420. {...uploadConfig}
  1421. showUploadList={false}
  1422. maxCount={1}
  1423. onChange={(info) => {
  1424. const fileList = info.fileList.map((file) => {
  1425. const data = file.response;
  1426. return {
  1427. ...file,
  1428. url: data?.document_url || file.url,
  1429. documentId: data?.document_id || '',
  1430. }
  1431. });
  1432. setFileList(fileList);
  1433. if (info.file.status === 'done') {// 上传成功
  1434. const { code, message: msg } = info.file.response;
  1435. if (code === 200) {
  1436. message.success('上传成功');
  1437. } else {
  1438. message.error(msg);
  1439. }
  1440. } else if (info.file.status === 'error') {// 上传失败
  1441. message.error('上传失败');
  1442. }
  1443. }}
  1444. >
  1445. <div
  1446. style={{
  1447. width: 35, height: 35, borderRadius: '50%', background: '#4357d2', display: 'flex', justifyContent: 'center', alignItems: 'center', cursor: 'pointer'
  1448. }}
  1449. >
  1450. <PaperClipOutlined style={{ color: '#FFFFFF', fontSize: '18px' }} />
  1451. </div>
  1452. </Upload>
  1453. </div>
  1454. <div
  1455. style={{
  1456. width: 35, height: 35, borderRadius: '50%', background: '#4357d2', display: 'flex', justifyContent: 'center', alignItems: 'center', cursor: 'pointer'
  1457. }}
  1458. onClick={() => doSubmit(userInput, fileList)}
  1459. >
  1460. <div style={{ transform: 'rotate(-45deg)', padding: '0px 0px 3px 5px' }}>
  1461. <SendOutlined style={{ color: '#FFFFFF' }} />
  1462. </div>
  1463. </div>
  1464. </div>
  1465. </div>
  1466. <div style={{ marginTop: 10, textAlign: 'center', color: '#888888', fontSize: 12 }}>
  1467. 内容由AI生成,仅供参考
  1468. </div>
  1469. </div>
  1470. {
  1471. showExport && (
  1472. <ExportMessageModal onClose={() => setShowExport(false)} />
  1473. )
  1474. }
  1475. {
  1476. isEditingMessage && (
  1477. <EditMessageModal
  1478. onClose={() => {
  1479. setIsEditingMessage(false);
  1480. }}
  1481. />
  1482. )
  1483. }
  1484. </div >
  1485. );
  1486. }
  1487. export function Chat() {
  1488. const chatStore = useChatStore();
  1489. const sessionIndex = chatStore.currentSessionIndex;
  1490. useEffect(() => {
  1491. chatStore.setModel('DeepSeek');
  1492. }, []);
  1493. return <_Chat key={sessionIndex}></_Chat>;
  1494. }