index.html 29.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Hermes — Agent Phone</title>
  <style>
    /* ─── Reset & Base (reused from lemonPCRM) ─── */
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    :root {
      --bg: #0f0f12;
      --card: #1a1a22;
      --card2: #22222e;
      --border: #2a2a38;
      --text: #e8e8f0;
      --muted: #8888a8;
      --accent: #6366f1;
      --accent-hover: #7c7ff5;
      --success: #22c55e;
      --warning: #f59e0b;
      --danger: #ef4444;
      --radius: 8px;
    }
    html, body { height: 100%; overflow: hidden; background: var(--bg); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; }
    ::-webkit-scrollbar { width: 4px; height: 4px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }

    /* ─── Layout ─── */
    #app { display: flex; height: 100vh; }

    /* ─── Left sidebar ─── */
    #sidebar {
      width: 260px; flex-shrink: 0;
      background: var(--card); border-right: 1px solid var(--border);
      display: flex; flex-direction: column;
    }

    .sidebar-header {
      padding: 16px; border-bottom: 1px solid var(--border);
      display: flex; align-items: center; gap: 10px;
    }
    .logo-icon { font-size: 22px; }
    .logo-text { font-size: 16px; font-weight: 700; }
    .logo-sub { font-size: 11px; color: var(--muted); margin-top: 1px; }

    .device-status {
      margin: 10px; padding: 10px 12px;
      background: var(--card2); border: 1px solid var(--border);
      border-radius: var(--radius);
    }
    .device-status-row { display: flex; align-items: center; gap: 8px; font-size: 12px; margin-bottom: 4px; }
    .device-status-row:last-child { margin-bottom: 0; }
    .dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }
    .dot.online { background: var(--success); box-shadow: 0 0 5px rgba(34,197,94,.5); }
    .dot.offline { background: var(--danger); }
    .dot.unknown { background: var(--muted); }
    .status-label { color: var(--muted); }
    .status-val { color: var(--text); margin-left: auto; }

    .sidebar-section-title {
      padding: 10px 12px 6px; font-size: 10px; font-weight: 600;
      text-transform: uppercase; letter-spacing: .1em; color: var(--muted);
    }

    #conv-list { flex: 1; overflow-y: auto; }
    .conv-item {
      display: flex; align-items: center; gap: 10px;
      padding: 9px 12px; cursor: pointer;
      border-left: 2px solid transparent;
      transition: background .1s;
    }
    .conv-item:hover { background: var(--card2); }
    .conv-item.active { background: rgba(99,102,241,.1); border-left-color: var(--accent); }
    .conv-dot { width: 28px; height: 28px; border-radius: 50%; background: linear-gradient(135deg, var(--accent), #8b5cf6); display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 700; color: #fff; flex-shrink: 0; }
    .conv-info { flex: 1; min-width: 0; }
    .conv-name { font-size: 13px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .conv-preview { font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 1px; }

    .sidebar-footer {
      padding: 10px 12px; border-top: 1px solid var(--border);
    }
    .new-chat-btn {
      width: 100%; padding: 8px; background: var(--accent); border: none;
      border-radius: var(--radius); color: #fff; font-size: 13px; cursor: pointer;
      transition: background .15s; font-weight: 500;
    }
    .new-chat-btn:hover { background: var(--accent-hover); }

    /* ─── Main chat area ─── */
    #main { flex: 1; display: flex; flex-direction: column; overflow: hidden; }

    .chat-topbar {
      height: 48px; border-bottom: 1px solid var(--border);
      display: flex; align-items: center; padding: 0 16px; gap: 12px;
      background: var(--card); flex-shrink: 0;
    }
    .chat-topbar-title { font-weight: 600; font-size: 14px; }
    .chat-topbar-sub { font-size: 12px; color: var(--muted); }
    .topbar-spacer { flex: 1; }
    .topbar-btn {
      padding: 5px 12px; border-radius: var(--radius);
      border: 1px solid var(--border); background: var(--card2);
      color: var(--text); cursor: pointer; font-size: 12px;
      transition: background .15s;
    }
    .topbar-btn:hover { background: #2d2d3d; border-color: var(--accent); }

    /* Messages area */
    #messages {
      flex: 1; overflow-y: auto; padding: 20px;
      display: flex; flex-direction: column; gap: 12px;
    }

    .msg-row { display: flex; gap: 10px; align-items: flex-start; }
    .msg-row.user { flex-direction: row-reverse; }

    .msg-avatar {
      width: 32px; height: 32px; border-radius: 50%; flex-shrink: 0;
      display: flex; align-items: center; justify-content: center; font-size: 13px;
    }
    .msg-avatar.hermes { background: linear-gradient(135deg, var(--accent), #8b5cf6); color: #fff; }
    .msg-avatar.user { background: var(--card2); border: 1px solid var(--border); color: var(--muted); }

    .msg-bubble {
      max-width: 70%; padding: 10px 14px; border-radius: 12px; font-size: 14px; line-height: 1.6;
      white-space: pre-wrap; word-break: break-word;
    }
    .msg-row.hermes .msg-bubble { background: var(--card2); border: 1px solid var(--border); border-top-left-radius: 2px; }
    .msg-row.user .msg-bubble { background: var(--accent); color: #fff; border-top-right-radius: 2px; }

    .msg-meta { font-size: 11px; color: var(--muted); margin-top: 3px; padding: 0 2px; }
    .msg-row.user .msg-meta { text-align: right; }

    .streaming-cursor::after { content: '▋'; animation: blink 1s step-end infinite; color: var(--accent); }
    @keyframes blink { 0%,100% { opacity: 1; } 50% { opacity: 0; } }

    /* Tool call badge */
    .tool-badge {
      display: inline-flex; align-items: center; gap: 5px;
      background: rgba(99,102,241,.12); border: 1px solid rgba(99,102,241,.3);
      border-radius: 6px; padding: 3px 9px; font-size: 11px; color: var(--accent);
      margin: 4px 0; cursor: default;
    }
    .tool-badge.success { background: rgba(34,197,94,.1); border-color: rgba(34,197,94,.25); color: var(--success); }
    .tool-badge.error { background: rgba(239,68,68,.1); border-color: rgba(239,68,68,.25); color: var(--danger); }

    /* Progress row */
    .progress-row {
      display: flex; align-items: center; gap: 8px;
      color: var(--muted); font-size: 13px; padding: 4px 0;
    }
    .spin { animation: spin .8s linear infinite; display: inline-block; }
    @keyframes spin { to { transform: rotate(360deg); } }

    /* Empty state */
    .empty-state {
      display: flex; flex-direction: column; align-items: center; justify-content: center;
      flex: 1; gap: 16px; color: var(--muted);
    }
    .empty-icon { font-size: 52px; }
    .empty-title { font-size: 20px; font-weight: 600; color: var(--text); }
    .empty-sub { font-size: 14px; text-align: center; max-width: 380px; line-height: 1.7; }
    .suggestion-chips { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; margin-top: 8px; }
    .chip {
      padding: 7px 14px; border-radius: 20px; border: 1px solid var(--border);
      background: var(--card2); color: var(--text); font-size: 13px; cursor: pointer;
      transition: border-color .15s, background .15s;
    }
    .chip:hover { border-color: var(--accent); background: rgba(99,102,241,.08); }

    /* Input area */
    .input-area {
      border-top: 1px solid var(--border); padding: 14px 16px;
      background: var(--card); flex-shrink: 0;
    }
    .input-row { display: flex; gap: 10px; align-items: flex-end; }
    #msg-input {
      flex: 1; min-height: 42px; max-height: 120px; resize: none;
      padding: 10px 14px; background: var(--card2); border: 1px solid var(--border);
      border-radius: var(--radius); color: var(--text); font-size: 14px; outline: none;
      transition: border-color .15s; font-family: inherit; line-height: 1.5;
    }
    #msg-input:focus { border-color: var(--accent); }
    #msg-input::placeholder { color: var(--muted); }
    #send-btn {
      width: 42px; height: 42px; border-radius: var(--radius);
      background: var(--accent); border: none; color: #fff;
      cursor: pointer; font-size: 16px; transition: background .15s; flex-shrink: 0;
      display: flex; align-items: center; justify-content: center;
    }
    #send-btn:hover { background: var(--accent-hover); }
    #send-btn:disabled { background: var(--border); cursor: not-allowed; }
    .input-hint { font-size: 11px; color: var(--muted); margin-top: 6px; }

    /* ─── Right panel: tool log ─── */
    #tool-panel {
      width: 300px; flex-shrink: 0;
      background: var(--card); border-left: 1px solid var(--border);
      display: flex; flex-direction: column;
      transition: width .2s;
    }
    #tool-panel.collapsed { width: 0; overflow: hidden; }
    .tool-panel-header {
      padding: 14px 12px; border-bottom: 1px solid var(--border);
      display: flex; align-items: center; justify-content: space-between;
      font-size: 12px; font-weight: 600; color: var(--muted);
      text-transform: uppercase; letter-spacing: .08em;
    }
    .collapse-btn { background: none; border: none; color: var(--muted); cursor: pointer; font-size: 16px; padding: 0; }
    #tool-log { flex: 1; overflow-y: auto; padding: 10px; display: flex; flex-direction: column; gap: 8px; }
    .tool-entry {
      background: var(--card2); border: 1px solid var(--border);
      border-radius: var(--radius); padding: 8px 10px;
    }
    .tool-entry-name { font-size: 12px; font-weight: 600; color: var(--accent); margin-bottom: 4px; }
    .tool-entry-params { font-size: 11px; color: var(--muted); font-family: monospace; white-space: pre-wrap; overflow: hidden; max-height: 80px; }
    .tool-entry-result { font-size: 11px; margin-top: 4px; color: var(--success); }
    .tool-entry-result.error { color: var(--danger); }
    .tool-empty { color: var(--muted); font-size: 12px; padding: 8px; text-align: center; }

    /* Toast */
    #toast { position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%); z-index: 999; pointer-events: none; }
    .toast-msg {
      padding: 9px 18px; border-radius: 8px; font-size: 13px; color: #fff;
      opacity: 0; transform: translateY(8px); transition: all .2s; white-space: nowrap;
    }
    .toast-msg.show { opacity: 1; transform: translateY(0); }
    .toast-msg.success { background: #166534; border: 1px solid var(--success); }
    .toast-msg.error { background: #7f1d1d; border: 1px solid var(--danger); }
    .toast-msg.info { background: #1e3a5f; border: 1px solid #3b82f6; }
  </style>
</head>
<body>
<div id="app">

  <!-- ── Left sidebar ── -->
  <aside id="sidebar">
    <div class="sidebar-header">
      <div class="logo-icon">🤖</div>
      <div>
        <div class="logo-text">Hermes</div>
        <div class="logo-sub">Agent Phone Controller</div>
      </div>
    </div>

    <!-- Device status -->
    <div class="device-status" id="device-status-panel">
      <div class="device-status-row">
        <span class="dot unknown" id="dot-phone"></span>
        <span class="status-label">MCP Server</span>
        <span class="status-val" id="status-phone">检测中…</span>
      </div>
      <div class="device-status-row">
        <span class="dot unknown" id="dot-events"></span>
        <span class="status-label">Event Bus</span>
        <span class="status-val" id="status-events">检测中…</span>
      </div>
      <div class="device-status-row">
        <span class="dot unknown" id="dot-adb"></span>
        <span class="status-label">ADB Forward</span>
        <span class="status-val" id="status-adb">-</span>
      </div>
    </div>

    <div class="sidebar-section-title">对话记录</div>
    <div id="conv-list">
      <!-- populated by JS -->
    </div>

    <div class="sidebar-footer">
      <button class="new-chat-btn" id="new-chat-btn">+ 新对话</button>
    </div>
  </aside>

  <!-- ── Main chat ── -->
  <main id="main">
    <div class="chat-topbar">
      <span id="topbar-session-id" class="chat-topbar-sub">新对话</span>
      <div class="topbar-spacer"></div>
      <button class="topbar-btn" id="btn-check-device">🔍 检查设备</button>
      <button class="topbar-btn" id="btn-toggle-tools">🔧 工具日志</button>
    </div>

    <div id="messages">
      <div class="empty-state" id="empty-state">
        <div class="empty-icon">📱</div>
        <div class="empty-title">Hermes Agent</div>
        <div class="empty-sub">通过自然语言控制你的 Android 手机。<br>发送消息、搜索记忆、创建日程——Hermes 会自动调用手机接口。</div>
        <div class="suggestion-chips">
          <div class="chip" data-msg="帮我查一下手机当前状态">📊 查手机状态</div>
          <div class="chip" data-msg="最近手机收到了哪些通知">🔔 最近通知</div>
          <div class="chip" data-msg="搜索我和张三的对话">💬 搜对话记录</div>
          <div class="chip" data-msg="帮我在日历创建明天下午三点的会议">📅 创建日程</div>
        </div>
      </div>
    </div>

    <div class="input-area">
      <div class="input-row">
        <textarea id="msg-input" placeholder="给 Hermes 发消息…(Enter 发送,Shift+Enter 换行)" rows="1"></textarea>
        <button id="send-btn" title="发送">➤</button>
      </div>
      <div class="input-hint">Hermes 会自动调用 Agent Phone 接口 · 手机需 USB 连接并运行 start.sh</div>
    </div>
  </main>

  <!-- ── Right: tool log panel ── -->
  <aside id="tool-panel">
    <div class="tool-panel-header">
      <span>工具调用</span>
      <button class="collapse-btn" id="collapse-tools">✕</button>
    </div>
    <div id="tool-log">
      <div class="tool-empty">暂无工具调用</div>
    </div>
  </aside>

</div>

<div id="toast"><div class="toast-msg" id="toast-msg"></div></div>

<script>
const API = '';  // same origin
let sessionId = null;
let currentSseCtrl = null;
let toolPanelOpen = true;
let conversations = [];  // { id, title, preview }

// ─── DOM refs ────────────────────────────────────────────────────────────────
const messagesEl = document.getElementById('messages');
const inputEl    = document.getElementById('msg-input');
const sendBtn    = document.getElementById('send-btn');
const emptyState = document.getElementById('empty-state');
const convList   = document.getElementById('conv-list');
const toolLog    = document.getElementById('tool-log');

// ─── Device status check ─────────────────────────────────────────────────────
async function checkDeviceStatus() {
  try {
    const res = await fetch(`${API}/api/hermes/status`);
    const data = await res.json();
    updateStatus('adb', 'online', `8765/8766`);
    // Try actual ping via Hermes
    await sendSilentMessage('get_device_status', async () => {});
  } catch(e) {
    updateStatus('phone', 'offline', '离线');
    updateStatus('events', 'offline', '离线');
    updateStatus('adb', 'offline', '未转发');
  }
}

function updateStatus(key, state, label) {
  const dot = document.getElementById(`dot-${key}`);
  const val = document.getElementById(`status-${key}`);
  if (!dot || !val) return;
  dot.className = `dot ${state}`;
  val.textContent = label;
}

// ─── Conversation list ────────────────────────────────────────────────────────
function renderConvList() {
  if (!conversations.length) {
    convList.innerHTML = `<div style="padding:12px;font-size:12px;color:var(--muted);text-align:center;">暂无对话记录</div>`;
    return;
  }
  convList.innerHTML = conversations.map(c => `
    <div class="conv-item ${c.id === sessionId ? 'active' : ''}" data-id="${c.id}">
      <div class="conv-dot">H</div>
      <div class="conv-info">
        <div class="conv-name">${escHtml(c.title)}</div>
        <div class="conv-preview">${escHtml(c.preview || '')}</div>
      </div>
    </div>
  `).join('');
  convList.querySelectorAll('.conv-item').forEach(el => {
    el.addEventListener('click', () => loadConversation(el.dataset.id));
  });
}

function loadConversation(id) {
  // For now just switch session context (messages stored in memory)
  sessionId = id;
  renderConvList();
  document.getElementById('topbar-session-id').textContent = id;
}

// ─── New chat ─────────────────────────────────────────────────────────────────
function newChat() {
  if (currentSseCtrl) { currentSseCtrl.abort(); currentSseCtrl = null; }
  sessionId = `hermes-${Date.now()}`;
  // Clear messages (except empty state)
  messagesEl.innerHTML = '';
  messagesEl.appendChild(emptyState);
  emptyState.style.display = 'flex';
  document.getElementById('topbar-session-id').textContent = '新对话';
  toolLog.innerHTML = `<div class="tool-empty">暂无工具调用</div>`;
  renderConvList();
}

// ─── Send message ─────────────────────────────────────────────────────────────
async function send() {
  const text = inputEl.value.trim();
  if (!text || sendBtn.disabled) return;

  if (!sessionId) sessionId = `hermes-${Date.now()}`;

  if (emptyState.style.display !== 'none') emptyState.style.display = 'none';

  appendMsg('user', text);
  inputEl.value = '';
  inputEl.style.height = 'auto';
  sendBtn.disabled = true;

  // Update conversation list
  const existingConv = conversations.find(c => c.id === sessionId);
  if (!existingConv) {
    conversations.unshift({ id: sessionId, title: text.slice(0, 30), preview: '' });
  }
  renderConvList();
  document.getElementById('topbar-session-id').textContent = sessionId;

  // Clear tool log for this turn
  toolLog.innerHTML = '';

  const progressEl = appendProgress('🤖 Hermes 思考中…');
  const hermesEl   = appendMsg('hermes', '', true);

  if (currentSseCtrl) { currentSseCtrl.abort(); }
  currentSseCtrl = new AbortController();

  try {
    const response = await fetch(`${API}/api/hermes/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream' },
      body: JSON.stringify({ message: text, sessionId }),
      signal: currentSseCtrl.signal,
    });

    if (!response.ok) {
      const err = await response.json().catch(() => ({ error: response.statusText }));
      throw new Error(err.error || response.statusText);
    }

    const reader = response.body.getReader();
    const dec    = new TextDecoder();
    let buf = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buf += dec.decode(value, { stream: true });
      const lines = buf.split('\n');
      buf = lines.pop();

      for (const line of lines) {
        if (!line.startsWith('data: ')) continue;
        const raw = line.slice(6).trim();
        if (!raw || raw === '[DONE]') continue;
        try {
          const ev = JSON.parse(raw);
          handleSSEEvent(ev, progressEl, hermesEl);
        } catch {}
      }
    }
  } catch (e) {
    if (e.name !== 'AbortError') {
      hermesEl.querySelector('.msg-bubble').textContent = '❌ 错误:' + e.message;
      hermesEl.querySelector('.msg-bubble').classList.remove('streaming-cursor');
      showToast(e.message, 'error');
    }
  } finally {
    progressEl.remove();
    sendBtn.disabled = false;
    currentSseCtrl = null;
    // update preview
    const conv = conversations.find(c => c.id === sessionId);
    if (conv) {
      const bubble = hermesEl.querySelector('.msg-bubble');
      conv.preview = bubble ? bubble.textContent.slice(0, 40) : '';
      renderConvList();
    }
  }
}

function handleSSEEvent(ev, progressEl, hermesEl) {
  const bubble = hermesEl.querySelector('.msg-bubble');
  switch (ev.event || detectEvent(ev)) {
    case 'session':
      sessionId = ev.sessionId || sessionId;
      break;
    case 'progress':
      progressEl.querySelector('span:last-child').textContent = ev.message || '';
      break;
    case 'agent_output':
      bubble.textContent += ev.message || '';
      scrollBottom();
      break;
    case 'tool_call':
      addToolEntry(ev.tool, ev.params);
      progressEl.querySelector('span:last-child').textContent = `调用 ${ev.tool}…`;
      break;
    case 'result':
      bubble.classList.remove('streaming-cursor');
      if (ev.toolCalls?.length) {
        ev.toolCalls.forEach(tc => updateToolEntry(tc.tool, tc.status));
      }
      // update status dots based on device_status tool
      updateStatusFromResult(ev);
      break;
    case 'error':
      bubble.textContent = `❌ ${ev.message}`;
      bubble.classList.remove('streaming-cursor');
      showToast(ev.message, 'error');
      break;
  }
}

// SSE uses named events (event: xxx) but our reader uses data parsing
// Try to detect from data payload if needed
function detectEvent(ev) {
  if (ev.sessionId !== undefined && ev.type === undefined) return 'session';
  if (ev.step !== undefined) return 'progress';
  if (ev.agent !== undefined) return 'agent_output';
  if (ev.tool !== undefined && ev.params !== undefined) return 'tool_call';
  if (ev.type !== undefined && (ev.output !== undefined || ev.rounds !== undefined)) return 'result';
  if (ev.message !== undefined && Object.keys(ev).length <= 2) return 'error';
  return null;
}

// Fix: parse SSE properly with event name
async function parseSSEStream(reader, progressEl, hermesEl) {
  const dec = new TextDecoder();
  let buf = '';
  let currentEvent = null;

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buf += dec.decode(value, { stream: true });
    const lines = buf.split('\n');
    buf = lines.pop();

    for (const line of lines) {
      if (line.startsWith('event: ')) {
        currentEvent = line.slice(7).trim();
      } else if (line.startsWith('data: ')) {
        const raw = line.slice(6).trim();
        if (!raw) continue;
        try {
          const ev = JSON.parse(raw);
          ev.event = currentEvent;
          handleSSEEvent(ev, progressEl, hermesEl);
        } catch {}
        currentEvent = null;
      }
    }
  }
}

// Replace the reader loop in send() with proper SSE parsing
// (re-attach after send is defined)

function updateStatusFromResult(result) {
  if (!result.toolCalls) return;
  const statusCall = result.toolCalls.find(tc => tc.tool === 'get_device_status');
  if (statusCall && statusCall.status === 'success') {
    updateStatus('phone', 'online', '在线');
    updateStatus('events', 'online', '在线');
    updateStatus('adb', 'online', '已连接');
  }
}

// ─── DOM helpers ──────────────────────────────────────────────────────────────
function appendMsg(role, text, streaming = false) {
  const row = document.createElement('div');
  row.className = `msg-row ${role}`;
  const avatar = role === 'hermes' ? '🤖' : '👤';
  const time = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  row.innerHTML = `
    <div class="msg-avatar ${role}">${avatar}</div>
    <div>
      <div class="msg-bubble${streaming ? ' streaming-cursor' : ''}">${escHtml(text)}</div>
      <div class="msg-meta">${time}</div>
    </div>
  `;
  messagesEl.appendChild(row);
  scrollBottom();
  return row;
}

function appendProgress(text) {
  const el = document.createElement('div');
  el.className = 'progress-row';
  el.innerHTML = `<span class="spin">⟳</span><span>${escHtml(text)}</span>`;
  messagesEl.appendChild(el);
  scrollBottom();
  return el;
}

function addToolEntry(toolName, params) {
  // Remove empty placeholder
  const placeholder = toolLog.querySelector('.tool-empty');
  if (placeholder) placeholder.remove();

  const entry = document.createElement('div');
  entry.className = 'tool-entry';
  entry.dataset.tool = toolName;
  const paramsStr = params ? JSON.stringify(params, null, 2) : '{}';
  entry.innerHTML = `
    <div class="tool-entry-name">⚡ ${escHtml(toolName)}</div>
    <div class="tool-entry-params">${escHtml(paramsStr)}</div>
    <div class="tool-entry-result">执行中…</div>
  `;
  toolLog.appendChild(entry);
  toolLog.scrollTop = toolLog.scrollHeight;
  return entry;
}

function updateToolEntry(toolName, status) {
  const entries = toolLog.querySelectorAll(`.tool-entry[data-tool="${toolName}"]`);
  const entry = entries[entries.length - 1];
  if (!entry) return;
  const resultEl = entry.querySelector('.tool-entry-result');
  if (status === 'success') {
    resultEl.textContent = '✓ 成功';
    resultEl.className = 'tool-entry-result';
  } else if (status === 'error') {
    resultEl.textContent = '✗ 失败';
    resultEl.className = 'tool-entry-result error';
  }
}

function scrollBottom() {
  messagesEl.scrollTop = messagesEl.scrollHeight;
}

function escHtml(s) {
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// ─── Toast ────────────────────────────────────────────────────────────────────
function showToast(msg, type = 'info') {
  const el = document.getElementById('toast-msg');
  el.textContent = msg;
  el.className = `toast-msg ${type} show`;
  setTimeout(() => el.classList.remove('show'), 3500);
}

// ─── Event listeners ──────────────────────────────────────────────────────────
sendBtn.addEventListener('click', send);
inputEl.addEventListener('keydown', e => {
  if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
});
inputEl.addEventListener('input', function() {
  this.style.height = 'auto';
  this.style.height = Math.min(this.scrollHeight, 120) + 'px';
});

document.getElementById('new-chat-btn').addEventListener('click', newChat);

document.getElementById('btn-check-device').addEventListener('click', async () => {
  showToast('检测设备状态…', 'info');
  // Send a status check via Hermes
  inputEl.value = '帮我检查一下手机当前的连接状态';
  send();
});

document.getElementById('btn-toggle-tools').addEventListener('click', () => {
  toolPanelOpen = !toolPanelOpen;
  document.getElementById('tool-panel').classList.toggle('collapsed', !toolPanelOpen);
});
document.getElementById('collapse-tools').addEventListener('click', () => {
  toolPanelOpen = false;
  document.getElementById('tool-panel').classList.add('collapsed');
});

// Suggestion chips
document.querySelectorAll('.chip').forEach(chip => {
  chip.addEventListener('click', () => {
    inputEl.value = chip.dataset.msg;
    send();
  });
});

// Proper SSE parsing — override send's reader loop by patching after parse
// Actually, re-route through named SSE events by overriding fetch approach:
const _origSend = send;

// Re-define send with proper named event SSE parsing:
window.send = async function() {
  const text = inputEl.value.trim();
  if (!text || sendBtn.disabled) return;

  if (!sessionId) sessionId = `hermes-${Date.now()}`;
  if (emptyState.style.display !== 'none') emptyState.style.display = 'none';

  appendMsg('user', text);
  inputEl.value = '';
  inputEl.style.height = 'auto';
  sendBtn.disabled = true;

  const existingConv = conversations.find(c => c.id === sessionId);
  if (!existingConv) {
    conversations.unshift({ id: sessionId, title: text.slice(0, 30), preview: '' });
  }
  renderConvList();
  document.getElementById('topbar-session-id').textContent = sessionId;
  toolLog.innerHTML = '';

  const progressEl = appendProgress('🤖 Hermes 思考中…');
  const hermesEl   = appendMsg('hermes', '', true);

  if (currentSseCtrl) currentSseCtrl.abort();
  currentSseCtrl = new AbortController();

  try {
    const response = await fetch(`${API}/api/hermes/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream' },
      body: JSON.stringify({ message: text, sessionId }),
      signal: currentSseCtrl.signal,
    });
    if (!response.ok) throw new Error((await response.json().catch(() => ({}))).error || response.statusText);

    await parseSSEStream(response.body.getReader(), progressEl, hermesEl);
  } catch(e) {
    if (e.name !== 'AbortError') {
      const b = hermesEl.querySelector('.msg-bubble');
      if (b) { b.textContent = '❌ ' + e.message; b.classList.remove('streaming-cursor'); }
      showToast(e.message, 'error');
    }
  } finally {
    progressEl.remove();
    sendBtn.disabled = false;
    currentSseCtrl = null;
    const conv = conversations.find(c => c.id === sessionId);
    if (conv) {
      const b = hermesEl.querySelector('.msg-bubble');
      conv.preview = b ? b.textContent.slice(0, 40) : '';
      renderConvList();
    }
  }
};

// Re-bind button + keyboard with overridden send
sendBtn.onclick = null;
document.getElementById('send-btn').addEventListener('click', () => window.send());
inputEl.onkeydown = null;
inputEl.addEventListener('keydown', e => {
  if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); window.send(); }
});

// ─── Init ─────────────────────────────────────────────────────────────────────
renderConvList();
// Check device status after 1s
setTimeout(() => {
  fetch(`${API}/api/hermes/status`).then(r => r.json()).then(data => {
    updateStatus('adb', 'online', `OK`);
  }).catch(() => {
    updateStatus('adb', 'unknown', '服务未启动');
  });
}, 800);
</script>
</body>
</html>