DeepSeekHomeChat.tsx 45 KB

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