DeepSeekChat.tsx 46 KB

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