DeepSeekChat.tsx 45 KB

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