2
0

index.html 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>MCP 助手</title>
  7. <script src="https://cdn.tailwindcss.com"></script>
  8. <style>
  9. .chat-container {
  10. height: calc(100vh - 200px);
  11. }
  12. /* 移动端优化 */
  13. @media (max-width: 768px) {
  14. .chat-container {
  15. height: calc(100vh - 180px);
  16. }
  17. /* 头部固定 */
  18. header {
  19. position: sticky;
  20. top: 0;
  21. z-index: 50;
  22. }
  23. /* 消息气泡宽度 */
  24. .message-bubble {
  25. max-width: 85vw !important;
  26. }
  27. /* 输入区域固定 */
  28. .input-area {
  29. position: sticky;
  30. bottom: 0;
  31. z-index: 50;
  32. background: white;
  33. border-top-left-radius: 0;
  34. border-top-right-radius: 0;
  35. }
  36. }
  37. /* 参数/结果可折叠区域 */
  38. .collapsible-section {
  39. margin-top: 6px;
  40. }
  41. .collapsible-header {
  42. display: flex;
  43. align-items: center;
  44. gap: 4px;
  45. padding: 4px 8px;
  46. background: rgba(255, 255, 255, 0.05);
  47. border-radius: 4px;
  48. cursor: pointer;
  49. font-size: 11px;
  50. color: #9ca3af;
  51. user-select: none;
  52. }
  53. .collapsible-header:hover {
  54. background: rgba(255, 255, 255, 0.08);
  55. }
  56. .collapsible-content {
  57. max-height: 0;
  58. overflow: hidden;
  59. transition: max-height 0.3s ease-out;
  60. }
  61. .collapsible-content.expanded {
  62. max-height: 300px;
  63. overflow-y: auto;
  64. }
  65. .collapsible-icon {
  66. transition: transform 0.3s;
  67. font-size: 10px;
  68. }
  69. .collapsible-icon.expanded {
  70. transform: rotate(90deg);
  71. }
  72. /* MCP 服务器横向滚动 */
  73. .mcp-servers-scroll {
  74. display: flex;
  75. gap: 8px;
  76. overflow-x: auto;
  77. padding: 4px 0;
  78. scrollbar-width: thin;
  79. -webkit-overflow-scrolling: touch;
  80. }
  81. .mcp-servers-scroll::-webkit-scrollbar {
  82. height: 4px;
  83. }
  84. .mcp-servers-scroll::-webkit-scrollbar-thumb {
  85. background: rgba(0, 0, 0, 0.2);
  86. border-radius: 2px;
  87. }
  88. .mcp-server-tag {
  89. flex-shrink: 0;
  90. display: flex;
  91. align-items: center;
  92. gap: 6px;
  93. padding: 8px 12px;
  94. border-radius: 8px;
  95. font-size: 12px;
  96. white-space: nowrap;
  97. }
  98. .mcp-server-tag.enabled {
  99. background: #d1fae5;
  100. color: #065f46;
  101. }
  102. .mcp-server-tag.disabled {
  103. background: #f3f4f6;
  104. color: #6b7280;
  105. }
  106. .mcp-status-dot {
  107. width: 8px;
  108. height: 8px;
  109. border-radius: 50%;
  110. }
  111. .mcp-status-dot.online {
  112. background: #10b981;
  113. }
  114. .mcp-status-dot.offline {
  115. background: #9ca3af;
  116. }
  117. .message-user {
  118. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  119. }
  120. .message-assistant {
  121. background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  122. }
  123. .typing-indicator span {
  124. animation: bounce 1.4s infinite ease-in-out both;
  125. }
  126. .typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
  127. .typing-indicator span:nth-child(2) { animation-delay: -0.16s; }
  128. @keyframes bounce {
  129. 0%, 80%, 100% { transform: scale(0); }
  130. 40% { transform: scale(1); }
  131. }
  132. /* 工具调用面板样式 */
  133. .tool-call-panel {
  134. background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  135. border-radius: 8px;
  136. margin: 12px 0;
  137. overflow: hidden;
  138. border: 1px solid #3a3a5a;
  139. }
  140. .tool-panel-header {
  141. background: rgba(255, 255, 255, 0.05);
  142. padding: 10px 14px;
  143. cursor: pointer;
  144. display: flex;
  145. align-items: center;
  146. justify-content: space-between;
  147. transition: background 0.2s;
  148. }
  149. .tool-panel-header:hover {
  150. background: rgba(255, 255, 255, 0.08);
  151. }
  152. .tool-panel-title {
  153. display: flex;
  154. align-items: center;
  155. gap: 8px;
  156. color: #e0e0e0;
  157. font-size: 13px;
  158. font-weight: 500;
  159. }
  160. .tool-panel-content {
  161. padding: 0;
  162. max-height: 0;
  163. overflow: hidden;
  164. transition: max-height 0.3s ease-out, padding 0.3s ease-out;
  165. }
  166. .tool-panel-content.collapsed {
  167. max-height: 0;
  168. }
  169. .tool-panel-content.expanded {
  170. max-height: 800px;
  171. padding: 12px;
  172. overflow-y: auto;
  173. }
  174. .tool-panel-content::-webkit-scrollbar {
  175. width: 6px;
  176. }
  177. .tool-panel-content::-webkit-scrollbar-track {
  178. background: rgba(255, 255, 255, 0.05);
  179. }
  180. .tool-panel-content::-webkit-scrollbar-thumb {
  181. background: rgba(255, 255, 255, 0.2);
  182. border-radius: 3px;
  183. }
  184. /* 工具调用项样式 */
  185. .tool-call-item {
  186. background: rgba(255, 255, 255, 0.03);
  187. border-radius: 6px;
  188. padding: 10px 12px;
  189. margin-bottom: 8px;
  190. border-left: 3px solid #555;
  191. transition: all 0.2s;
  192. }
  193. .tool-call-item:last-child {
  194. margin-bottom: 0;
  195. }
  196. .tool-call-item.pending {
  197. border-left-color: #f59e0b;
  198. animation: pulse-border 1.5s infinite;
  199. }
  200. .tool-call-item.success {
  201. border-left-color: #10b981;
  202. }
  203. .tool-call-item.error {
  204. border-left-color: #ef4444;
  205. }
  206. @keyframes pulse-border {
  207. 0%, 100% { border-left-color: #f59e0b; }
  208. 50% { border-left-color: #fbbf24; }
  209. }
  210. .tool-call-header {
  211. display: flex;
  212. align-items: center;
  213. justify-content: space-between;
  214. margin-bottom: 6px;
  215. }
  216. .tool-name {
  217. color: #e0e0e0;
  218. font-size: 13px;
  219. font-weight: 500;
  220. display: flex;
  221. align-items: center;
  222. gap: 6px;
  223. }
  224. .tool-status {
  225. font-size: 11px;
  226. padding: 2px 8px;
  227. border-radius: 10px;
  228. font-weight: 500;
  229. }
  230. .tool-status.pending {
  231. background: rgba(245, 158, 11, 0.2);
  232. color: #fbbf24;
  233. }
  234. .tool-status.success {
  235. background: rgba(16, 185, 129, 0.2);
  236. color: #34d399;
  237. }
  238. .tool-status.error {
  239. background: rgba(239, 68, 68, 0.2);
  240. color: #f87171;
  241. }
  242. .tool-params {
  243. background: rgba(0, 0, 0, 0.3);
  244. border-radius: 4px;
  245. padding: 8px;
  246. margin-top: 6px;
  247. font-size: 11px;
  248. color: #9ca3af;
  249. overflow-x: auto;
  250. }
  251. .tool-params::-webkit-scrollbar {
  252. height: 4px;
  253. }
  254. .tool-params::-webkit-scrollbar-thumb {
  255. background: rgba(255, 255, 255, 0.2);
  256. border-radius: 2px;
  257. }
  258. .tool-result {
  259. background: rgba(16, 185, 129, 0.1);
  260. border-radius: 4px;
  261. padding: 8px;
  262. margin-top: 6px;
  263. font-size: 11px;
  264. color: #6ee7b7;
  265. }
  266. .tool-result.error {
  267. background: rgba(239, 68, 68, 0.1);
  268. color: #fca5a5;
  269. }
  270. .tool-result-content {
  271. max-height: 100px;
  272. overflow-y: auto;
  273. word-break: break-all;
  274. }
  275. .tool-result-content::-webkit-scrollbar {
  276. width: 4px;
  277. }
  278. .tool-result-content::-webkit-scrollbar-thumb {
  279. background: rgba(255, 255, 255, 0.2);
  280. border-radius: 2px;
  281. }
  282. .expand-icon {
  283. transition: transform 0.3s;
  284. }
  285. .expand-icon.expanded {
  286. transform: rotate(180deg);
  287. }
  288. /* 加载动画 */
  289. .spinner {
  290. width: 14px;
  291. height: 14px;
  292. border: 2px solid rgba(251, 191, 36, 0.3);
  293. border-top-color: #fbbf24;
  294. border-radius: 50%;
  295. animation: spin 0.8s linear infinite;
  296. }
  297. @keyframes spin {
  298. to { transform: rotate(360deg); }
  299. }
  300. /* 状态指示器 */
  301. .process-indicator {
  302. display: flex;
  303. align-items: center;
  304. gap: 6px;
  305. padding: 6px 10px;
  306. background: rgba(245, 158, 11, 0.1);
  307. border-radius: 6px;
  308. font-size: 12px;
  309. color: #fbbf24;
  310. }
  311. .process-indicator.success {
  312. background: rgba(16, 185, 129, 0.1);
  313. color: #34d399;
  314. }
  315. .process-indicator .spinner {
  316. width: 12px;
  317. height: 12px;
  318. }
  319. pre {
  320. background: #1e1e1e;
  321. color: #d4d4d4;
  322. padding: 1rem;
  323. border-radius: 0.5rem;
  324. overflow-x: auto;
  325. }
  326. code {
  327. font-family: 'Courier New', monospace;
  328. }
  329. </style>
  330. </head>
  331. <body class="bg-gray-100 min-h-screen">
  332. <div class="container mx-auto px-4 py-6 max-w-4xl">
  333. <!-- Header -->
  334. <header class="bg-white rounded-lg shadow-md p-4 mb-4">
  335. <div class="flex items-center justify-between">
  336. <div class="flex items-center space-x-3">
  337. <div class="w-10 h-10 bg-gradient-to-br from-purple-500 to-indigo-600 rounded-lg flex items-center justify-center">
  338. <span class="text-white font-bold">AI</span>
  339. </div>
  340. <div>
  341. <h1 class="text-xl font-bold text-gray-800">AI MCP Web UI</h1>
  342. <p class="text-sm text-gray-500">通用 MCP 服务器 Web 界面</p>
  343. </div>
  344. </div>
  345. <div id="status-indicator" class="flex items-center space-x-2">
  346. <span class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
  347. <span class="text-sm text-gray-600">已连接</span>
  348. </div>
  349. </div>
  350. </header>
  351. <!-- Chat Container -->
  352. <div class="bg-white rounded-lg shadow-md">
  353. <!-- Messages -->
  354. <div id="chat-messages" class="chat-container overflow-y-auto p-4 space-y-4">
  355. <!-- Welcome Message -->
  356. <div class="flex justify-start">
  357. <div class="message-assistant message-bubble rounded-lg p-4 max-w-[80%] shadow-sm">
  358. <p class="text-gray-800">你好!我是 AI MCP Web UI 助手。我可以帮助你:</p>
  359. <ul class="mt-2 text-gray-700 list-disc list-inside">
  360. <li>与 Claude AI 进行对话</li>
  361. <li>调用 MCP 服务器工具</li>
  362. <li>自动化各种任务</li>
  363. </ul>
  364. <p class="mt-2 text-gray-600 text-sm">请问有什么可以帮助你的?</p>
  365. </div>
  366. </div>
  367. </div>
  368. <!-- Input Area -->
  369. <div class="border-t border-gray-200 p-4 input-area">
  370. <form id="chat-form" class="flex space-x-3">
  371. <input
  372. type="text"
  373. id="user-input"
  374. placeholder="输入你的消息..."
  375. class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
  376. style="font-size: 16px;"
  377. autocomplete="off"
  378. >
  379. <button
  380. type="submit"
  381. id="send-button"
  382. class="px-6 py-3 bg-gradient-to-r from-purple-500 to-indigo-600 text-white rounded-lg hover:from-purple-600 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
  383. style="font-size: 16px;"
  384. >
  385. 发送
  386. </button>
  387. </form>
  388. </div>
  389. </div>
  390. <!-- MCP Servers Status -->
  391. <div class="mt-4 bg-white rounded-lg shadow-md p-4">
  392. <h2 class="text-sm font-semibold text-gray-800 mb-2">MCP 服务器</h2>
  393. <div id="mcp-servers" class="mcp-servers-scroll">
  394. <!-- MCP server tags will be inserted here -->
  395. </div>
  396. </div>
  397. </div>
  398. <script>
  399. // State
  400. let conversationHistory = [];
  401. let isTyping = false;
  402. // DOM Elements
  403. const chatMessages = document.getElementById('chat-messages');
  404. const chatForm = document.getElementById('chat-form');
  405. const userInput = document.getElementById('user-input');
  406. const sendButton = document.getElementById('send-button');
  407. const mcpServers = document.getElementById('mcp-servers');
  408. const statusIndicator = document.getElementById('status-indicator');
  409. // API Base URL
  410. const API_BASE = window.location.origin;
  411. // Format message content (handle code blocks, etc.)
  412. function formatMessage(content) {
  413. // Simple markdown-like formatting
  414. let formatted = content
  415. .replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
  416. .replace(/`([^`]+)`/g, '<code class="bg-gray-200 px-1 rounded">$1</code>')
  417. .replace(/\n/g, '<br>');
  418. return formatted;
  419. }
  420. // Add message to chat
  421. function addMessage(role, content) {
  422. const messageDiv = document.createElement('div');
  423. messageDiv.className = `flex ${role === 'user' ? 'justify-end' : 'justify-start'}`;
  424. const bubbleClass = role === 'user' ? 'message-user text-white' : 'message-assistant text-gray-800';
  425. messageDiv.innerHTML = `
  426. <div class="${bubbleClass} message-bubble rounded-lg p-4 max-w-[80%] shadow-sm">
  427. <div>${formatMessage(content)}</div>
  428. </div>
  429. `;
  430. chatMessages.appendChild(messageDiv);
  431. chatMessages.scrollTop = chatMessages.scrollHeight;
  432. }
  433. // Add typing indicator
  434. function addTypingIndicator() {
  435. const typingDiv = document.createElement('div');
  436. typingDiv.id = 'typing-indicator';
  437. typingDiv.className = 'flex justify-start';
  438. typingDiv.innerHTML = `
  439. <div class="message-assistant rounded-lg p-4 shadow-sm">
  440. <div class="typing-indicator flex space-x-1">
  441. <span class="w-2 h-2 bg-gray-500 rounded-full"></span>
  442. <span class="w-2 h-2 bg-gray-500 rounded-full"></span>
  443. <span class="w-2 h-2 bg-gray-500 rounded-full"></span>
  444. </div>
  445. </div>
  446. `;
  447. chatMessages.appendChild(typingDiv);
  448. chatMessages.scrollTop = chatMessages.scrollHeight;
  449. }
  450. // Remove typing indicator
  451. function removeTypingIndicator() {
  452. const indicator = document.getElementById('typing-indicator');
  453. if (indicator) indicator.remove();
  454. }
  455. // 创建工具调用面板
  456. function createToolCallPanel() {
  457. const panel = document.createElement('div');
  458. panel.className = 'tool-call-panel';
  459. panel.innerHTML = `
  460. <div class="tool-panel-header" onclick="toggleToolPanel(this)">
  461. <div class="tool-panel-title">
  462. <span class="expand-icon">▶</span>
  463. <span>🔧 工具调用</span>
  464. <span class="tool-count">(0)</span>
  465. </div>
  466. <div class="process-indicator">
  467. <div class="spinner"></div>
  468. <span>处理中...</span>
  469. </div>
  470. </div>
  471. <div class="tool-panel-content">
  472. <div class="tool-calls-container"></div>
  473. </div>
  474. `;
  475. return panel;
  476. }
  477. // 切换工具面板展开/收起
  478. function toggleToolPanel(header) {
  479. const content = header.nextElementSibling;
  480. const icon = header.querySelector('.expand-icon');
  481. content.classList.toggle('expanded');
  482. icon.classList.toggle('expanded');
  483. }
  484. // 切换参数/结果折叠区域
  485. function toggleCollapsible(header) {
  486. const content = header.nextElementSibling;
  487. const icon = header.querySelector('.collapsible-icon');
  488. content.classList.toggle('expanded');
  489. icon.classList.toggle('expanded');
  490. }
  491. // 添加工具调用项
  492. function addToolCallItem(container, toolName, params, toolUseId = null) {
  493. const item = document.createElement('div');
  494. item.className = 'tool-call-item pending';
  495. const uniqueId = `tool-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  496. item.id = uniqueId;
  497. // 存储 tool_use_id 和 tool_name 以便后续匹配
  498. if (toolUseId) {
  499. item.dataset.toolUseId = toolUseId;
  500. }
  501. item.dataset.toolName = toolName;
  502. console.log('[addToolCallItem] Created item:', { id: uniqueId, toolName, toolUseId });
  503. // 简化工具名称显示 - 去掉 mcp__ 前缀和下划线
  504. let displayName = toolName;
  505. if (toolName.startsWith('mcp__')) {
  506. displayName = toolName.replace('mcp__', '').replace(/_/g, ' ');
  507. }
  508. // 首字母大写
  509. displayName = displayName.charAt(0).toUpperCase() + displayName.slice(1);
  510. const paramsStr = params ? JSON.stringify(params, null, 2) : '{}';
  511. const hasParams = params && Object.keys(params).length > 0;
  512. item.innerHTML = `
  513. <div class="tool-call-header">
  514. <div class="tool-name">
  515. <span>🔧</span>
  516. <span>${escapeHtml(displayName)}</span>
  517. </div>
  518. <div class="tool-status pending">
  519. <div class="spinner"></div>
  520. <span>执行中</span>
  521. </div>
  522. </div>
  523. ${hasParams ? `
  524. <div class="collapsible-section">
  525. <div class="collapsible-header" onclick="toggleCollapsible(this)">
  526. <span class="collapsible-icon">▶</span>
  527. <span>查看参数</span>
  528. </div>
  529. <div class="collapsible-content">
  530. <div class="tool-params"><pre style="margin:0;padding:0;background:transparent;font-size:10px;">${escapeHtml(paramsStr)}</pre></div>
  531. </div>
  532. </div>
  533. ` : ''}
  534. `;
  535. container.appendChild(item);
  536. return { id: uniqueId, toolUseId: toolUseId, toolName: toolName };
  537. }
  538. // 更新工具调用状态
  539. function updateToolCallStatus(itemId, status, result = null) {
  540. const item = document.getElementById(itemId);
  541. if (!item) {
  542. console.warn('[updateToolCallStatus] Item not found:', itemId);
  543. return;
  544. }
  545. const statusEl = item.querySelector('.tool-status');
  546. item.classList.remove('pending', 'success', 'error');
  547. if (status === 'success') {
  548. item.classList.add('success');
  549. statusEl.className = 'tool-status success';
  550. statusEl.innerHTML = '✅ 完成';
  551. // 总是显示结果区域(即使结果为空)
  552. const resultText = result ? (typeof result === 'string' ? result : JSON.stringify(result, null, 2)) : '';
  553. const displayResult = resultText || '(无返回结果)';
  554. const truncatedResult = displayResult.substring(0, 1000) + (displayResult.length > 1000 ? '...' : '');
  555. const resultDiv = document.createElement('div');
  556. resultDiv.className = 'collapsible-section';
  557. resultDiv.innerHTML = `
  558. <div class="collapsible-header" onclick="toggleCollapsible(this)">
  559. <span class="collapsible-icon">▶</span>
  560. <span>查看结果</span>
  561. </div>
  562. <div class="collapsible-content">
  563. <div class="tool-result"><div class="tool-result-content">${escapeHtml(truncatedResult)}</div></div>
  564. </div>
  565. `;
  566. item.appendChild(resultDiv);
  567. } else if (status === 'error') {
  568. item.classList.add('error');
  569. statusEl.className = 'tool-status error';
  570. statusEl.innerHTML = '❌ 失败';
  571. const errorDiv = document.createElement('div');
  572. errorDiv.className = 'collapsible-section';
  573. errorDiv.innerHTML = `
  574. <div class="collapsible-header" onclick="toggleCollapsible(this)">
  575. <span class="collapsible-icon">▶</span>
  576. <span>查看错误</span>
  577. </div>
  578. <div class="collapsible-content expanded">
  579. <div class="tool-result error">${escapeHtml(result || '未知错误')}</div>
  580. </div>
  581. `;
  582. item.appendChild(errorDiv);
  583. }
  584. }
  585. // 更新工具面板状态
  586. function updateToolPanelStatus(panel, status, totalCalls = 0) {
  587. const indicator = panel.querySelector('.process-indicator');
  588. const countEl = panel.querySelector('.tool-count');
  589. const content = panel.querySelector('.tool-panel-content');
  590. const icon = panel.querySelector('.expand-icon');
  591. countEl.textContent = `(${totalCalls})`;
  592. if (status === 'running') {
  593. // 保持处理中状态,不改变
  594. indicator.className = 'process-indicator';
  595. indicator.innerHTML = `<div class="spinner"></div><span>处理中...</span>`;
  596. } else if (status === 'complete') {
  597. indicator.className = 'process-indicator success';
  598. indicator.innerHTML = `<span>✅ 完成 - ${totalCalls} 个工具调用</span>`;
  599. // 自动展开面板以便查看结果
  600. if (content && !content.classList.contains('expanded')) {
  601. content.classList.add('expanded');
  602. if (icon) icon.classList.add('expanded');
  603. }
  604. } else if (status === 'error') {
  605. indicator.className = 'process-indicator';
  606. indicator.style.background = 'rgba(239, 68, 68, 0.1)';
  607. indicator.style.color = '#f87171';
  608. indicator.innerHTML = `<span>❌ 部分失败</span>`;
  609. }
  610. }
  611. // HTML 转义
  612. function escapeHtml(text) {
  613. const div = document.createElement('div');
  614. div.textContent = text;
  615. return div.innerHTML;
  616. }
  617. function scrollToBottom() {
  618. chatMessages.scrollTop = chatMessages.scrollHeight;
  619. }
  620. // ========== 流式聊天功能 ==========
  621. async function chatStream(message, onEvent) {
  622. const events = [];
  623. try {
  624. const response = await fetch('/api/chat/stream', {
  625. method: 'POST',
  626. headers: { 'Content-Type': 'application/json' },
  627. body: JSON.stringify({ message, history: conversationHistory })
  628. });
  629. if (!response.ok) {
  630. throw new Error(`HTTP error! status: ${response.status}`);
  631. }
  632. const reader = response.body.getReader();
  633. const decoder = new TextDecoder();
  634. let buffer = '';
  635. while (true) {
  636. const { done, value } = await reader.read();
  637. if (done) break;
  638. buffer += decoder.decode(value, { stream: true });
  639. // 处理 SSE 格式: "event: xxx\ndata: {...}\n\n"
  640. const lines = buffer.split('\n');
  641. buffer = lines.pop() || ''; // 保留未完成的行
  642. for (let i = 0; i < lines.length; i++) {
  643. const line = lines[i].trim();
  644. if (!line) continue;
  645. if (line.startsWith('event:')) {
  646. const eventType = line.substring(6).trim();
  647. events.push({ type: eventType, data: null });
  648. } else if (line.startsWith('data:')) {
  649. const data = line.substring(5).trim();
  650. if (events.length > 0) {
  651. events[events.length - 1].data = data;
  652. }
  653. }
  654. // 处理完整的事件
  655. while (events.length > 0 && events[0].data) {
  656. const event = events.shift();
  657. try {
  658. const data = JSON.parse(event.data);
  659. onEvent(event.type, data);
  660. } catch (e) {
  661. console.error('Parse error:', e, event.data);
  662. }
  663. }
  664. }
  665. }
  666. } catch (error) {
  667. onEvent('error', { error: error.message });
  668. }
  669. }
  670. async function sendMessageStream(message) {
  671. if (isTyping) return;
  672. isTyping = true;
  673. sendButton.disabled = true;
  674. // 添加用户消息
  675. addMessage('user', message);
  676. conversationHistory.push({ role: 'user', content: message });
  677. // 创建助手消息容器
  678. const assistantMsgDiv = document.createElement('div');
  679. assistantMsgDiv.className = 'flex justify-start';
  680. assistantMsgDiv.innerHTML = `
  681. <div class="message-assistant message-bubble rounded-lg p-4 shadow-sm">
  682. <div class="response-content">
  683. <div class="text" id="currentResponse"></div>
  684. </div>
  685. <div id="toolCallContainer"></div>
  686. </div>
  687. `;
  688. chatMessages.appendChild(assistantMsgDiv);
  689. const responseDiv = assistantMsgDiv.querySelector('#currentResponse');
  690. const toolContainer = assistantMsgDiv.querySelector('#toolCallContainer');
  691. let currentText = '';
  692. let toolCallsCount = 0;
  693. let toolCallItems = []; // 改为数组存储,按索引匹配
  694. let finalResponse = '';
  695. let toolCallPanel = null;
  696. let toolCallsContainer = null;
  697. await chatStream(message, (eventType, data) => {
  698. switch (eventType) {
  699. case 'start':
  700. responseDiv.innerHTML = '<span style="color: #888; font-style: italic;">🤔 AI 正在思考...</span>';
  701. break;
  702. case 'token':
  703. // 移除思考提示
  704. if (currentText === '') {
  705. responseDiv.innerHTML = '';
  706. }
  707. currentText += data.text || '';
  708. responseDiv.innerHTML = formatMessage(currentText);
  709. scrollToBottom();
  710. break;
  711. case 'tool_call':
  712. // 首次工具调用时创建面板
  713. if (!toolCallPanel) {
  714. toolCallPanel = createToolCallPanel();
  715. toolContainer.appendChild(toolCallPanel);
  716. toolCallsContainer = toolCallPanel.querySelector('.tool-calls-container');
  717. // 清空思考提示
  718. if (currentText === '' || currentText.includes('正在思考')) {
  719. responseDiv.innerHTML = '<span style="color: #888; font-style: italic;">🔧 正在调用工具...</span>';
  720. }
  721. }
  722. // 添加工具调用项
  723. const toolName = data.tool || 'unknown';
  724. const params = data.args || data.params || null;
  725. const toolUseId = data.tool_id || null;
  726. console.log('[tool_call] Adding tool:', { toolName, toolUseId, params });
  727. const itemInfo = addToolCallItem(toolCallsContainer, toolName, params, toolUseId);
  728. toolCallItems.push(itemInfo);
  729. toolCallsCount++;
  730. console.log('[tool_call] Current toolCallItems:', toolCallItems);
  731. updateToolPanelStatus(toolCallPanel, 'running', toolCallsCount);
  732. scrollToBottom();
  733. break;
  734. case 'tools_start':
  735. // 批量工具开始
  736. if (!toolCallPanel) {
  737. toolCallPanel = createToolCallPanel();
  738. toolContainer.appendChild(toolCallPanel);
  739. toolCallsContainer = toolCallPanel.querySelector('.tool-calls-container');
  740. }
  741. if (currentText === '' || currentText.includes('正在思考')) {
  742. responseDiv.innerHTML = '<span style="color: #888; font-style: italic;">🔧 正在调用工具...</span>';
  743. }
  744. scrollToBottom();
  745. break;
  746. case 'tool_done':
  747. // 工具执行完成 - 按 tool_use_id 或 tool_name 匹配
  748. const doneToolUseId = data.tool_id;
  749. const doneToolName = data.tool;
  750. const doneResult = data.result;
  751. console.log('[tool_done] Looking for tool:', { tool_id: doneToolUseId, tool: doneToolName });
  752. console.log('[tool_done] Current toolCallItems:', toolCallItems);
  753. // 查找匹配的工具调用项
  754. const doneItem = toolCallItems.find(item =>
  755. item.toolUseId === doneToolUseId || item.toolName === doneToolName
  756. );
  757. if (doneItem) {
  758. console.log('[tool_done] Found item, updating status:', doneItem.id);
  759. updateToolCallStatus(doneItem.id, 'success', doneResult);
  760. } else {
  761. console.warn('[tool_done] Tool item not found for:', { tool_id: doneToolUseId, tool: doneToolName });
  762. // 如果找不到匹配项,尝试通过 DOM 查找
  763. const fallbackItem = Array.from(document.querySelectorAll('.tool-call-item')).find(el => {
  764. return el.dataset.toolUseId === doneToolUseId || el.dataset.toolName === doneToolName;
  765. });
  766. if (fallbackItem) {
  767. console.log('[tool_done] Found via DOM fallback:', fallbackItem.id);
  768. updateToolCallStatus(fallbackItem.id, 'success', doneResult);
  769. }
  770. }
  771. scrollToBottom();
  772. break;
  773. case 'tool_error':
  774. // 工具执行错误 - 按 tool_use_id 或 tool_name 匹配
  775. const errorToolUseId = data.tool_id;
  776. const errorToolName = data.tool;
  777. const errorItem = toolCallItems.find(item =>
  778. item.toolUseId === errorToolUseId || item.toolName === errorToolName
  779. );
  780. if (errorItem) {
  781. updateToolCallStatus(errorItem.id, 'error', data.error);
  782. }
  783. if (toolCallPanel) {
  784. updateToolPanelStatus(toolCallPanel, 'error', toolCallsCount);
  785. }
  786. scrollToBottom();
  787. break;
  788. case 'complete':
  789. // 完成
  790. console.log('[complete] Tool calls finished, updating panel status');
  791. if (toolCallPanel) {
  792. updateToolPanelStatus(toolCallPanel, 'complete', toolCallsCount);
  793. }
  794. // 清空临时提示并显示最终响应
  795. if (data.response || currentText) {
  796. finalResponse = data.response || currentText;
  797. responseDiv.innerHTML = formatMessage(finalResponse);
  798. }
  799. conversationHistory.push({ role: 'assistant', content: finalResponse });
  800. scrollToBottom();
  801. break;
  802. case 'error':
  803. responseDiv.innerHTML = `<span style="color: #ef4444;">❌ 错误: ${escapeHtml(data.error || '未知错误')}</span>`;
  804. if (toolCallPanel) {
  805. updateToolPanelStatus(toolCallPanel, 'error', toolCallsCount);
  806. }
  807. scrollToBottom();
  808. break;
  809. }
  810. });
  811. // 重置状态
  812. isTyping = false;
  813. sendButton.disabled = false;
  814. userInput.focus();
  815. }
  816. // Load MCP servers
  817. async function loadMCPServers() {
  818. try {
  819. const response = await fetch(`${API_BASE}/api/mcp/servers`);
  820. const data = await response.json();
  821. mcpServers.innerHTML = data.servers.map(server => `
  822. <div class="mcp-server-tag ${server.enabled ? 'enabled' : 'disabled'}">
  823. <span class="mcp-status-dot ${server.enabled ? 'online' : 'offline'}"></span>
  824. <span class="font-medium">${server.name}</span>
  825. ${server.auth_type === 'jwt' ? '<span>🔒</span>' : ''}
  826. </div>
  827. `).join('');
  828. } catch (error) {
  829. console.error('Failed to load MCP servers:', error);
  830. }
  831. }
  832. // Check health
  833. async function checkHealth() {
  834. try {
  835. const response = await fetch(`${API_BASE}/api/health`);
  836. if (response.ok) {
  837. statusIndicator.innerHTML = `
  838. <span class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
  839. <span class="text-sm text-gray-600">已连接</span>
  840. `;
  841. } else {
  842. throw new Error('Health check failed');
  843. }
  844. } catch (error) {
  845. statusIndicator.innerHTML = `
  846. <span class="w-2 h-2 bg-red-500 rounded-full"></span>
  847. <span class="text-sm text-gray-600">连接失败</span>
  848. `;
  849. }
  850. }
  851. // Event listeners
  852. chatForm.addEventListener('submit', (e) => {
  853. e.preventDefault();
  854. const message = userInput.value.trim();
  855. if (message) {
  856. sendMessageStream(message);
  857. userInput.value = '';
  858. }
  859. });
  860. // Initialize
  861. loadMCPServers();
  862. checkHealth();
  863. userInput.focus();
  864. // Make toggle functions global
  865. window.toggleToolPanel = toggleToolPanel;
  866. window.toggleCollapsible = toggleCollapsible;
  867. </script>
  868. </body>
  869. </html>