DeepSeekChat.tsx 44 KB

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