chat.js 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250
  1. document.addEventListener('DOMContentLoaded', () => {
  2. // 注意:认证状态检查由 index.html 中的 checkAuthStatus 函数处理
  3. // 这里不再重复检查,避免冲突
  4. // 防重复重定向标志
  5. let isRedirecting = false;
  6. // 主题检测和适配功能
  7. function initThemeDetection () {
  8. // 检测当前主题偏好
  9. const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
  10. // 为body添加主题类名,便于CSS选择器
  11. if (prefersDark) {
  12. document.body.classList.add('dark-theme');
  13. document.body.classList.remove('light-theme');
  14. } else {
  15. document.body.classList.add('light-theme');
  16. document.body.classList.remove('dark-theme');
  17. }
  18. // 监听主题变化
  19. const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  20. mediaQuery.addEventListener('change', (e) => {
  21. if (e.matches) {
  22. // 切换到深色主题
  23. document.body.classList.add('dark-theme');
  24. document.body.classList.remove('light-theme');
  25. } else {
  26. // 切换到浅色主题
  27. document.body.classList.add('light-theme');
  28. document.body.classList.remove('dark-theme');
  29. }
  30. // 触发自定义事件,通知其他组件主题已变化
  31. window.dispatchEvent(new CustomEvent('themeChanged', {
  32. detail: { isDark: e.matches }
  33. }));
  34. });
  35. // 添加平滑过渡效果
  36. const style = document.createElement('style');
  37. style.textContent = `
  38. * {
  39. transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease, box-shadow 0.3s ease !important;
  40. }
  41. /* 确保过渡效果不会影响动画 */
  42. .typing-indicator span,
  43. .loading-spinner,
  44. .ripple,
  45. .message {
  46. transition: none !important;
  47. }
  48. `;
  49. document.head.appendChild(style);
  50. }
  51. // 初始化主题检测
  52. initThemeDetection();
  53. // 获取DOM元素
  54. const chatMessages = document.getElementById('chat-messages');
  55. const userInput = document.getElementById('user-input');
  56. const sendButton = document.getElementById('send-btn');
  57. const resetButton = document.getElementById('reset-btn');
  58. const logoutButton = document.getElementById('logout-btn');
  59. // 初始化复制按钮
  60. if (typeof window.setupCopyButtons === 'function') {
  61. window.setupCopyButtons();
  62. }
  63. // 绑定退出登录事件
  64. if (logoutButton) {
  65. logoutButton.addEventListener('click', handleLogout);
  66. }
  67. // 添加字符计数器样式
  68. const style = document.createElement('style');
  69. style.textContent = `
  70. .char-counter {
  71. position: absolute;
  72. bottom: 8px;
  73. right: 10px;
  74. font-size: 12px;
  75. color: #999;
  76. opacity: 0.8;
  77. transition: all 0.3s ease;
  78. display: flex;
  79. align-items: center;
  80. background: rgba(255, 255, 255, 0.9);
  81. padding: 2px 6px;
  82. border-radius: 4px;
  83. pointer-events: none;
  84. z-index: 1;
  85. }
  86. .char-counter.warning {
  87. color: #ff9800;
  88. font-weight: 500;
  89. background: rgba(255, 152, 0, 0.1);
  90. }
  91. .char-counter.exceeded {
  92. color: #f44336;
  93. font-weight: 500;
  94. background: rgba(244, 67, 54, 0.1);
  95. animation: pulse 1s infinite;
  96. }
  97. @keyframes pulse {
  98. 0% { transform: scale(1); }
  99. 50% { transform: scale(1.05); }
  100. 100% { transform: scale(1); }
  101. }
  102. .error-message {
  103. background-color: #ff5252;
  104. color: white;
  105. padding: 10px 15px;
  106. border-radius: 4px;
  107. margin: 10px auto;
  108. max-width: 80%;
  109. text-align: center;
  110. box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  111. position: relative;
  112. transition: opacity 0.3s ease, transform 0.3s ease;
  113. }
  114. /* AI思考过程样式 */
  115. .thought-container {
  116. background-color: #f3f0fa;
  117. border-left: 3px solid #7952b3;
  118. padding: 10px 15px;
  119. margin: 10px 0 10px 0;
  120. border-radius: 0 4px 4px 0;
  121. font-style: italic;
  122. color: #7952b3;
  123. position: relative;
  124. font-size: 0.98em;
  125. }
  126. .thought-container::before {
  127. content: "思考过程";
  128. display: block;
  129. font-size: 0.75rem;
  130. color: #7952b3;
  131. font-weight: 600;
  132. margin-bottom: 4px;
  133. font-style: normal;
  134. }
  135. .thought-toggle-btn {
  136. position: absolute;
  137. top: 8px;
  138. right: 12px;
  139. background: none;
  140. border: none;
  141. color: #7952b3;
  142. font-size: 1.1em;
  143. cursor: pointer;
  144. z-index: 2;
  145. padding: 2px 6px;
  146. border-radius: 3px;
  147. transition: background 0.2s;
  148. }
  149. .thought-toggle-btn:hover {
  150. background: #e5e1f6;
  151. }
  152. .thought-content {
  153. overflow-y: auto;
  154. max-height: 500px;
  155. transition: max-height 0.35s cubic-bezier(.4,0,.2,1), padding 0.3s;
  156. will-change: max-height;
  157. /* 自定义滚动条样式 */
  158. scrollbar-width: thin;
  159. scrollbar-color: #d1c4e9 #f3f0fa;
  160. }
  161. /* Webkit浏览器的滚动条样式 */
  162. .thought-content::-webkit-scrollbar {
  163. width: 8px;
  164. }
  165. .thought-content::-webkit-scrollbar-track {
  166. background: #f3f0fa;
  167. border-radius: 4px;
  168. }
  169. .thought-content::-webkit-scrollbar-thumb {
  170. background: linear-gradient(135deg, #d1c4e9, #b39ddb);
  171. border-radius: 4px;
  172. border: 1px solid #f3f0fa;
  173. transition: background 0.2s ease;
  174. }
  175. .thought-content::-webkit-scrollbar-thumb:hover {
  176. background: linear-gradient(135deg, #b39ddb, #9575cd);
  177. }
  178. .thought-content::-webkit-scrollbar-thumb:active {
  179. background: linear-gradient(135deg, #9575cd, #7e57c2);
  180. }
  181. .thought-container.collapsed .thought-content {
  182. max-height: 0;
  183. padding: 0 !important;
  184. }
  185. .thought-container.collapsed::before {
  186. content: "思考过程(已收起)";
  187. }
  188. .thought-container p {
  189. margin: 0 0 6px 0;
  190. font-style: italic;
  191. color: #7952b3;
  192. background: none;
  193. border-bottom: 1px dashed #d1c4e9;
  194. padding-bottom: 2px;
  195. }
  196. .thought-container p:last-child {
  197. border-bottom: none;
  198. }
  199. /* 打字机闪烁光标 */
  200. .cursor-blink {
  201. display: inline-block;
  202. color: #666;
  203. font-weight: bold;
  204. margin-left: 1px;
  205. animation: blink 1s step-end infinite;
  206. }
  207. @keyframes blink {
  208. 50% { opacity: 0; }
  209. }
  210. #send-btn:disabled {
  211. opacity: 0.6;
  212. cursor: not-allowed;
  213. transform: scale(0.98);
  214. }
  215. #send-btn:disabled:hover {
  216. background-color: #007bff;
  217. }
  218. /* 输入框Loading样式 */
  219. .input-loading {
  220. background-image: linear-gradient(90deg, rgba(239, 242, 255, 0.5), rgba(255, 255, 255, 0.8), rgba(239, 242, 255, 0.5));
  221. background-size: 200% 100%;
  222. animation: input-loading 1.5s infinite;
  223. border-color: #6366f1 !important;
  224. box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.15);
  225. }
  226. @keyframes input-loading {
  227. 0% { background-position: 100% 50%; }
  228. 100% { background-position: 0% 50%; }
  229. }
  230. /* 消息气泡动画效果 */
  231. .message-content.typing {
  232. position: relative;
  233. overflow: hidden;
  234. }
  235. .message-content.typing::before {
  236. content: '';
  237. position: absolute;
  238. top: 0;
  239. left: 0;
  240. right: 0;
  241. bottom: 0;
  242. border-radius: inherit;
  243. border: 2px solid;
  244. border-color: #6366f1;
  245. box-shadow: 0 0 5px rgba(99, 102, 241, 0.5);
  246. animation: border-pulse 0.8s ease-in-out infinite;
  247. pointer-events: none;
  248. }
  249. @keyframes border-pulse {
  250. 0% { opacity: 0.4; border-color: #6366f1; }
  251. 50% { opacity: 1; border-color: #818cf8; }
  252. 100% { opacity: 0.4; border-color: #6366f1; }
  253. }
  254. /* 对话切换状态样式 */
  255. .conversation-item.streaming {
  256. position: relative;
  257. }
  258. .conversation-item.streaming::after {
  259. content: '';
  260. position: absolute;
  261. top: 8px;
  262. right: 8px;
  263. width: 8px;
  264. height: 8px;
  265. background: #10b981;
  266. border-radius: 50%;
  267. animation: pulse-dot 2s infinite;
  268. }
  269. .conversation-item.paused {
  270. position: relative;
  271. }
  272. .conversation-item.paused::after {
  273. content: '';
  274. position: absolute;
  275. top: 8px;
  276. right: 8px;
  277. width: 8px;
  278. height: 8px;
  279. background: #f59e0b;
  280. border-radius: 50%;
  281. animation: pulse-dot 2s infinite;
  282. }
  283. @keyframes pulse-dot {
  284. 0% { opacity: 1; transform: scale(1); }
  285. 50% { opacity: 0.5; transform: scale(1.2); }
  286. 100% { opacity: 1; transform: scale(1); }
  287. }
  288. .paused-tip {
  289. background: rgba(245, 158, 11, 0.1);
  290. border: 1px solid rgba(245, 158, 11, 0.3);
  291. border-radius: 4px;
  292. padding: 4px 8px;
  293. font-size: 0.85em;
  294. color: #f59e0b;
  295. margin-top: 8px;
  296. font-style: italic;
  297. text-align: center;
  298. }
  299. `;
  300. document.head.appendChild(style);
  301. // 状态变量 - 确保用户ID始终存在
  302. let userId = localStorage.getItem('chat_user_id');
  303. if (!userId) {
  304. userId = generateUUID();
  305. localStorage.setItem('chat_user_id', userId);
  306. }
  307. // 新增:用于流式输出中断的标志
  308. let isStopped = false;
  309. let isWaitingForResponse = false;
  310. let currentBotMessageElement = null;
  311. let currentBotMessageContainer = null; // 添加消息容器引用
  312. let useStreamingMode = true; // 始终启用流式响应
  313. let currentLoadingElement = null;
  314. let markdownEnabled = true; // 启用 Markdown 渲染
  315. // 统一的Markdown渲染函数
  316. function renderMarkdown (text) {
  317. if (!markdownEnabled || typeof showdown === 'undefined') {
  318. return text;
  319. }
  320. const converter = new showdown.Converter({
  321. strikethrough: true,
  322. tables: true,
  323. tasklists: true,
  324. ghCodeBlocks: true,
  325. openLinksInNewWindow: true,
  326. emoji: true,
  327. underline: true,
  328. simplifiedAutoLink: true,
  329. excludeTrailingPunctuationFromURLs: true,
  330. literalMidWordUnderscores: true,
  331. tablesHeaderId: true,
  332. smoothLivePreview: true,
  333. smartIndentationFix: true,
  334. disableForced4SpacesIndentedSublists: true,
  335. simpleLineBreaks: true,
  336. requireSpaceBeforeHeadingText: true,
  337. ghCompatibleHeaderId: true,
  338. ghMentions: true,
  339. ghMentionsLink: 'https://github.com/{mention}',
  340. encodeEmails: true,
  341. backslashEscapesHTMLTags: true,
  342. omitExtraWLInCodeBlocks: true,
  343. noHeaderId: false,
  344. prefixHeaderId: false,
  345. rawPrefixHeaderId: false,
  346. rawHeaderId: false,
  347. headerLevelStart: 1,
  348. parseImgDimensions: true
  349. });
  350. return converter.makeHtml(text);
  351. }
  352. // 思考过程专用的渲染函数
  353. function renderThoughts (text) {
  354. if (!markdownEnabled || typeof showdown === 'undefined') {
  355. return text;
  356. }
  357. const converter = new showdown.Converter({
  358. strikethrough: true,
  359. tables: true,
  360. tasklists: true,
  361. ghCodeBlocks: true,
  362. openLinksInNewWindow: true,
  363. emoji: true,
  364. underline: true,
  365. simplifiedAutoLink: true,
  366. excludeTrailingPunctuationFromURLs: true,
  367. literalMidWordUnderscores: true,
  368. tablesHeaderId: true,
  369. smoothLivePreview: true,
  370. smartIndentationFix: true,
  371. disableForced4SpacesIndentedSublists: true,
  372. simpleLineBreaks: false, // 禁用简单换行,保持段落结构
  373. requireSpaceBeforeHeadingText: true,
  374. ghCompatibleHeaderId: true,
  375. ghMentions: true,
  376. ghMentionsLink: 'https://github.com/{mention}',
  377. encodeEmails: true,
  378. backslashEscapesHTMLTags: true,
  379. omitExtraWLInCodeBlocks: true,
  380. noHeaderId: false,
  381. prefixHeaderId: false,
  382. rawPrefixHeaderId: false,
  383. rawHeaderId: false,
  384. headerLevelStart: 1,
  385. parseImgDimensions: true
  386. });
  387. return converter.makeHtml(text);
  388. }
  389. let renderDebounceTimer = null; // 用于防抖动渲染
  390. let maxMessageLength = 20000; // 设置最大消息长度与后端POST限制一致
  391. let eventSource = null; // 存储EventSource实例,用于停止请求
  392. let abortController = null; // 用于中止fetch请求
  393. // 全局对话状态管理 - 支持多对话并发流式响应
  394. const conversationStates = new Map(); // 存储每个对话的状态
  395. let currentActiveConversationId = null; // 当前激活的对话ID
  396. let conversationStreams = new Map(); // 存储每个对话的流式连接
  397. // 用于控制自动滚动的变量
  398. let shouldAutoScroll = true;
  399. let lastScrollTop = 0;
  400. let scrollThreshold = 50; // 距离底部多少像素内触发自动滚动
  401. // 对话状态管理函数
  402. function initializeConversationState (conversationId) {
  403. if (!conversationStates.has(conversationId)) {
  404. conversationStates.set(conversationId, {
  405. isStreaming: false,
  406. isPaused: false,
  407. currentMessage: '',
  408. currentThoughts: [],
  409. messageElement: null,
  410. thoughtContainer: null,
  411. abortController: null,
  412. lastUpdateTime: Date.now(),
  413. isVisible: false,
  414. isUserStopped: false // 标记是否为用户主动停止
  415. });
  416. }
  417. }
  418. function setActiveConversation (conversationId) {
  419. // 暂停当前激活的对话(如果存在)
  420. if (currentActiveConversationId && currentActiveConversationId !== conversationId) {
  421. pauseConversationStream(currentActiveConversationId);
  422. }
  423. // 激活新对话
  424. currentActiveConversationId = conversationId;
  425. initializeConversationState(conversationId);
  426. // 切换对话时默认启用自动跟随底部
  427. shouldAutoScroll = true;
  428. const state = conversationStates.get(conversationId);
  429. state.isVisible = true;
  430. // 根据当前对话状态更新输入框UI
  431. updateInputUIForConversation(conversationId);
  432. // 如果该对话有正在进行的流式响应,恢复显示
  433. if (state.isStreaming) {
  434. if (state.isPaused) {
  435. // 如果被暂停了,恢复显示
  436. resumeConversationStream(conversationId);
  437. } else {
  438. // 如果正在流式响应但没有暂停,确保可见
  439. state.isVisible = true;
  440. updateConversationItemStatus(conversationId, 'streaming');
  441. // 确保消息元素可见
  442. if (state.messageElement) {
  443. state.messageElement.style.opacity = '1';
  444. state.messageElement.style.transform = 'translateY(0)';
  445. // 滚动到消息位置
  446. const chatMessages = document.getElementById('chat-messages');
  447. if (chatMessages) {
  448. state.messageElement.scrollIntoView({ behavior: 'smooth', block: 'end' });
  449. }
  450. }
  451. }
  452. } else if (state.currentMessage || state.currentThoughts.length > 0) {
  453. // 如果流式响应已完成,但还有内容,确保显示
  454. if (state.messageElement) {
  455. state.isVisible = true;
  456. updateConversationItemStatus(conversationId, 'stopped');
  457. // 确保消息元素可见
  458. state.messageElement.style.opacity = '1';
  459. state.messageElement.style.transform = 'translateY(0)';
  460. // 滚动到消息位置
  461. const chatMessages = document.getElementById('chat-messages');
  462. if (chatMessages && state.messageElement) {
  463. state.messageElement.scrollIntoView({ behavior: 'smooth', block: 'end' });
  464. }
  465. }
  466. }
  467. // 更新全局状态:检查是否有任何对话正在流式响应
  468. isWaitingForResponse = isAnyConversationStreaming();
  469. }
  470. // 根据对话状态更新输入框UI
  471. function updateInputUIForConversation (conversationId) {
  472. const state = conversationStates.get(conversationId);
  473. const userInput = document.getElementById('user-input');
  474. const sendButton = document.getElementById('send-btn');
  475. if (!userInput || !sendButton) return;
  476. // 检查当前对话是否正在流式响应
  477. const isCurrentConversationStreaming = state && state.isStreaming && !state.isPaused;
  478. if (isCurrentConversationStreaming) {
  479. // 如果当前对话正在流式响应,设置输入框为回复中状态
  480. userInput.classList.add('input-loading');
  481. userInput.placeholder = '正在回复中...';
  482. userInput.disabled = true;
  483. // 更新发送按钮为停止按钮
  484. sendButton.innerHTML = `
  485. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  486. <rect x="6" y="6" width="12" height="12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  487. </svg>`;
  488. sendButton.classList.add('stopping');
  489. // 更新全局状态
  490. isWaitingForResponse = true;
  491. } else {
  492. // 如果当前对话没有流式响应,恢复输入框为正常状态
  493. userInput.classList.remove('input-loading');
  494. userInput.placeholder = '请输入需要撰写的品类名和要求...';
  495. userInput.disabled = false;
  496. // 恢复发送按钮
  497. sendButton.innerHTML = `
  498. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  499. <path d="M22 2L11 13M22 2L15 22L11 13M11 13L2 9L22 2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  500. </svg>`;
  501. sendButton.classList.remove('stopping');
  502. // 更新全局状态
  503. isWaitingForResponse = false;
  504. }
  505. }
  506. // 新增:检查是否有任何对话正在流式响应
  507. function isAnyConversationStreaming () {
  508. for (const [conversationId, state] of conversationStates) {
  509. if (state.isStreaming && !state.isPaused) {
  510. return true;
  511. }
  512. }
  513. return false;
  514. }
  515. // 新增:获取当前正在流式响应的对话ID
  516. function getStreamingConversationId () {
  517. for (const [conversationId, state] of conversationStates) {
  518. if (state.isStreaming && !state.isPaused) {
  519. return conversationId;
  520. }
  521. }
  522. return null;
  523. }
  524. function pauseConversationStream (conversationId) {
  525. const state = conversationStates.get(conversationId);
  526. if (state && state.isStreaming) {
  527. state.isPaused = true;
  528. state.isVisible = false;
  529. // 在思考过程区域显示"已暂停"提示
  530. if (state.thoughtContainer && !state.thoughtContainer.querySelector('.paused-tip')) {
  531. const pausedTip = document.createElement('div');
  532. pausedTip.className = 'paused-tip';
  533. pausedTip.textContent = '对话已切换,AI回复已暂停';
  534. pausedTip.style.color = '#f59e0b';
  535. pausedTip.style.marginTop = '8px';
  536. pausedTip.style.fontSize = '0.9em';
  537. pausedTip.style.fontStyle = 'italic';
  538. state.thoughtContainer.appendChild(pausedTip);
  539. }
  540. // 更新侧边栏状态显示
  541. updateConversationItemStatus(conversationId, 'paused');
  542. }
  543. }
  544. function resumeConversationStream (conversationId) {
  545. const state = conversationStates.get(conversationId);
  546. if (state && state.isStreaming && state.isPaused) {
  547. state.isPaused = false;
  548. state.isVisible = true;
  549. // 移除暂停提示
  550. const pausedTip = state.thoughtContainer?.querySelector('.paused-tip');
  551. if (pausedTip) {
  552. pausedTip.remove();
  553. }
  554. // 更新侧边栏状态显示
  555. updateConversationItemStatus(conversationId, 'streaming');
  556. // 更新输入框状态
  557. updateInputUIForConversation(conversationId);
  558. // 恢复显示最新的思考过程
  559. if (state.thoughtContainer && state.currentThoughts.length > 0) {
  560. const thoughtContent = state.thoughtContainer.querySelector('.thought-content');
  561. if (thoughtContent) {
  562. const combinedThoughts = state.currentThoughts.join('');
  563. // 使用思考过程专用的渲染函数
  564. thoughtContent.innerHTML = renderThoughts(combinedThoughts);
  565. }
  566. }
  567. // 恢复显示最新的消息内容
  568. if (state.messageElement && state.currentMessage) {
  569. const contentContainer = state.messageElement.querySelector('.message-content');
  570. if (contentContainer) {
  571. debouncedRenderMarkdown(contentContainer, state.currentMessage);
  572. }
  573. }
  574. // 确保消息元素可见
  575. if (state.messageElement) {
  576. state.messageElement.style.opacity = '1';
  577. state.messageElement.style.transform = 'translateY(0)';
  578. // 滚动到当前对话的底部
  579. const chatMessages = document.getElementById('chat-messages');
  580. if (chatMessages) {
  581. chatMessages.scrollTop = chatMessages.scrollHeight;
  582. }
  583. }
  584. // 如果消息元素不在聊天区域中,重新添加到聊天区域
  585. if (state.messageElement && !state.messageElement.parentNode) {
  586. const chatMessages = document.getElementById('chat-messages');
  587. if (chatMessages) {
  588. chatMessages.appendChild(state.messageElement);
  589. // 滚动到底部
  590. setTimeout(() => {
  591. chatMessages.scrollTop = chatMessages.scrollHeight;
  592. }, 100);
  593. }
  594. }
  595. }
  596. }
  597. function stopConversationStream (conversationId) {
  598. const state = conversationStates.get(conversationId);
  599. if (state) {
  600. // 标记为用户主动停止
  601. state.isUserStopped = true;
  602. state.isStreaming = false;
  603. state.isPaused = false;
  604. if (state.abortController) {
  605. state.abortController.abort();
  606. state.abortController = null;
  607. }
  608. // 移除暂停提示
  609. const pausedTip = state.thoughtContainer?.querySelector('.paused-tip');
  610. if (pausedTip) {
  611. pausedTip.remove();
  612. }
  613. }
  614. // 更新侧边栏状态显示
  615. updateConversationItemStatus(conversationId, 'stopped');
  616. // 更新全局状态:检查是否有任何对话正在流式响应
  617. isWaitingForResponse = isAnyConversationStreaming();
  618. // 如果停止的是当前激活的对话,更新输入框状态
  619. if (conversationId === currentActiveConversationId) {
  620. updateInputUIForConversation(conversationId);
  621. }
  622. }
  623. function updateConversationItemStatus (conversationId, status) {
  624. const conversationItem = document.querySelector(`[data-conversation-id="${conversationId}"]`);
  625. if (conversationItem) {
  626. const statusDot = conversationItem.querySelector('.conversation-status-dot');
  627. // 移除所有状态类
  628. conversationItem.classList.remove('streaming', 'paused');
  629. // 添加新的状态类
  630. if (status === 'streaming') {
  631. conversationItem.classList.add('streaming');
  632. if (statusDot) {
  633. statusDot.style.opacity = '1';
  634. statusDot.style.background = '#10b981';
  635. }
  636. } else if (status === 'paused') {
  637. conversationItem.classList.add('paused');
  638. if (statusDot) {
  639. statusDot.style.opacity = '1';
  640. statusDot.style.background = '#f59e0b';
  641. }
  642. } else if (status === 'stopped') {
  643. if (statusDot) {
  644. statusDot.style.opacity = '0';
  645. }
  646. }
  647. }
  648. }
  649. // 创建字符计数器
  650. const charCounter = document.createElement('div');
  651. charCounter.className = 'char-counter';
  652. charCounter.textContent = '0/' + maxMessageLength;
  653. charCounter.id = 'char-counter';
  654. // 将字符计数器添加到输入框的父元素中,以便定位在输入框内部
  655. const inputContainer = document.querySelector('.chat-input-container');
  656. if (inputContainer) {
  657. inputContainer.style.position = 'relative';
  658. inputContainer.appendChild(charCounter);
  659. }
  660. // 防抖动函数
  661. function debounce (func, wait) {
  662. return function () {
  663. const context = this;
  664. const args = arguments;
  665. clearTimeout(renderDebounceTimer);
  666. renderDebounceTimer = setTimeout(() => {
  667. func.apply(context, args);
  668. }, wait);
  669. };
  670. }
  671. // 防抖动的Markdown渲染函数,确保光标跟随文字
  672. const debouncedRenderMarkdown = debounce((element, text) => {
  673. // 检查是否需要自动滚动
  674. const wasAtBottom = shouldAutoScroll && isUserNearBottom();
  675. // 使用 requestAnimationFrame 优化渲染性能
  676. requestAnimationFrame(() => {
  677. try {
  678. // 移除现有光标
  679. const existingCursor = element.querySelector('.cursor-blink');
  680. if (existingCursor) existingCursor.remove();
  681. // 使用统一的Markdown渲染函数
  682. element.innerHTML = renderMarkdown(text);
  683. // 添加代码高亮
  684. applyCodeHighlighting(element);
  685. // 处理审核结果表格
  686. processAuditResultTables();
  687. } catch (error) {
  688. // 出错时使用简单文本显示
  689. element.textContent = text;
  690. }
  691. // 根据情况滚动到底部
  692. if (wasAtBottom) {
  693. requestAnimationFrame(() => {
  694. forceScrollToBottom();
  695. });
  696. }
  697. });
  698. }, 16); // 降低防抖时间到16ms,约等于60fps
  699. // 改进 Markdown 解析器
  700. function parseMarkdown (text) {
  701. if (!markdownEnabled || !text) return text;
  702. try {
  703. // 检查marked是否存在
  704. if (typeof marked === 'undefined') {
  705. // 简单的备用实现:仅处理基本格式
  706. const formattedText = text
  707. .replace(/\n\n/g, '</p><p>') // 段落
  708. .replace(/\n/g, '<br>') // 换行
  709. .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // 粗体
  710. .replace(/\*(.*?)\*/g, '<em>$1</em>') // 斜体
  711. .replace(/`(.*?)`/g, '<code>$1</code>'); // 行内代码
  712. return `<div class="markdown-content"><p>${formattedText}</p></div>`;
  713. }
  714. // 配置marked选项
  715. marked.setOptions({
  716. renderer: new marked.Renderer(),
  717. highlight: function (code, lang) {
  718. const language = hljs.getLanguage(lang) ? lang : 'plaintext';
  719. return hljs.highlight(code, { language }).value;
  720. },
  721. langPrefix: 'hljs language-', // 为代码块添加类名
  722. pedantic: false,
  723. gfm: true,
  724. breaks: true,
  725. sanitize: false,
  726. smartypants: false,
  727. xhtml: false
  728. });
  729. // 创建自定义渲染器
  730. const renderer = new marked.Renderer();
  731. // 定制表格渲染方法
  732. renderer.table = function (header, body) {
  733. // 检测表格中是否包含违规内容
  734. const hasViolations = body.includes('violation-row');
  735. // 添加audit-result类,确保能应用我们的CSS样式
  736. return `<table class="audit-result ${hasViolations ? 'risk-table' : ''}" data-type="audit-result">\n<thead>\n${header}</thead>\n<tbody>\n${body}</tbody>\n</table>\n`;
  737. };
  738. // 定制表格行渲染方法
  739. renderer.tablerow = function (content) {
  740. // 检测行内是否包含违规关键词
  741. const violationKeywords = ['违规', '违反', '不符合', '禁止', '风险', '投诉', '举报', '警告', '严重', '不通过'];
  742. let rowClass = '';
  743. if (violationKeywords.some(keyword => content.includes(keyword))) {
  744. rowClass = 'violation-row';
  745. } else if (content.includes('注意') || content.includes('警示') || content.includes('提醒')) {
  746. rowClass = 'warning-row';
  747. } else if (content.includes('正常') || content.includes('合规') || content.includes('通过')) {
  748. rowClass = 'safe-row';
  749. }
  750. return `<tr class="${rowClass}">${content}</tr>\n`;
  751. };
  752. // 定制段落渲染方法
  753. renderer.paragraph = function (text) {
  754. // 高亮审核结果关键词
  755. if (text.includes('通过') && !text.includes('不通过')) {
  756. text = text.replace(
  757. /(.*?)(通过)(.*?)/g,
  758. '$1<span class="audit-pass">$2</span>$3'
  759. );
  760. }
  761. if (text.includes('不通过')) {
  762. text = text.replace(
  763. /(.*?)(不通过)(.*?)/g,
  764. '$1<span class="audit-fail">$2</span>$3'
  765. );
  766. }
  767. // 突出显示包含违规关键词的段落
  768. const violationKeywords = ['违规', '违反', '不符合', '禁止', '风险', '投诉', '举报', '警告', '严重'];
  769. violationKeywords.forEach(keyword => {
  770. if (text.includes(keyword)) {
  771. text = text.replace(
  772. new RegExp(`(.*?)(${keyword})(.*?)`, 'g'),
  773. '$1<span class="violation">$2</span>$3'
  774. );
  775. }
  776. });
  777. return `<p>${text}</p>\n`;
  778. };
  779. // 使用定制的渲染器解析Markdown
  780. marked.setOptions({ renderer: renderer });
  781. // 解析Markdown文本
  782. const parsed = marked.parse(text);
  783. // 添加markdown-content类以应用样式
  784. const result = `<div class="markdown-content">${parsed}</div>`;
  785. return result;
  786. } catch (error) {
  787. // 发生错误时,回退到原始文本
  788. return `<p>${text}</p>`;
  789. }
  790. }
  791. // 自动调整文本区域高度
  792. function autoResizeTextarea () {
  793. // 重置高度,以便重新计算
  794. userInput.style.height = 'auto';
  795. // 设置行高基准值
  796. const lineHeight = 24; // 假设行高为24px
  797. const minHeight = lineHeight + 12; // 最小高度,一行加上padding
  798. const maxHeight = 200; // 最大高度
  799. // 计算内容高度
  800. const contentHeight = userInput.scrollHeight;
  801. if (contentHeight <= minHeight) {
  802. // 内容少于或等于一行
  803. userInput.style.height = minHeight + 'px';
  804. userInput.style.overflowY = 'hidden'; // 隐藏滚动条
  805. } else if (contentHeight > maxHeight) {
  806. // 内容超过最大高度
  807. userInput.style.height = maxHeight + 'px';
  808. userInput.style.overflowY = 'auto'; // 显示滚动条
  809. } else {
  810. // 内容在一行和最大高度之间
  811. userInput.style.height = contentHeight + 'px';
  812. userInput.style.overflowY = 'hidden'; // 隐藏滚动条
  813. }
  814. }
  815. // 更新字符计数器
  816. function updateCharCounter () {
  817. const charCount = userInput.value.length;
  818. const counterElement = document.getElementById('char-counter');
  819. if (counterElement) {
  820. counterElement.textContent = `${charCount}/${maxMessageLength}`;
  821. // 当接近字符上限时改变样式提醒用户
  822. counterElement.classList.remove('warning', 'exceeded');
  823. if (charCount > maxMessageLength) {
  824. counterElement.classList.add('exceeded');
  825. } else if (charCount > maxMessageLength * 0.9) {
  826. counterElement.classList.add('warning');
  827. }
  828. }
  829. }
  830. // 检查用户是否接近底部
  831. function isUserNearBottom () {
  832. return chatMessages.scrollHeight - chatMessages.scrollTop - chatMessages.clientHeight < scrollThreshold;
  833. }
  834. // 强制滚动到底部
  835. function forceScrollToBottom (force = false) {
  836. // 如果正在编辑消息,不滚动
  837. if (window.isEditingMessage) {
  838. return;
  839. }
  840. if (!force && !shouldAutoScroll) {
  841. return;
  842. }
  843. chatMessages.scrollTop = chatMessages.scrollHeight;
  844. }
  845. // 添加用户消息
  846. function addUserMessage (message, messageId = null) {
  847. const messageElement = document.createElement('div');
  848. messageElement.className = 'message user';
  849. const contentElement = document.createElement('div');
  850. contentElement.className = 'message-content';
  851. contentElement.textContent = message;
  852. messageElement.appendChild(contentElement);
  853. // 如果有 messageId,添加编辑按钮
  854. if (messageId) {
  855. // 转义特殊字符,防止XSS攻击
  856. const escapedContent = message
  857. .replace(/\\/g, '\\\\')
  858. .replace(/"/g, '&quot;')
  859. .replace(/'/g, '&#39;')
  860. .replace(/</g, '&lt;')
  861. .replace(/>/g, '&gt;')
  862. .replace(/\n/g, '\\n');
  863. const editButton = document.createElement('button');
  864. editButton.className = 'edit-button';
  865. editButton.setAttribute('title', '编辑消息');
  866. editButton.innerHTML = `
  867. <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  868. <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  869. <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  870. </svg>
  871. `;
  872. editButton.onclick = function () {
  873. // 调用全局的 editMessage 函数(在 index.html 中定义)
  874. if (typeof window.editMessage === 'function') {
  875. window.editMessage(messageId, message);
  876. }
  877. };
  878. messageElement.appendChild(editButton);
  879. messageElement.setAttribute('data-message-id', messageId);
  880. }
  881. chatMessages.appendChild(messageElement);
  882. // 确保消息立即可见
  883. messageElement.style.opacity = '1';
  884. messageElement.style.transform = 'translateY(0)';
  885. // 滚动到底部
  886. forceScrollToBottom(true);
  887. return messageElement;
  888. }
  889. // 修改添加机器人消息函数
  890. function addBotMessage (message, isMarkdown = true, thoughts = []) {
  891. if (message.length <= 0 && (!thoughts || thoughts.length === 0)) {
  892. return;
  893. }
  894. const botMessage = document.createElement('div');
  895. botMessage.className = 'message bot-message';
  896. // 先渲染思考过程(如有)
  897. if (thoughts && Array.isArray(thoughts) && thoughts.length > 0) {
  898. const thoughtContainer = document.createElement('div');
  899. thoughtContainer.className = 'thought-container';
  900. // 创建折叠按钮
  901. const toggleBtn = document.createElement('button');
  902. toggleBtn.className = 'thought-toggle-btn';
  903. toggleBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
  904. toggleBtn.title = '收起/展开思考过程';
  905. toggleBtn.onclick = function (e) {
  906. e.stopPropagation();
  907. thoughtContainer.classList.toggle('collapsed');
  908. const icon = toggleBtn.querySelector('svg path');
  909. if (thoughtContainer.classList.contains('collapsed')) {
  910. icon.setAttribute('d', 'M18 15L12 9L6 15');
  911. } else {
  912. icon.setAttribute('d', 'M6 9l6 6 6-6');
  913. }
  914. };
  915. thoughtContainer.appendChild(toggleBtn);
  916. const contentArea = document.createElement('div');
  917. contentArea.className = 'thought-content';
  918. // 处理思考过程,显示为连续的文本块
  919. if (Array.isArray(thoughts)) {
  920. // 如果是数组,合并后使用思考过程专用的渲染函数
  921. const combinedThoughts = thoughts.join('');
  922. contentArea.innerHTML = renderThoughts(combinedThoughts);
  923. } else if (typeof thoughts === 'string') {
  924. // 如果是字符串,使用思考过程专用的渲染函数
  925. contentArea.innerHTML = renderThoughts(thoughts);
  926. }
  927. thoughtContainer.appendChild(contentArea);
  928. botMessage.appendChild(thoughtContainer);
  929. }
  930. // 再渲染AI回复内容
  931. const messageContent = document.createElement('div');
  932. messageContent.className = 'message-content';
  933. if (isMarkdown) {
  934. messageContent.innerHTML = renderMarkdown(message);
  935. } else {
  936. messageContent.innerText = message;
  937. }
  938. botMessage.appendChild(messageContent);
  939. document.getElementById('chat-messages').appendChild(botMessage);
  940. applyCodeHighlighting(botMessage);
  941. processAuditResultTables();
  942. // 为新添加的消息添加复制按钮
  943. if (typeof window.setupCopyButtons === 'function') {
  944. window.setupCopyButtons();
  945. }
  946. forceScrollToBottom();
  947. return botMessage;
  948. }
  949. // 添加错误消息
  950. function addErrorMessage (error, isAuthError = false) {
  951. // 如果已经有打字动画,则移除
  952. removeTypingAnimation();
  953. const errorElement = document.createElement('div');
  954. errorElement.className = 'error-message';
  955. if (isAuthError) {
  956. errorElement.innerHTML = `
  957. <div style="display: flex; align-items: center; gap: 8px;">
  958. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  959. <path d="M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  960. </svg>
  961. <span>${error}</span>
  962. </div>
  963. <div style="margin-top: 8px; font-size: 0.9em; opacity: 0.9;">
  964. 正在尝试重新连接,如果失败将跳转到登录页面...
  965. </div>
  966. `;
  967. } else {
  968. errorElement.textContent = error;
  969. }
  970. chatMessages.appendChild(errorElement);
  971. forceScrollToBottom();
  972. // 认证错误显示更长时间,其他错误5秒后移除
  973. const timeout = isAuthError ? 10000 : 5000;
  974. setTimeout(() => {
  975. if (errorElement.parentNode) {
  976. errorElement.parentNode.removeChild(errorElement);
  977. }
  978. }, timeout);
  979. }
  980. // 生成UUID
  981. function generateUUID () {
  982. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  983. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  984. return v.toString(16);
  985. });
  986. }
  987. // 应用代码块高亮
  988. function applyCodeHighlighting (element) {
  989. // 检查hljs是否存在
  990. if (typeof hljs === 'undefined') {
  991. return;
  992. }
  993. try {
  994. const codeBlocks = element.querySelectorAll('pre code');
  995. for (const block of codeBlocks) {
  996. hljs.highlightElement(block);
  997. }
  998. } catch (error) {
  999. }
  1000. }
  1001. // 处理审核结果表格
  1002. function processAuditResultTables () {
  1003. const tables = document.querySelectorAll('table.audit-result');
  1004. tables.forEach(table => {
  1005. // 如果表格已经处理过,则跳过
  1006. if (table.dataset.processed) return;
  1007. // 标记表格已处理
  1008. table.dataset.processed = 'true';
  1009. // 处理表格内的长文本
  1010. const cells = table.querySelectorAll('td');
  1011. cells.forEach(cell => {
  1012. if (cell.textContent.length > 100) {
  1013. cell.classList.add('long-text');
  1014. }
  1015. });
  1016. });
  1017. }
  1018. // 修改发送消息函数
  1019. function sendMessage () {
  1020. const message = userInput.value.trim();
  1021. // 检查是否有任何对话正在流式响应
  1022. if (!message || isAnyConversationStreaming()) return;
  1023. if (message.length > maxMessageLength) {
  1024. alert(`消息长度不能超过${maxMessageLength}字符`);
  1025. return;
  1026. }
  1027. // 获取当前对话ID
  1028. const conversationId = window.currentConversationId || 'new';
  1029. // 初始化对话状态
  1030. initializeConversationState(conversationId);
  1031. setActiveConversation(conversationId);
  1032. // 确保当前对话可见
  1033. const state = conversationStates.get(conversationId);
  1034. if (state) {
  1035. state.isVisible = true;
  1036. }
  1037. // 展示用户消息(立即显示,不等待后端响应)
  1038. // 注意:此时还没有 message_id,后续会在收到后端响应后更新
  1039. const userMessageElement = addUserMessage(message);
  1040. // 将用户消息保存到对话状态中,确保切换对话时不会丢失
  1041. if (state) {
  1042. state.userMessages = state.userMessages || [];
  1043. state.userMessages.push({
  1044. content: message,
  1045. timestamp: new Date(),
  1046. element: userMessageElement,
  1047. messageId: null // 将在收到后端响应后设置
  1048. });
  1049. }
  1050. // 清空输入框
  1051. userInput.value = '';
  1052. autoResizeTextarea();
  1053. updateCharCounter();
  1054. // 更新按钮状态为停止按钮
  1055. sendButton.innerHTML = `
  1056. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  1057. <rect x="6" y="6" width="12" height="12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  1058. </svg>`;
  1059. sendButton.classList.add('stopping');
  1060. // 标记正在等待响应
  1061. isWaitingForResponse = true;
  1062. // 将输入框设置为loading状态
  1063. userInput.classList.add('input-loading');
  1064. userInput.placeholder = '正在回复中...';
  1065. userInput.disabled = true;
  1066. // 准备请求数据
  1067. const requestData = {
  1068. message: message,
  1069. user_id: userId,
  1070. agent: (localStorage.getItem('current_agent') || 'kuaishou'),
  1071. conversation_id: window.currentConversationId || null,
  1072. session_id: window.currentSessionId || null,
  1073. force_new: window.forceNewConversation || false
  1074. };
  1075. // 重置强制创建新对话的标志
  1076. window.forceNewConversation = false;
  1077. // 根据选择的模式,使用不同的请求方式
  1078. if (useStreamingMode) {
  1079. handleStreamResponse(message, conversationId);
  1080. } else {
  1081. handleStandardResponse(message, requestData);
  1082. }
  1083. isStopped = false; // 每次发送消息时重置
  1084. }
  1085. // 修改处理流式响应函数
  1086. function handleStreamResponse (message, conversationId) {
  1087. const state = conversationStates.get(conversationId);
  1088. if (!state) {
  1089. return;
  1090. }
  1091. // 重置对话状态
  1092. state.isStreaming = true;
  1093. state.isPaused = false;
  1094. state.isUserStopped = false; // 重置用户停止标志
  1095. state.currentMessage = '';
  1096. state.currentThoughts = [];
  1097. state.lastUpdateTime = Date.now();
  1098. // 更新侧边栏状态显示
  1099. updateConversationItemStatus(conversationId, 'streaming');
  1100. let fullMessage = '';
  1101. let lastProcessedMessage = '';
  1102. let lastRenderTime = 0;
  1103. const RENDER_INTERVAL = 16; // 16ms,约等于60fps
  1104. let allThoughts = [];
  1105. let thoughtContainer = null; // 新增思考过程容器
  1106. let thoughtContent = null; // 新增思考内容包裹层
  1107. let thoughtToggleBtn = null; // 折叠按钮
  1108. let contentContainer = null; // 结果内容容器,初始不创建
  1109. try {
  1110. // 创建AbortController用于取消请求
  1111. state.abortController = new AbortController();
  1112. // 创建机器人消息元素
  1113. const messageDiv = document.createElement('div');
  1114. messageDiv.className = 'message bot';
  1115. // 创建思考过程容器
  1116. thoughtContainer = document.createElement('div');
  1117. thoughtContainer.className = 'thought-container';
  1118. // 创建折叠按钮
  1119. thoughtToggleBtn = document.createElement('button');
  1120. thoughtToggleBtn.className = 'thought-toggle-btn';
  1121. // 展开时默认向上箭头
  1122. thoughtToggleBtn.innerHTML = '<span class="toggle-icon">'
  1123. + '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">'
  1124. + '<path d="M18 15L12 9L6 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'
  1125. + '</svg>'
  1126. + '</span>';
  1127. thoughtToggleBtn.title = '收起/展开思考过程';
  1128. thoughtToggleBtn.onclick = function (e) {
  1129. e.stopPropagation();
  1130. thoughtContainer.classList.toggle('collapsed');
  1131. // 切换SVG图标
  1132. const icon = thoughtToggleBtn.querySelector('.toggle-icon');
  1133. if (thoughtContainer.classList.contains('collapsed')) {
  1134. // 向下箭头
  1135. icon.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">'
  1136. + '<path d="M6 9L12 15L18 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'
  1137. + '</svg>';
  1138. } else {
  1139. // 向上箭头
  1140. icon.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">'
  1141. + '<path d="M18 15L12 9L6 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'
  1142. + '</svg>';
  1143. }
  1144. };
  1145. thoughtContainer.appendChild(thoughtToggleBtn);
  1146. // 创建思考内容包裹层
  1147. thoughtContent = document.createElement('div');
  1148. thoughtContent.className = 'thought-content';
  1149. thoughtContainer.appendChild(thoughtContent);
  1150. messageDiv.appendChild(thoughtContainer);
  1151. // 保存到对话状态
  1152. state.messageElement = messageDiv;
  1153. state.thoughtContainer = thoughtContainer;
  1154. // 添加到聊天区域
  1155. chatMessages.appendChild(state.messageElement);
  1156. // 确保消息元素可见
  1157. messageDiv.style.opacity = '1';
  1158. messageDiv.style.transform = 'translateY(0)';
  1159. // 添加对话ID标识,便于后续管理
  1160. messageDiv.setAttribute('data-conversation-id', conversationId);
  1161. // 滚动到底部
  1162. forceScrollToBottom();
  1163. // 始终使用POST方法发送所有消息
  1164. fetch('/api/chat/stream', {
  1165. method: 'POST',
  1166. headers: {
  1167. 'Content-Type': 'application/json'
  1168. },
  1169. body: JSON.stringify({
  1170. message: message,
  1171. user_id: userId,
  1172. agent: (localStorage.getItem('current_agent') || 'kuaishou'),
  1173. conversation_id: window.currentConversationId || null,
  1174. session_id: window.currentSessionId || null,
  1175. force_new: window.forceNewConversation || false
  1176. }),
  1177. signal: state.abortController.signal
  1178. })
  1179. .then(response => {
  1180. if (!response.ok) {
  1181. throw new Error(`HTTP error! Status: ${response.status}`);
  1182. }
  1183. // 创建新的EventSource,包装响应
  1184. const reader = response.body.getReader();
  1185. const decoder = new TextDecoder();
  1186. let buffer = '';
  1187. function readStream () {
  1188. reader.read().then(({ done, value }) => {
  1189. if (done) {
  1190. // 流式响应完成
  1191. state.isStreaming = false;
  1192. updateConversationItemStatus(conversationId, 'stopped');
  1193. resetUIState();
  1194. return;
  1195. }
  1196. // 解码二进制数据为文本
  1197. const chunk = decoder.decode(value, { stream: true });
  1198. buffer += chunk;
  1199. // 处理buffer中完整的SSE消息
  1200. const lines = buffer.split('\n\n');
  1201. buffer = lines.pop() || ''; // 最后一个可能不完整,保留到下次处理
  1202. lines.forEach(line => {
  1203. if (line.startsWith('data: ')) {
  1204. try {
  1205. const eventData = JSON.parse(line.substring(6));
  1206. processEventData(eventData, state);
  1207. } catch (error) {
  1208. }
  1209. }
  1210. });
  1211. // 无论是否暂停,都继续读取流数据
  1212. readStream(); // 继续读取下一块数据
  1213. }).catch(error => {
  1214. // 如果是用户主动停止,不显示错误提示
  1215. if (!state.isPaused && !state.isUserStopped && error.name !== 'AbortError') {
  1216. addErrorMessage('连接错误,请重试');
  1217. }
  1218. state.isStreaming = false;
  1219. state.isUserStopped = false; // 重置标志
  1220. resetUIState();
  1221. });
  1222. }
  1223. readStream(); // 开始读取流
  1224. })
  1225. .catch(error => {
  1226. // 如果是用户主动停止(AbortError),不显示错误提示
  1227. if (!state.isPaused && !state.isUserStopped && error.name !== 'AbortError') {
  1228. if (error.message.includes('401')) {
  1229. addErrorMessage('登录已过期,正在重新连接...', true);
  1230. // 尝试刷新token
  1231. tryRefreshToken().then(refreshed => {
  1232. if (!refreshed) {
  1233. clearAuthAndRedirect();
  1234. }
  1235. });
  1236. } else {
  1237. addErrorMessage('连接错误,请重试: ' + error.message);
  1238. }
  1239. }
  1240. state.isStreaming = false;
  1241. state.isUserStopped = false; // 重置标志
  1242. updateConversationItemStatus(conversationId, 'stopped');
  1243. resetUIState();
  1244. });
  1245. // 提取通用的事件数据处理逻辑为函数
  1246. function processEventData (data, conversationState) {
  1247. // 更新最后更新时间
  1248. conversationState.lastUpdateTime = Date.now();
  1249. // 处理用户消息ID(在初始响应中返回)
  1250. if (data.user_message_id) {
  1251. // 更新最后添加的用户消息,为其添加编辑按钮
  1252. if (conversationState.userMessages && conversationState.userMessages.length > 0) {
  1253. const lastUserMessage = conversationState.userMessages[conversationState.userMessages.length - 1];
  1254. if (lastUserMessage && !lastUserMessage.messageId) {
  1255. lastUserMessage.messageId = data.user_message_id;
  1256. // 更新消息元素,添加编辑按钮
  1257. if (lastUserMessage.element) {
  1258. const messageElement = lastUserMessage.element;
  1259. const messageId = data.user_message_id;
  1260. const messageContent = lastUserMessage.content;
  1261. // 转义特殊字符
  1262. const escapedContent = messageContent
  1263. .replace(/\\/g, '\\\\')
  1264. .replace(/"/g, '&quot;')
  1265. .replace(/'/g, '&#39;')
  1266. .replace(/</g, '&lt;')
  1267. .replace(/>/g, '&gt;')
  1268. .replace(/\n/g, '\\n');
  1269. // 创建编辑按钮
  1270. const editButton = document.createElement('button');
  1271. editButton.className = 'edit-button';
  1272. editButton.setAttribute('title', '编辑消息');
  1273. editButton.innerHTML = `
  1274. <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  1275. <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  1276. <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  1277. </svg>
  1278. `;
  1279. editButton.onclick = function () {
  1280. if (typeof window.editMessage === 'function') {
  1281. window.editMessage(messageId, messageContent);
  1282. }
  1283. };
  1284. messageElement.appendChild(editButton);
  1285. messageElement.setAttribute('data-message-id', messageId);
  1286. }
  1287. }
  1288. }
  1289. }
  1290. if (!data.success) {
  1291. if (data.error && data.error.includes('401')) {
  1292. addErrorMessage('登录已过期,正在重新连接...', true);
  1293. // 尝试刷新token
  1294. tryRefreshToken().then(refreshed => {
  1295. if (!refreshed) {
  1296. clearAuthAndRedirect();
  1297. }
  1298. });
  1299. } else {
  1300. addErrorMessage(data.error || '发生未知错误');
  1301. }
  1302. conversationState.isStreaming = false;
  1303. updateConversationItemStatus(conversationId, 'stopped');
  1304. resetUIState();
  1305. return;
  1306. }
  1307. // 处理思考过程
  1308. if (data.thought) {
  1309. allThoughts.push(data.thought);
  1310. conversationState.currentThoughts = allThoughts;
  1311. // 显示为连续的文本块,不添加换行符
  1312. if (thoughtContent) {
  1313. const combinedThoughts = allThoughts.join('');
  1314. // 使用思考过程专用的渲染函数
  1315. thoughtContent.innerHTML = renderThoughts(combinedThoughts);
  1316. // 只有在可见且未暂停时才滚动
  1317. if (conversationState.isVisible && !conversationState.isPaused) {
  1318. forceScrollToBottom();
  1319. }
  1320. }
  1321. return;
  1322. }
  1323. if (data.chunk) {
  1324. fullMessage += data.chunk;
  1325. conversationState.currentMessage = fullMessage;
  1326. // 第一次收到chunk时再创建contentContainer
  1327. if (!contentContainer) {
  1328. contentContainer = document.createElement('div');
  1329. contentContainer.className = 'message-content typing';
  1330. messageDiv.appendChild(contentContainer);
  1331. }
  1332. // 使用 requestAnimationFrame 优化渲染性能
  1333. const now = performance.now();
  1334. if (now - lastRenderTime >= RENDER_INTERVAL) {
  1335. requestAnimationFrame(() => {
  1336. if (fullMessage !== lastProcessedMessage && contentContainer) {
  1337. // 总是渲染内容,但只在可见且未暂停时滚动
  1338. debouncedRenderMarkdown(contentContainer, fullMessage);
  1339. lastProcessedMessage = fullMessage;
  1340. if (conversationState.isVisible && !conversationState.isPaused && isUserNearBottom()) {
  1341. requestAnimationFrame(() => {
  1342. forceScrollToBottom();
  1343. });
  1344. }
  1345. }
  1346. });
  1347. lastRenderTime = now;
  1348. }
  1349. }
  1350. if (data.session_id) {
  1351. // 更新当前对话的session_id
  1352. window.currentSessionId = data.session_id;
  1353. }
  1354. if (data.conversation_id) {
  1355. // 更新当前对话ID
  1356. window.currentConversationId = data.conversation_id;
  1357. // 更新对话状态中的对话ID
  1358. if (conversationId !== data.conversation_id) {
  1359. // 获取当前状态
  1360. const currentState = conversationStates.get(conversationId);
  1361. if (currentState) {
  1362. // 更新状态到新的对话ID
  1363. conversationStates.set(data.conversation_id, currentState);
  1364. conversationStates.delete(conversationId);
  1365. // 更新当前激活的对话ID
  1366. if (currentActiveConversationId === conversationId) {
  1367. currentActiveConversationId = data.conversation_id;
  1368. }
  1369. }
  1370. }
  1371. }
  1372. if (data.done) {
  1373. if (contentContainer) {
  1374. contentContainer.classList.remove('typing');
  1375. // 只在done时渲染最终结果
  1376. debouncedRenderMarkdown(contentContainer, fullMessage);
  1377. }
  1378. conversationState.isStreaming = false;
  1379. updateConversationItemStatus(conversationId, 'stopped');
  1380. resetUIState();
  1381. userInput.focus();
  1382. if (conversationState.isVisible) {
  1383. forceScrollToBottom();
  1384. }
  1385. // 为流式响应完成的消息添加复制按钮
  1386. if (typeof window.setupCopyButtons === 'function') {
  1387. window.setupCopyButtons();
  1388. }
  1389. // 对话完成后刷新历史记录
  1390. if (typeof loadConversationHistory === 'function') {
  1391. // 添加延迟确保数据库保存完成
  1392. setTimeout(() => {
  1393. loadConversationHistory(true); // 自动选中最新的对话
  1394. }, 500);
  1395. }
  1396. // 如果是新对话,更新侧边栏选中状态
  1397. if (data.conversation_id && data.conversation_id !== conversationId) {
  1398. if (typeof updateConversationSelection === 'function') {
  1399. updateConversationSelection(data.conversation_id);
  1400. }
  1401. }
  1402. // 更新对话内容缓存
  1403. if (typeof updateConversationCache === 'function') {
  1404. updateConversationCache(conversationId, fullMessage, allThoughts);
  1405. }
  1406. return;
  1407. }
  1408. }
  1409. } catch (error) {
  1410. addErrorMessage('连接错误,请重试');
  1411. state.isStreaming = false;
  1412. updateConversationItemStatus(conversationId, 'stopped');
  1413. resetUIState();
  1414. }
  1415. }
  1416. // 修改处理标准响应函数
  1417. function handleStandardResponse (message, requestData) {
  1418. abortController = new AbortController();
  1419. fetch('/api/chat', {
  1420. method: 'POST',
  1421. headers: {
  1422. 'Content-Type': 'application/json'
  1423. },
  1424. body: JSON.stringify(requestData),
  1425. signal: abortController.signal
  1426. })
  1427. .then(response => response.json())
  1428. .then(data => {
  1429. if (data.success) {
  1430. addBotMessage(data.message, true, data.thoughts);
  1431. // 更新当前对话ID和session_id
  1432. if (data.conversation_id) {
  1433. window.currentConversationId = data.conversation_id;
  1434. }
  1435. if (data.session_id) {
  1436. window.currentSessionId = data.session_id;
  1437. }
  1438. // 对话完成后刷新历史记录
  1439. if (typeof loadConversationHistory === 'function') {
  1440. // 添加延迟确保数据库保存完成
  1441. setTimeout(() => {
  1442. loadConversationHistory(true); // 自动选中最新的对话
  1443. }, 500);
  1444. }
  1445. // 如果是新对话,更新侧边栏选中状态
  1446. if (data.conversation_id) {
  1447. if (typeof updateConversationSelection === 'function') {
  1448. updateConversationSelection(data.conversation_id);
  1449. }
  1450. }
  1451. } else {
  1452. if (data.error && data.error.includes('401')) {
  1453. addErrorMessage('登录已过期,正在重新连接...', true);
  1454. // 尝试刷新token
  1455. tryRefreshToken().then(refreshed => {
  1456. if (!refreshed) {
  1457. clearAuthAndRedirect();
  1458. }
  1459. });
  1460. } else {
  1461. addErrorMessage(data.error || '发生未知错误');
  1462. }
  1463. }
  1464. })
  1465. .catch(error => {
  1466. if (error.name === 'AbortError') {
  1467. addErrorMessage('请求已取消');
  1468. } else {
  1469. addErrorMessage('连接错误,请重试');
  1470. }
  1471. })
  1472. .finally(() => {
  1473. document.querySelectorAll('.message-content.typing').forEach(el => {
  1474. el.classList.remove('typing');
  1475. });
  1476. resetUIState();
  1477. });
  1478. }
  1479. // 修改停止请求函数
  1480. function stopRequest () {
  1481. isStopped = true; // 新增:设置停止标志
  1482. // 停止当前激活对话的流式响应
  1483. if (currentActiveConversationId) {
  1484. stopConversationStream(currentActiveConversationId);
  1485. }
  1486. if (eventSource) {
  1487. closeEventSource();
  1488. }
  1489. if (abortController) {
  1490. abortController.abort();
  1491. abortController = null;
  1492. }
  1493. // 重置为发送按钮
  1494. resetUIState();
  1495. // 重置消息元素引用
  1496. currentBotMessageElement = null;
  1497. currentBotMessageContainer = null;
  1498. }
  1499. // 关闭EventSource连接
  1500. function closeEventSource () {
  1501. if (eventSource) {
  1502. eventSource.close();
  1503. eventSource = null;
  1504. }
  1505. }
  1506. // 修改重置UI状态函数
  1507. function resetUIState () {
  1508. // 更新全局状态:检查是否有任何对话正在流式响应
  1509. isWaitingForResponse = isAnyConversationStreaming();
  1510. // 根据当前激活的对话状态来重置UI
  1511. if (currentActiveConversationId) {
  1512. updateInputUIForConversation(currentActiveConversationId);
  1513. } else {
  1514. // 如果没有激活的对话,恢复默认状态
  1515. sendButton.innerHTML = `
  1516. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  1517. <path d="M22 2L11 13M22 2L15 22L11 13M11 13L2 9L22 2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  1518. </svg>`;
  1519. sendButton.classList.remove('stopping');
  1520. // 恢复输入框状态
  1521. userInput.classList.remove('input-loading');
  1522. userInput.placeholder = '请输入需要撰写的品类名和要求...';
  1523. userInput.disabled = false;
  1524. }
  1525. // 重置消息元素引用
  1526. currentBotMessageElement = null;
  1527. currentBotMessageContainer = null;
  1528. // 如果有加载动画,移除它
  1529. if (currentLoadingElement) {
  1530. currentLoadingElement.remove();
  1531. currentLoadingElement = null;
  1532. }
  1533. }
  1534. // 重置对话
  1535. function resetConversation () {
  1536. // 如果正在确认,则执行重置
  1537. if (resetButton.classList.contains('confirming')) {
  1538. // 发送重置请求
  1539. fetch('/api/reset', {
  1540. method: 'POST',
  1541. headers: {
  1542. 'Content-Type': 'application/json'
  1543. },
  1544. body: JSON.stringify({ user_id: userId })
  1545. })
  1546. .then(response => response.json())
  1547. .then(data => {
  1548. if (data.success) {
  1549. // 清空聊天记录,仅保留欢迎消息
  1550. while (chatMessages.childNodes.length > 1) {
  1551. chatMessages.removeChild(chatMessages.lastChild);
  1552. }
  1553. // 清除当前对话ID
  1554. window.currentConversationId = null;
  1555. // 重置按钮状态
  1556. resetButton.classList.remove('confirming');
  1557. resetButton.textContent = '重置对话';
  1558. // 显示提示
  1559. addBotMessage('对话已重置,您可以开始新的对话了。');
  1560. } else {
  1561. addErrorMessage(data.error || '重置失败,请重试');
  1562. }
  1563. })
  1564. .catch(error => {
  1565. addErrorMessage('重置失败,请重试');
  1566. });
  1567. } else {
  1568. // 进入确认状态
  1569. resetButton.classList.add('confirming');
  1570. resetButton.textContent = '确认重置';
  1571. // 5秒后如果没有点击,恢复原状
  1572. setTimeout(() => {
  1573. if (resetButton.classList.contains('confirming')) {
  1574. resetButton.classList.remove('confirming');
  1575. resetButton.textContent = '重置对话';
  1576. }
  1577. }, 5000);
  1578. }
  1579. }
  1580. // 添加事件监听器
  1581. userInput.addEventListener('input', () => {
  1582. autoResizeTextarea();
  1583. updateCharCounter();
  1584. });
  1585. // 在输入框内按Enter发送消息(Shift+Enter换行),状态与发送按钮一致
  1586. userInput.addEventListener('keydown', (e) => {
  1587. if (e.key !== 'Enter') return;
  1588. if (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || e.isComposing) return;
  1589. e.preventDefault(); // 阻止默认换行
  1590. if (isAnyConversationStreaming()) {
  1591. stopRequest(); // 和按钮行为保持一致:正在流式时改为停止
  1592. return;
  1593. }
  1594. if (userInput.disabled) return;
  1595. sendMessage();
  1596. });
  1597. // 按下Escape键时取消请求
  1598. document.addEventListener('keydown', (e) => {
  1599. if (e.key === 'Escape' && isAnyConversationStreaming()) {
  1600. e.preventDefault();
  1601. stopRequest();
  1602. }
  1603. });
  1604. // 点击发送按钮
  1605. sendButton.addEventListener('click', () => {
  1606. if (isAnyConversationStreaming()) {
  1607. stopRequest();
  1608. } else {
  1609. sendMessage();
  1610. }
  1611. });
  1612. // 重置按钮点击事件
  1613. resetButton.addEventListener('click', resetConversation);
  1614. // 监听滚动事件
  1615. chatMessages.addEventListener('scroll', () => {
  1616. // 记录当前滚动位置
  1617. const currentScrollTop = chatMessages.scrollTop;
  1618. const maxScrollTop = chatMessages.scrollHeight - chatMessages.clientHeight;
  1619. if (currentScrollTop < lastScrollTop - 2) {
  1620. shouldAutoScroll = false;
  1621. } else if (maxScrollTop - currentScrollTop <= scrollThreshold) {
  1622. shouldAutoScroll = true;
  1623. }
  1624. lastScrollTop = currentScrollTop;
  1625. });
  1626. // 初始化调整文本区域高度
  1627. autoResizeTextarea();
  1628. // 聚焦到输入框
  1629. userInput.focus();
  1630. // 初始化字符计数器
  1631. updateCharCounter();
  1632. // 向输入框添加水波纹效果
  1633. function createRipple (event) {
  1634. const button = event.currentTarget;
  1635. // 如果按钮被禁用,则不创建水波纹
  1636. if (button.disabled) return;
  1637. const ripple = document.createElement('span');
  1638. ripple.classList.add('ripple');
  1639. button.appendChild(ripple);
  1640. const rect = button.getBoundingClientRect();
  1641. const size = Math.max(rect.width, rect.height);
  1642. const x = event.clientX - rect.left - size / 2;
  1643. const y = event.clientY - rect.top - size / 2;
  1644. ripple.style.width = ripple.style.height = `${size}px`;
  1645. ripple.style.left = `${x}px`;
  1646. ripple.style.top = `${y}px`;
  1647. // 动画结束后移除水波纹元素
  1648. setTimeout(() => {
  1649. ripple.remove();
  1650. }, 600);
  1651. }
  1652. // 添加水波纹效果
  1653. sendButton.addEventListener('click', createRipple);
  1654. resetButton.addEventListener('click', createRipple);
  1655. // 移除打字动画
  1656. function removeTypingAnimation () {
  1657. document.querySelectorAll('.message-content.typing').forEach(el => {
  1658. el.classList.remove('typing');
  1659. });
  1660. }
  1661. // 认证相关函数 - 增强版本
  1662. async function checkAuthStatusInChat () {
  1663. try {
  1664. const token = localStorage.getItem('auth_token');
  1665. const userInfo = localStorage.getItem('user_info');
  1666. if (!token || !userInfo) {
  1667. window.location.href = '/login';
  1668. return;
  1669. }
  1670. // 检查token是否即将过期(提前1小时检查)
  1671. if (isTokenExpiringSoon(token)) {
  1672. const refreshed = await tryRefreshToken();
  1673. if (!refreshed) {
  1674. clearAuthAndRedirect();
  1675. return;
  1676. }
  1677. }
  1678. // 显示本地用户信息
  1679. try {
  1680. const user = JSON.parse(userInfo);
  1681. displayUserInfo(user);
  1682. showUserSection();
  1683. addAuthHeader(token);
  1684. } catch (e) {
  1685. clearAuthAndRedirect();
  1686. }
  1687. } catch (error) {
  1688. clearAuthAndRedirect();
  1689. }
  1690. }
  1691. // 检查token是否即将过期
  1692. function isTokenExpiringSoon (token) {
  1693. try {
  1694. const payload = JSON.parse(atob(token.split('.')[1]));
  1695. const exp = payload.exp * 1000; // 转换为毫秒
  1696. const now = Date.now();
  1697. const oneHour = 60 * 60 * 1000; // 1小时
  1698. return (exp - now) < oneHour;
  1699. } catch (e) {
  1700. return true; // 解析失败,认为已过期
  1701. }
  1702. }
  1703. // 尝试刷新token
  1704. let isRefreshing = false; // 防止并发刷新
  1705. async function tryRefreshToken () {
  1706. // 如果正在刷新,直接返回false
  1707. if (isRefreshing) {
  1708. return false;
  1709. }
  1710. try {
  1711. isRefreshing = true;
  1712. const token = localStorage.getItem('auth_token');
  1713. if (!token) {
  1714. return false;
  1715. }
  1716. const response = await fetch('/api/auth/refresh', {
  1717. method: 'POST',
  1718. headers: {
  1719. 'Content-Type': 'application/json',
  1720. 'Authorization': `Bearer ${token}`
  1721. }
  1722. });
  1723. const data = await response.json();
  1724. if (response.ok && data.success && data.token) {
  1725. localStorage.setItem('auth_token', data.token);
  1726. return true;
  1727. } else {
  1728. // 如果是401错误或token过期相关错误,直接返回false
  1729. if (response.status === 401 ||
  1730. data.code === 'TOKEN_EXPIRED_NO_SESSION' ||
  1731. data.code === 'MISSING_TOKEN') {
  1732. return false;
  1733. }
  1734. return false;
  1735. }
  1736. } catch (error) {
  1737. return false;
  1738. } finally {
  1739. isRefreshing = false;
  1740. }
  1741. }
  1742. function clearAuthAndRedirect () {
  1743. if (isRedirecting) {
  1744. return;
  1745. }
  1746. isRedirecting = true;
  1747. // 清除本地存储
  1748. localStorage.removeItem('auth_token');
  1749. localStorage.removeItem('user_info');
  1750. // 清除session存储(如果有)
  1751. sessionStorage.removeItem('auth_token');
  1752. sessionStorage.removeItem('user_info');
  1753. // 立即跳转,不使用setTimeout
  1754. try {
  1755. window.location.replace('/login');
  1756. } catch (error) {
  1757. window.location.href = '/login';
  1758. }
  1759. }
  1760. function showUserSection () {
  1761. const userInfo = document.getElementById('user-info');
  1762. if (userInfo) userInfo.style.display = 'flex';
  1763. }
  1764. function addAuthHeader (token) {
  1765. // 为所有fetch请求添加认证头和错误处理
  1766. const originalFetch = window.fetch;
  1767. window.fetch = async function (url, options = {}) {
  1768. if (options.headers === undefined) {
  1769. options.headers = {};
  1770. }
  1771. options.headers['Authorization'] = `Bearer ${token}`;
  1772. try {
  1773. const response = await originalFetch(url, options);
  1774. // 检查401错误,但不要对refresh接口本身进行重试
  1775. if (response.status == 401) {
  1776. // 如果是refresh接口返回401,直接跳转登录,不要再次尝试刷新
  1777. const urlString = typeof url === 'string' ? url : url.toString();
  1778. if (urlString.includes('/api/auth/refresh')) {
  1779. clearAuthAndRedirect();
  1780. return response;
  1781. }
  1782. const refreshed = await tryRefreshToken();
  1783. if (refreshed) {
  1784. // 更新token后重试请求
  1785. options.headers['Authorization'] = `Bearer ${localStorage.getItem('auth_token')}`;
  1786. return originalFetch(url, options);
  1787. } else {
  1788. // 刷新失败,清除认证信息并跳转登录
  1789. clearAuthAndRedirect();
  1790. return response;
  1791. }
  1792. }
  1793. return response;
  1794. } catch (error) {
  1795. throw error;
  1796. }
  1797. };
  1798. }
  1799. // 将addAuthHeader函数暴露到全局作用域
  1800. window.addAuthHeader = addAuthHeader;
  1801. // 定期更新对话状态
  1802. function startConversationStatusUpdater () {
  1803. setInterval(() => {
  1804. updateAllConversationStatuses();
  1805. }, 2000); // 每2秒更新一次
  1806. }
  1807. function updateAllConversationStatuses () {
  1808. conversationStates.forEach((state, conversationId) => {
  1809. if (state.isStreaming) {
  1810. // 检查流式响应是否还在进行
  1811. const now = Date.now();
  1812. const timeSinceLastUpdate = now - state.lastUpdateTime;
  1813. // 如果超过30秒没有更新,认为流式响应已结束
  1814. if (timeSinceLastUpdate > 30000) {
  1815. state.isStreaming = false;
  1816. state.isPaused = false;
  1817. updateConversationItemStatus(conversationId, 'stopped');
  1818. }
  1819. }
  1820. });
  1821. }
  1822. // 将对话状态管理函数和变量暴露到全局作用域
  1823. window.conversationStates = conversationStates;
  1824. window.currentActiveConversationId = currentActiveConversationId;
  1825. window.setActiveConversation = setActiveConversation;
  1826. window.pauseConversationStream = pauseConversationStream;
  1827. window.resumeConversationStream = resumeConversationStream;
  1828. window.stopConversationStream = stopConversationStream;
  1829. window.initializeConversationState = initializeConversationState;
  1830. window.updateConversationItemStatus = updateConversationItemStatus;
  1831. window.startConversationStatusUpdater = startConversationStatusUpdater;
  1832. window.isAnyConversationStreaming = isAnyConversationStreaming;
  1833. window.getStreamingConversationId = getStreamingConversationId;
  1834. window.updateInputUIForConversation = updateInputUIForConversation;
  1835. window.renderMarkdown = renderMarkdown;
  1836. window.renderThoughts = renderThoughts;
  1837. function displayUserInfo (userInfo) {
  1838. const userInfoElement = document.getElementById('user-info');
  1839. const userNameElement = document.getElementById('user-name');
  1840. const userTypeElement = document.getElementById('user-type');
  1841. const userTitleElement = document.getElementById('user-title');
  1842. const avatarImg = document.getElementById('avatar-img');
  1843. const avatarFallback = document.getElementById('avatar-fallback');
  1844. const userDropdown = document.getElementById('user-dropdown');
  1845. if (!userInfoElement || !userNameElement) return;
  1846. // 显示用户名
  1847. userNameElement.textContent = userInfo.nickname || userInfo.name || '用户';
  1848. // 显示用户类型
  1849. if (userTypeElement) {
  1850. const typeMap = {
  1851. 'dingtalk': '钉钉用户',
  1852. 'wecom': '企业微信用户'
  1853. };
  1854. userTypeElement.textContent = typeMap[userInfo.login_type] || '用户';
  1855. }
  1856. // 显示用户职位
  1857. if (userTitleElement && userInfo.title) {
  1858. userTitleElement.textContent = userInfo.title;
  1859. userTitleElement.style.display = 'block';
  1860. }
  1861. // 显示用户头像
  1862. if (avatarImg && avatarFallback) {
  1863. if (userInfo.avatar) {
  1864. avatarImg.src = userInfo.avatar;
  1865. avatarImg.style.display = 'block';
  1866. avatarFallback.style.display = 'none';
  1867. // 添加头像加载失败处理
  1868. avatarImg.onerror = function () {
  1869. this.style.display = 'none';
  1870. avatarFallback.style.display = 'flex';
  1871. const firstChar = (userInfo.name || 'U').charAt(0).toUpperCase();
  1872. avatarFallback.textContent = firstChar;
  1873. };
  1874. } else {
  1875. avatarImg.style.display = 'none';
  1876. avatarFallback.style.display = 'flex';
  1877. const firstChar = (userInfo.name || 'U').charAt(0).toUpperCase();
  1878. avatarFallback.textContent = firstChar;
  1879. }
  1880. }
  1881. // 显示用户详细信息下拉框
  1882. if (userDropdown) {
  1883. displayUserDetails(userInfo);
  1884. }
  1885. userInfoElement.style.display = 'flex';
  1886. }
  1887. function displayUserDetails (userInfo) {
  1888. // 显示邮箱信息
  1889. const emailElement = document.getElementById('user-email');
  1890. if (emailElement && userInfo.email) {
  1891. emailElement.querySelector('.info-value').textContent = userInfo.email;
  1892. emailElement.style.display = 'flex';
  1893. }
  1894. // 显示手机信息
  1895. const mobileElement = document.getElementById('user-mobile');
  1896. if (mobileElement && userInfo.mobile) {
  1897. mobileElement.querySelector('.info-value').textContent = userInfo.mobile;
  1898. mobileElement.style.display = 'flex';
  1899. }
  1900. // 显示工号信息
  1901. const jobElement = document.getElementById('user-job');
  1902. if (jobElement && userInfo.job_number) {
  1903. jobElement.querySelector('.info-value').textContent = userInfo.job_number;
  1904. jobElement.style.display = 'flex';
  1905. }
  1906. // 显示部门信息
  1907. const deptElement = document.getElementById('user-dept');
  1908. if (deptElement && userInfo.dept_name) {
  1909. deptElement.querySelector('.info-value').textContent = userInfo.dept_name;
  1910. deptElement.style.display = 'flex';
  1911. }
  1912. // 如果有任何详细信息,显示下拉框
  1913. const userDropdown = document.getElementById('user-dropdown');
  1914. if (userDropdown && (userInfo.email || userInfo.mobile || userInfo.job_number || userInfo.dept_name)) {
  1915. userDropdown.style.display = 'block';
  1916. }
  1917. }
  1918. async function handleLogout () {
  1919. try {
  1920. const token = localStorage.getItem('auth_token');
  1921. // 调用退出登录API
  1922. const response = await fetch('/api/auth/logout', {
  1923. method: 'POST',
  1924. headers: {
  1925. 'Authorization': `Bearer ${token}`
  1926. }
  1927. });
  1928. // 清除本地存储
  1929. localStorage.removeItem('auth_token');
  1930. localStorage.removeItem('user_info');
  1931. // 跳转到登录页
  1932. window.location.href = '/login';
  1933. } catch (error) {
  1934. // 即使API调用失败,也清除本地存储并跳转
  1935. localStorage.removeItem('auth_token');
  1936. localStorage.removeItem('user_info');
  1937. window.location.href = '/login';
  1938. }
  1939. }
  1940. });