DeepSeekHomeChat.tsx 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  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 SendWhiteIcon from "../icons/send-white.svg";
  12. import BrainIcon from "../icons/brain.svg";
  13. import CopyIcon from "../icons/copy.svg";
  14. import LoadingIcon from "../icons/three-dots.svg";
  15. import ResetIcon from "../icons/reload.svg";
  16. import DeleteIcon from "../icons/clear.svg";
  17. import ConfirmIcon from "../icons/confirm.svg";
  18. import CancelIcon from "../icons/cancel.svg";
  19. import SizeIcon from "../icons/size.svg";
  20. import avatar from "../icons/aiIcon.png";
  21. import sdsk from "../icons/sdsk.png";
  22. import hlw from "../icons/hlw.png";
  23. import {
  24. SubmitKey,
  25. useChatStore,
  26. useAccessStore,
  27. Theme,
  28. useAppConfig,
  29. DEFAULT_TOPIC,
  30. ModelType,
  31. } from "../store";
  32. import {
  33. copyToClipboard,
  34. selectOrCopy,
  35. autoGrowTextArea,
  36. useMobileScreen,
  37. getMessageTextContent,
  38. getMessageImages,
  39. isVisionModel,
  40. isDalle3,
  41. } from "../utils";
  42. import { uploadImage as uploadImageRemote } from "@/app/utils/chat";
  43. import dynamic from "next/dynamic";
  44. import { ChatControllerPool } from "../client/controller";
  45. import { DalleSize } from "../typing";
  46. import type { RequestMessage } from "../client/api";
  47. import { Prompt, usePromptStore } from "../store/prompt";
  48. import { useGlobalStore } from "../store";
  49. import Locale from "../locales";
  50. import { IconButton } from "./button";
  51. import styles from "./chat.module.scss";
  52. import {
  53. List,
  54. ListItem,
  55. Modal,
  56. Selector,
  57. showConfirm,
  58. showToast,
  59. } from "./ui-lib";
  60. import { useNavigate, useLocation } from "react-router-dom";
  61. import {
  62. CHAT_PAGE_SIZE,
  63. LAST_INPUT_KEY,
  64. Path,
  65. REQUEST_TIMEOUT_MS,
  66. UNFINISHED_INPUT,
  67. ServiceProvider,
  68. Plugin,
  69. } from "../constant";
  70. import { ContextPrompts, MaskConfig } from "./mask";
  71. import { useMaskStore } from "../store/mask";
  72. import { ChatCommandPrefix, useChatCommand, useCommand } from "../command";
  73. import { prettyObject } from "../utils/format";
  74. import { ExportMessageModal } from "./exporter";
  75. import { getClientConfig } from "../config/client";
  76. import { useAllModels } from "../utils/hooks";
  77. import { nanoid } from "nanoid";
  78. import { SendOutlined } from '@ant-design/icons';
  79. export function createMessage(override: Partial<ChatMessage>): ChatMessage {
  80. return {
  81. id: nanoid(),
  82. date: new Date().toLocaleString(),
  83. role: "user",
  84. content: "",
  85. ...override,
  86. };
  87. }
  88. export type ChatMessage = RequestMessage & {
  89. date: string;
  90. streaming?: boolean;
  91. isError?: boolean;
  92. id: string;
  93. model?: ModelType;
  94. };
  95. export const BOT_HELLO: ChatMessage = createMessage({
  96. role: "assistant",
  97. content: '你好,我是小智~\n' +
  98. '我可以帮助你快速查询作业指导书、规范条文、公司信息等内容,如需获取上述内容,请点击上方导航栏中的「专业知识」或「职能管理」,选择相应的智能体进行提问。无论是现场技术,还是制度流程,我都会尽力为你解答!\n' +
  99. '请注意:在这个对话框内,我只能请DeepSeek来帮忙回答常见通用问题哦!',
  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. const [inputRows, setInputRows] = useState(2);
  747. const measure = useDebouncedCallback(
  748. () => {
  749. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  750. const inputRows = Math.min(
  751. 20,
  752. Math.max(2 + Number(!isMobileScreen), rows),
  753. );
  754. setInputRows(inputRows);
  755. },
  756. 100,
  757. {
  758. leading: true,
  759. trailing: true,
  760. },
  761. );
  762. // eslint-disable-next-line react-hooks/exhaustive-deps
  763. useEffect(measure, [userInput]);
  764. // chat commands shortcuts
  765. const chatCommands = useChatCommand({
  766. new: () => chatStore.newSession(),
  767. // newm: () => navigate(Path.MaskChat), // 关闭mask入口 ,后续有需求再二开
  768. prev: () => chatStore.nextSession(-1),
  769. next: () => chatStore.nextSession(1),
  770. clear: () =>
  771. chatStore.updateCurrentSession(
  772. (session) => (session.clearContextIndex = session.messages.length),
  773. ),
  774. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  775. });
  776. // only search prompts when user input is short
  777. const SEARCH_TEXT_LIMIT = 30;
  778. const onInput = (text: string) => {
  779. setUserInput(text);
  780. const n = text.trim().length;
  781. // clear search results
  782. if (n === 0) {
  783. setPromptHints([]);
  784. } else if (text.match(ChatCommandPrefix)) {
  785. setPromptHints(chatCommands.search(text));
  786. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  787. // check if need to trigger auto completion
  788. if (text.startsWith("/")) {
  789. let searchText = text.slice(1);
  790. onSearch(searchText);
  791. }
  792. }
  793. };
  794. const doSubmit = (userInput: string) => {
  795. if (userInput.trim() === "") return;
  796. const matchCommand = chatCommands.match(userInput);
  797. if (matchCommand.matched) {
  798. setUserInput("");
  799. setPromptHints([]);
  800. matchCommand.invoke();
  801. return;
  802. }
  803. setIsLoading(true);
  804. chatStore.onUserInput([], userInput, attachImages).then(() => setIsLoading(false));
  805. setAttachImages([]);
  806. localStorage.setItem(LAST_INPUT_KEY, userInput);
  807. setUserInput("");
  808. setPromptHints([]);
  809. if (!isMobileScreen) inputRef.current?.focus();
  810. setAutoScroll(true);
  811. };
  812. const onPromptSelect = (prompt: RenderPrompt) => {
  813. setTimeout(() => {
  814. setPromptHints([]);
  815. const matchedChatCommand = chatCommands.match(prompt.content);
  816. if (matchedChatCommand.matched) {
  817. // if user is selecting a chat command, just trigger it
  818. matchedChatCommand.invoke();
  819. setUserInput("");
  820. } else {
  821. // or fill the prompt
  822. setUserInput(prompt.content);
  823. }
  824. inputRef.current?.focus();
  825. }, 30);
  826. };
  827. // stop response
  828. const onUserStop = (messageId: string) => {
  829. ChatControllerPool.stop(session.id, messageId);
  830. };
  831. useEffect(() => {
  832. chatStore.updateCurrentSession((session) => {
  833. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  834. session.messages.forEach((m) => {
  835. // check if should stop all stale messages
  836. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  837. if (m.streaming) {
  838. m.streaming = false;
  839. }
  840. if (m.content.length === 0) {
  841. m.isError = true;
  842. m.content = prettyObject({
  843. error: true,
  844. message: "empty response",
  845. });
  846. }
  847. }
  848. });
  849. // auto sync mask config from global config
  850. if (session.mask.syncGlobalConfig) {
  851. console.log("[Mask] syncing from global, name = ", session.mask.name);
  852. session.mask.modelConfig = { ...config.modelConfig };
  853. }
  854. });
  855. // eslint-disable-next-line react-hooks/exhaustive-deps
  856. }, []);
  857. // check if should send message
  858. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  859. if (
  860. e.key === "ArrowUp" &&
  861. userInput.length <= 0 &&
  862. !(e.metaKey || e.altKey || e.ctrlKey)
  863. ) {
  864. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  865. e.preventDefault();
  866. return;
  867. }
  868. if (shouldSubmit(e) && promptHints.length === 0) {
  869. doSubmit(userInput);
  870. e.preventDefault();
  871. }
  872. };
  873. const onRightClick = (e: any, message: ChatMessage) => {
  874. // copy to clipboard
  875. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  876. if (userInput.length === 0) {
  877. setUserInput(getMessageTextContent(message));
  878. }
  879. e.preventDefault();
  880. }
  881. };
  882. const deleteMessage = (msgId?: string) => {
  883. chatStore.updateCurrentSession(
  884. (session) =>
  885. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  886. );
  887. };
  888. const onDelete = (msgId: string) => {
  889. deleteMessage(msgId);
  890. };
  891. const onResend = (message: ChatMessage) => {
  892. // when it is resending a message
  893. // 1. for a user's message, find the next bot response
  894. // 2. for a bot's message, find the last user's input
  895. // 3. delete original user input and bot's message
  896. // 4. resend the user's input
  897. const resendingIndex = session.messages.findIndex(
  898. (m) => m.id === message.id,
  899. );
  900. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  901. console.error("[Chat] failed to find resending message", message);
  902. return;
  903. }
  904. let userMessage: ChatMessage | undefined;
  905. let botMessage: ChatMessage | undefined;
  906. if (message.role === "assistant") {
  907. // if it is resending a bot's message, find the user input for it
  908. botMessage = message;
  909. for (let i = resendingIndex; i >= 0; i -= 1) {
  910. if (session.messages[i].role === "user") {
  911. userMessage = session.messages[i];
  912. break;
  913. }
  914. }
  915. } else if (message.role === "user") {
  916. // if it is resending a user's input, find the bot's response
  917. userMessage = message;
  918. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  919. if (session.messages[i].role === "assistant") {
  920. botMessage = session.messages[i];
  921. break;
  922. }
  923. }
  924. }
  925. if (userMessage === undefined) {
  926. console.error("[Chat] failed to resend", message);
  927. return;
  928. }
  929. // delete the original messages
  930. deleteMessage(userMessage.id);
  931. deleteMessage(botMessage?.id);
  932. // resend the message
  933. setIsLoading(true);
  934. const textContent = getMessageTextContent(userMessage);
  935. const images = getMessageImages(userMessage);
  936. chatStore.onUserInput([], textContent, images).then(() => setIsLoading(false));
  937. inputRef.current?.focus();
  938. };
  939. const onPinMessage = (message: ChatMessage) => {
  940. chatStore.updateCurrentSession((session) =>
  941. session.mask.context.push(message),
  942. );
  943. showToast(Locale.Chat.Actions.PinToastContent, {
  944. text: Locale.Chat.Actions.PinToastAction,
  945. onClick: () => {
  946. setShowPromptModal(true);
  947. },
  948. });
  949. };
  950. const context: RenderMessage[] = useMemo(() => {
  951. return session.mask.hideContext ? [] : session.mask.context.slice();
  952. }, [session.mask.context, session.mask.hideContext]);
  953. const accessStore = useAccessStore();
  954. if (
  955. context.length === 0 &&
  956. session.messages.at(0)?.content !== BOT_HELLO.content
  957. ) {
  958. const copiedHello = Object.assign({}, BOT_HELLO);
  959. if (!accessStore.isAuthorized()) {
  960. copiedHello.content = Locale.Error.Unauthorized;
  961. }
  962. context.push(copiedHello);
  963. }
  964. // preview messages
  965. const renderMessages = useMemo(() => {
  966. return context.concat(session.messages as RenderMessage[]).concat(
  967. isLoading
  968. ? [
  969. {
  970. ...createMessage({
  971. role: "assistant",
  972. content: "……",
  973. }),
  974. preview: true,
  975. },
  976. ]
  977. : [],
  978. ).concat(
  979. userInput.length > 0 && config.sendPreviewBubble
  980. ? [
  981. {
  982. ...createMessage({
  983. role: "user",
  984. content: userInput,
  985. }),
  986. preview: true,
  987. },
  988. ]
  989. : [],
  990. );
  991. }, [
  992. config.sendPreviewBubble,
  993. context,
  994. isLoading,
  995. session.messages,
  996. userInput,
  997. ]);
  998. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  999. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1000. );
  1001. function setMsgRenderIndex(newIndex: number) {
  1002. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1003. newIndex = Math.max(0, newIndex);
  1004. _setMsgRenderIndex(newIndex);
  1005. }
  1006. const messages = useMemo(() => {
  1007. const endRenderIndex = Math.min(
  1008. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1009. renderMessages.length,
  1010. );
  1011. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1012. }, [msgRenderIndex, renderMessages]);
  1013. const onChatBodyScroll = (e: HTMLElement) => {
  1014. const bottomHeight = e.scrollTop + e.clientHeight;
  1015. const edgeThreshold = e.clientHeight;
  1016. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1017. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1018. const isHitBottom =
  1019. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1020. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1021. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1022. if (isTouchTopEdge && !isTouchBottomEdge) {
  1023. setMsgRenderIndex(prevPageMsgIndex);
  1024. } else if (isTouchBottomEdge) {
  1025. setMsgRenderIndex(nextPageMsgIndex);
  1026. }
  1027. setHitBottom(isHitBottom);
  1028. setAutoScroll(isHitBottom);
  1029. };
  1030. function scrollToBottom() {
  1031. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1032. scrollDomToBottom();
  1033. }
  1034. // clear context index = context length + index in messages
  1035. const clearContextIndex =
  1036. (session.clearContextIndex ?? -1) >= 0
  1037. ? session.clearContextIndex! + context.length - msgRenderIndex
  1038. : -1;
  1039. const [showPromptModal, setShowPromptModal] = useState(false);
  1040. const clientConfig = useMemo(() => getClientConfig(), []);
  1041. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1042. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1043. useCommand({
  1044. fill: setUserInput,
  1045. submit: (text) => {
  1046. doSubmit(text);
  1047. },
  1048. code: (text) => {
  1049. if (accessStore.disableFastLink) return;
  1050. console.log("[Command] got code from url: ", text);
  1051. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1052. if (res) {
  1053. accessStore.update((access) => (access.accessCode = text));
  1054. }
  1055. });
  1056. },
  1057. settings: (text) => {
  1058. if (accessStore.disableFastLink) return;
  1059. try {
  1060. const payload = JSON.parse(text) as {
  1061. key?: string;
  1062. url?: string;
  1063. };
  1064. console.log("[Command] got settings from url: ", payload);
  1065. if (payload.key || payload.url) {
  1066. showConfirm(
  1067. Locale.URLCommand.Settings +
  1068. `\n${JSON.stringify(payload, null, 4)}`,
  1069. ).then((res) => {
  1070. if (!res) return;
  1071. if (payload.key) {
  1072. accessStore.update(
  1073. (access) => (access.openaiApiKey = payload.key!),
  1074. );
  1075. }
  1076. if (payload.url) {
  1077. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1078. }
  1079. accessStore.update((access) => (access.useCustomConfig = true));
  1080. });
  1081. }
  1082. } catch {
  1083. console.error("[Command] failed to get settings from url: ", text);
  1084. }
  1085. },
  1086. });
  1087. // edit / insert message modal
  1088. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1089. // remember unfinished input
  1090. useEffect(() => {
  1091. // try to load from local storage
  1092. const key = UNFINISHED_INPUT(session.id);
  1093. const mayBeUnfinishedInput = localStorage.getItem(key);
  1094. if (mayBeUnfinishedInput && userInput.length === 0) {
  1095. setUserInput(mayBeUnfinishedInput);
  1096. localStorage.removeItem(key);
  1097. }
  1098. const dom = inputRef.current;
  1099. return () => {
  1100. localStorage.setItem(key, dom?.value ?? "");
  1101. };
  1102. // eslint-disable-next-line react-hooks/exhaustive-deps
  1103. }, []);
  1104. const handlePaste = useCallback(
  1105. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1106. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1107. if (!isVisionModel(currentModel)) {
  1108. return;
  1109. }
  1110. const items = (event.clipboardData || window.clipboardData).items;
  1111. for (const item of items) {
  1112. if (item.kind === "file" && item.type.startsWith("image/")) {
  1113. event.preventDefault();
  1114. const file = item.getAsFile();
  1115. if (file) {
  1116. const images: string[] = [];
  1117. images.push(...attachImages);
  1118. images.push(
  1119. ...(await new Promise<string[]>((res, rej) => {
  1120. setUploading(true);
  1121. const imagesData: string[] = [];
  1122. uploadImageRemote(file).then((dataUrl) => {
  1123. imagesData.push(dataUrl);
  1124. setUploading(false);
  1125. res(imagesData);
  1126. }).catch((e) => {
  1127. setUploading(false);
  1128. rej(e);
  1129. });
  1130. })),
  1131. );
  1132. const imagesLength = images.length;
  1133. if (imagesLength > 3) {
  1134. images.splice(3, imagesLength - 3);
  1135. }
  1136. setAttachImages(images);
  1137. }
  1138. }
  1139. }
  1140. },
  1141. [attachImages, chatStore],
  1142. );
  1143. async function uploadImage() {
  1144. const images: string[] = [];
  1145. images.push(...attachImages);
  1146. images.push(
  1147. ...(await new Promise<string[]>((res, rej) => {
  1148. const fileInput = document.createElement("input");
  1149. fileInput.type = "file";
  1150. fileInput.accept =
  1151. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1152. fileInput.multiple = true;
  1153. fileInput.onchange = (event: any) => {
  1154. setUploading(true);
  1155. const files = event.target.files;
  1156. const imagesData: string[] = [];
  1157. for (let i = 0; i < files.length; i++) {
  1158. const file = event.target.files[i];
  1159. uploadImageRemote(file).then((dataUrl) => {
  1160. imagesData.push(dataUrl);
  1161. if (
  1162. imagesData.length === 3 ||
  1163. imagesData.length === files.length
  1164. ) {
  1165. setUploading(false);
  1166. res(imagesData);
  1167. }
  1168. }).catch((e) => {
  1169. setUploading(false);
  1170. rej(e);
  1171. });
  1172. }
  1173. };
  1174. fileInput.click();
  1175. })),
  1176. );
  1177. const imagesLength = images.length;
  1178. if (imagesLength > 3) {
  1179. images.splice(3, imagesLength - 3);
  1180. }
  1181. setAttachImages(images);
  1182. }
  1183. return (
  1184. <div className={styles.chat} key={session.id}>
  1185. <div
  1186. className={styles["chat-body"]}
  1187. ref={scrollRef}
  1188. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1189. onMouseDown={() => inputRef.current?.blur()}
  1190. onTouchStart={() => {
  1191. inputRef.current?.blur();
  1192. setAutoScroll(false);
  1193. }}
  1194. >
  1195. <>
  1196. {messages.map((message, i) => {
  1197. const isUser = message.role === "user";
  1198. const isContext = i < context.length;
  1199. const showActions =
  1200. i > 0 &&
  1201. !(message.preview || message.content.length === 0) &&
  1202. !isContext;
  1203. const showTyping = message.preview || message.streaming;
  1204. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1205. return (
  1206. <Fragment key={message.id}>
  1207. <div
  1208. className={
  1209. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1210. }
  1211. >
  1212. <div className={styles["chat-message-container"]} style={{ display: 'flex', flexDirection: 'row' }}>
  1213. <div className={styles["chat-message-header"]}>
  1214. <div className={styles["chat-message-avatar"]}>
  1215. {isUser ? null : (
  1216. <img src={avatar.src} style={{ width: 40, marginRight: 10 }} />
  1217. )}
  1218. </div>
  1219. </div>
  1220. {/* {showTyping && (
  1221. <div className={styles["chat-message-status"]}>
  1222. 正在输入…
  1223. </div>
  1224. )} */}
  1225. <div className={styles["chat-message-item"]} style={{ marginTop: 20 }}>
  1226. <Markdown
  1227. key={message.streaming ? "loading" : "done"}
  1228. content={getMessageTextContent(message)}
  1229. loading={
  1230. (message.preview || message.streaming) &&
  1231. message.content.length === 0 &&
  1232. !isUser
  1233. }
  1234. onDoubleClickCapture={() => {
  1235. if (!isMobileScreen) return;
  1236. setUserInput(getMessageTextContent(message));
  1237. }}
  1238. fontSize={fontSize}
  1239. fontFamily={fontFamily}
  1240. parentRef={scrollRef}
  1241. defaultShow={i >= messages.length - 6}
  1242. />
  1243. {getMessageImages(message).length == 1 && (
  1244. <img
  1245. className={styles["chat-message-item-image"]}
  1246. src={getMessageImages(message)[0]}
  1247. alt=""
  1248. />
  1249. )}
  1250. {getMessageImages(message).length > 1 && (
  1251. <div
  1252. className={styles["chat-message-item-images"]}
  1253. style={
  1254. {
  1255. "--image-count": getMessageImages(message).length,
  1256. } as React.CSSProperties
  1257. }
  1258. >
  1259. {getMessageImages(message).map((image, index) => {
  1260. return (
  1261. <img
  1262. className={
  1263. styles["chat-message-item-image-multi"]
  1264. }
  1265. key={index}
  1266. src={image}
  1267. alt=""
  1268. />
  1269. );
  1270. })}
  1271. </div>
  1272. )}
  1273. </div>
  1274. </div>
  1275. </div>
  1276. {shouldShowClearContextDivider && <ClearContextDivider />}
  1277. </Fragment>
  1278. );
  1279. })}
  1280. </>
  1281. </div>
  1282. <div className={styles["chat-input-panel"]}>
  1283. <ChatActions
  1284. setUserInput={setUserInput}
  1285. doSubmit={doSubmit}
  1286. uploadImage={uploadImage}
  1287. setAttachImages={setAttachImages}
  1288. setUploading={setUploading}
  1289. showPromptModal={() => setShowPromptModal(true)}
  1290. scrollToBottom={scrollToBottom}
  1291. hitBottom={hitBottom}
  1292. uploading={uploading}
  1293. showPromptHints={() => {
  1294. if (promptHints.length > 0) {
  1295. setPromptHints([]);
  1296. return;
  1297. }
  1298. inputRef.current?.focus();
  1299. setUserInput("/");
  1300. onSearch("");
  1301. }}
  1302. />
  1303. <label
  1304. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  1305. ? styles["chat-input-panel-inner-attach"]
  1306. : ""
  1307. }`}
  1308. htmlFor="chat-input"
  1309. >
  1310. <textarea
  1311. id="chat-input"
  1312. ref={inputRef}
  1313. className={styles["chat-input2"]}
  1314. placeholder={Locale.Chat.Input(submitKey)}
  1315. onInput={(e) => onInput(e.currentTarget.value)}
  1316. value={userInput}
  1317. onKeyDown={onInputKeyDown}
  1318. onFocus={scrollToBottom}
  1319. onClick={scrollToBottom}
  1320. onPaste={handlePaste}
  1321. rows={inputRows}
  1322. autoFocus={autoFocus}
  1323. style={{
  1324. fontSize: config.fontSize,
  1325. fontFamily: config.fontFamily,
  1326. }}
  1327. />
  1328. {attachImages.length != 0 && (
  1329. <div className={styles["attach-images"]}>
  1330. {attachImages.map((image, index) => {
  1331. return (
  1332. <div
  1333. key={index}
  1334. className={styles["attach-image"]}
  1335. style={{ backgroundImage: `url("${image}")` }}
  1336. >
  1337. <div className={styles["attach-image-mask"]}>
  1338. <DeleteImageButton
  1339. deleteImage={() => {
  1340. setAttachImages(
  1341. attachImages.filter((_, i) => i !== index),
  1342. );
  1343. }}
  1344. />
  1345. </div>
  1346. </div>
  1347. );
  1348. })}
  1349. </div>
  1350. )}
  1351. </label>
  1352. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 10 }}>
  1353. <div style={{ display: 'flex', alignItems: 'center' }}>
  1354. <div
  1355. style={{ padding: '0 10px', height: 30, borderRadius: 30, fontSize: 12, background: '#f3f4f6', display: 'flex', justifyContent: 'center', alignItems: 'center', marginRight: 20 }}
  1356. >
  1357. <img src={sdsk.src} style={{ height: 23 }} />
  1358. <div style={{ marginLeft: 5 }}>
  1359. 深度思考(R1)
  1360. </div>
  1361. </div>
  1362. <div
  1363. style={{ padding: '0 10px', height: 30, borderRadius: 30, fontSize: 12, background: '#f3f4f6', display: 'flex', justifyContent: 'center', alignItems: 'center' }}
  1364. >
  1365. <img src={hlw.src} style={{ height: 23 }} />
  1366. <div style={{ marginLeft: 5 }}>
  1367. 联网搜索
  1368. </div>
  1369. </div>
  1370. </div>
  1371. <div
  1372. style={{
  1373. width: 35, height: 35, borderRadius: '50%', background: '#4357d2', display: 'flex', justifyContent: 'center', alignItems: 'center', cursor: 'pointer'
  1374. }}
  1375. onClick={() => doSubmit(userInput)}
  1376. >
  1377. <div style={{ transform: 'rotate(-45deg)', padding: '0px 0px 3px 5px' }}>
  1378. <SendOutlined style={{ color: '#FFFFFF' }} />
  1379. </div>
  1380. </div>
  1381. </div>
  1382. <div style={{ marginTop: 10, textAlign: 'center', color: '#888888', fontSize: 12 }}>
  1383. 内容由AI生成,仅供参考
  1384. </div>
  1385. </div>
  1386. {showExport && (
  1387. <ExportMessageModal onClose={() => setShowExport(false)} />
  1388. )}
  1389. {isEditingMessage && (
  1390. <EditMessageModal
  1391. onClose={() => {
  1392. setIsEditingMessage(false);
  1393. }}
  1394. />
  1395. )}
  1396. </div>
  1397. );
  1398. }
  1399. export function Chat() {
  1400. const chatStore = useChatStore();
  1401. const sessionIndex = chatStore.currentSessionIndex;
  1402. useEffect(() => {
  1403. chatStore.setModel('DeepSeek');
  1404. }, []);
  1405. return <_Chat key={sessionIndex}></_Chat>;
  1406. }