DeepSeekChat.tsx 66 KB

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