chat.tsx 54 KB

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