DeepSeekHomeChat.tsx 45 KB

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