chat.tsx 54 KB

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