chat.tsx 52 KB

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