chat.tsx 53 KB

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