chat.tsx 55 KB

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