aichat.html 27.8 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
{% extends "base.html" %}
{% block title %}AI Chat{% endblock %}
{% block page_title %}AI 对话{% endblock %}

{% block topbar_extra %}
<button onclick="toggleChatSidebar()" aria-label="会话列表" style="
  background: rgba(255,255,255,0.15); border: none; color: white;
  padding: 4px 10px; border-radius: 6px; font-size: 13px; cursor: pointer;
  display: flex; align-items: center; gap: 4px;
">&equiv; 对话</button>
{% endblock %}

{% block body %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<style>
/* ── Chat-specific overrides (dark theme) ── */
/* Fix for foldable/unfolded: 100dvh handles dynamic viewport height */
.main { height: 100dvh; height: calc(100dvh - 48px); padding-top: 0; overflow: hidden; background: #343541; }

/* Chat layout: sidebar + main area */
.chat-layout { display: flex; height: 100%; }

/* ── Session sidebar ── */
.chat-sidebar { width: 260px; background: #202123; color: white; display: flex;
  flex-direction: column; flex-shrink: 0; position: relative; z-index: 1; }
.chat-sidebar-header { padding: 12px; border-bottom: 1px solid rgba(255,255,255,0.1); }
.chat-sidebar-header .brand { font-size: 15px; font-weight: bold; color: white; margin-bottom: 8px; }
.chat-search { padding: 8px 12px; border-bottom: 1px solid rgba(255,255,255,0.1); }
.chat-search input { width: 100%; box-sizing: border-box; padding: 8px 10px; border: 1px solid rgba(255,255,255,0.15); border-radius: 6px; background: #2d2d2f; color: white; font-size: 13px; }
.chat-search input::placeholder { color: #666; }
.conv-sort { padding: 8px 12px; border-bottom: 1px solid rgba(255,255,255,0.1); display: flex; gap: 8px; }
.conv-sort select { flex: 1; padding: 6px 8px; border: 1px solid rgba(255,255,255,0.15); border-radius: 6px; background: #2d2d2f; color: white; font-size: 12px; }
.new-chat-btn { width: 100%; padding: 8px 12px; border: 1px solid rgba(255,255,255,0.2);
  border-radius: 6px; background: transparent; color: white; font-size: 13px;
  cursor: pointer; text-align: left; transition: .15s; position: relative; z-index: 2;
  -webkit-tap-highlight-color: transparent; }
.new-chat-btn:hover { background: rgba(255,255,255,0.1); }
.new-chat-btn:active { background: rgba(255,255,255,0.2); }

.conv-list { flex: 1; overflow-y: auto; padding: 4px 8px; }
.conv-item { padding: 10px 12px; border-radius: 6px; cursor: pointer; margin-bottom: 2px;
  display: flex; justify-content: space-between; align-items: center;
  font-size: 13px; transition: .15s; -webkit-tap-highlight-color: transparent; }
.conv-item:hover { background: rgba(255,255,255,0.08); }
.conv-item.active { background: rgba(255,255,255,0.15); }
.conv-item .title { flex: 1; overflow: hidden; text-overflow: ellipsis;
  white-space: nowrap; color: #ececec; }
.conv-item .time { font-size: 11px; color: #888; margin-left: 8px; flex-shrink: 0; }
.conv-item .delete-btn { display: none; color: #888; margin-left: 6px; font-size: 14px;
  cursor: pointer; }
.conv-item:hover .delete-btn { display: inline; }
.conv-item .delete-btn:hover { color: #e74c3c; }

.chat-sidebar-footer { padding: 12px; border-top: 1px solid rgba(255,255,255,0.1); }
.chat-sidebar-footer a { color: #888; text-decoration: none; font-size: 12px; }
.chat-sidebar-footer a:hover { color: white; }

/* ── Sidebar toggle button ── (always visible) */
.chat-toggle-btn { display: flex; align-items: center; justify-content: center;
  background: none; border: none; color: white; font-size: 18px; cursor: pointer;
  padding: 4px 8px; border-radius: 4px; -webkit-tap-highlight-color: transparent; }
.chat-toggle-btn:hover { background: rgba(255,255,255,0.1); }
.chat-toggle-btn:active { background: rgba(255,255,255,0.2); }
.chat-sidebar-overlay { display: none; position: fixed; top: 48px; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.5); z-index: 50; }

/* ── Main chat area ── */
.chat-main { flex: 1; display: flex; flex-direction: column; min-width: 0;
  position: relative; z-index: 1; }
.chat-main-header { padding: 8px 16px; border-bottom: 1px solid rgba(255,255,255,0.1);
  color: white; font-size: 14px; display: flex; align-items: center; gap: 8px; }
.chat-main-header .conv-title { font-weight: bold; }

/* ── Message list ── */
.msg-list { flex: 1; overflow-y: auto; padding: 16px 20px;
  display: flex; flex-direction: column; gap: 4px; }

/* ... (msg-row, avatar, bubble styles unchanged) ... */
.msg-row { display: flex; margin-bottom: 4px; align-items: flex-start; gap: 8px; }
.msg-row.user { justify-content: flex-end; }
.msg-row.assistant { justify-content: flex-start; }

.msg-avatar { width: 30px; height: 30px; border-radius: 4px; flex-shrink: 0;
  display: flex; align-items: center; justify-content: center;
  font-size: 14px; font-weight: bold; color: white; user-select: none; }
.msg-avatar.ai { background: #19c37d; }
.msg-avatar.user-av { background: #3498db; }

.msg-bubble { padding: 10px 14px; border-radius: 8px; font-size: 14px;
  line-height: 1.55; word-break: break-word; max-width: 70%; }
.msg-row.user .msg-bubble { background: #2563eb; color: white; }
.msg-row.assistant .msg-bubble { background: #444654; color: #ececec; }

.msg-time { font-size: 10px; color: #888; margin-top: 2px; padding: 0 2px; }
.msg-row.user .msg-time { text-align: right; }

/* Empty state */
.empty-state { flex: 1; display: flex; align-items: center; justify-content: center;
  color: #888; font-size: 15px; }

/* Typing indicator */
.typing-indicator { display: flex; align-items: center; gap: 8px;
  padding: 10px 14px; color: #888; font-size: 13px; }
.typing-dots { display: flex; gap: 3px; }
.typing-dots span { width: 6px; height: 6px; background: #888; border-radius: 50%;
  animation: typingBounce 1.4s infinite; }
.typing-dots span:nth-child(2) { animation-delay: 0.2s; }
.typing-dots span:nth-child(3) { animation-delay: 0.4s; }
@keyframes typingBounce { 0%,60%,100%{transform:translateY(0);} 30%{transform:translateY(-6px);} }

/* Input area — with safe-area for foldables */
.chat-input-area { padding: 12px 16px;
  padding-bottom: max(12px, env(safe-area-inset-bottom, 12px));
  border-top: 1px solid rgba(255,255,255,0.1); display: flex; gap: 8px;
  align-items: flex-end; background: #40414f; position: relative; z-index: 1; }
.chat-input-area textarea { flex: 1; background: #40414f;
  border: 1px solid rgba(255,255,255,0.15); border-radius: 8px;
  color: white; font-size: 14px; padding: 10px 14px; resize: none;
  min-height: 44px; max-height: 150px; font-family: inherit;
  line-height: 1.4; outline: none; transition: border-color .15s;
  -webkit-tap-highlight-color: transparent; }
.chat-input-area textarea:focus { border-color: #2563eb; }
.chat-input-area textarea::placeholder { color: #888; }
.chat-input-area button { width: 40px; height: 40px; border: none; border-radius: 8px;
  background: #2563eb; color: white; font-size: 16px; cursor: pointer;
  flex-shrink: 0; display: flex; align-items: center; justify-content: center;
  transition: background .15s; -webkit-tap-highlight-color: transparent; }
.chat-input-area button:hover { background: #1d4ed8; }
.chat-input-area button:active { background: #1e40af; }
.chat-input-area button:disabled { background: #555; cursor: not-allowed; }

/* Markdown-ish */
.msg-bubble pre { background: rgba(0,0,0,0.2); padding: 8px; border-radius: 4px;
  overflow-x: auto; font-size: 13px; margin: 6px 0; }
.msg-bubble code { font-size: 12px; }
.msg-bubble p { margin: 4px 0; }

/* ── Responsive ── */
/* ≤600px only (phone/folded): sidebar becomes a slide-out drawer */
@media (max-width: 600px) {
  .chat-sidebar { position: fixed; top: 48px; left: 0; bottom: 0; z-index: 51;
    transform: translateX(-100%); transition: transform 0.25s ease; }
  .chat-sidebar.open { transform: translateX(0); }
  .chat-sidebar-overlay.show { display: block; }
}
/* >600px (incl. foldable dual-screen): sidebar visible by default, toggle hides it */
@media (min-width: 601px) {
  .chat-sidebar.collapsed { display: none; }
}
</style>

<div class="chat-layout">
  <!-- Session sidebar overlay (mobile) -->
  <div class="chat-sidebar-overlay" id="chatSidebarOverlay" onclick="closeChatSidebar()"></div>

  <!-- Session sidebar -->
  <div class="chat-sidebar" id="chatSidebar">
    <div class="chat-sidebar-header">
      <div class="brand">🧠 AI Chat</div>
      <button class="new-chat-btn" onclick="newConversation()">+ 新建对话</button>
    </div>
    <div class="chat-search">
      <input type="text" id="searchInput" placeholder="搜索对话..." oninput="renderConversations()">
    </div>
    <div class="conv-sort">
      <select id="sortBy" onchange="renderConversations()">
        <option value="time">按时间↓</option>
        <option value="title">按标题</option>
      </select>
    </div>
    <div class="conv-list" id="convList"></div>
    <div class="chat-sidebar-footer">
      <a href="/">← 返回首页</a>
    </div>
  </div>

  <!-- Main chat area -->
  <div class="chat-main">
    <div class="chat-main-header">
      <button class="chat-toggle-btn" onclick="toggleChatSidebar()" aria-label="会话列表">📋</button>
      <span class="conv-title" id="currentConvTitle">选择一个对话</span>
      <select id="agentSelect" onchange="onAgentChange()" style="margin-left:auto;font-size:12px;padding:3px 8px;border:1px solid #ddd;border-radius:6px;background:white;cursor:pointer;">
        <option value="default">🤖 default</option>
        <option value="planning">📋 planning</option>
        <option value="loop-code">💻 loop-code</option>
        <option value="qa">🧪 qa</option>
      </select>
    </div>
    <div class="msg-list" id="msgList">
      <div class="empty-state" id="emptyState">选择一个对话开始聊天</div>
    </div>
    <div class="chat-input-area">
      <textarea id="msgInput" rows="1" placeholder="输入消息..."
        onkeydown="handleKeyDown(event)"></textarea>
      <button id="sendBtn" onclick="sendMessage()">▶</button>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script>
// ── Sidebar toggle ── works at all widths
function toggleChatSidebar() {
  var sidebar = document.getElementById('chatSidebar');
  var overlay = document.getElementById('chatSidebarOverlay');
  // ≤600px: slide-out drawer mode
  if (window.innerWidth <= 600) {
    if (sidebar.classList.contains('open')) {
      closeChatSidebar();
    } else {
      sidebar.classList.add('open');
      overlay.classList.add('show');
    }
  } else {
    // >600px: collapse/expand in-place (toggle visibility)
    sidebar.classList.toggle('collapsed');
  }
}
function closeChatSidebar() {
  var sidebar = document.getElementById('chatSidebar');
  var overlay = document.getElementById('chatSidebarOverlay');
  sidebar.classList.remove('open');
  overlay.classList.remove('show');
}

function onAgentChange() {
  var sel = document.getElementById('agentSelect');
  console.log('Agent switched to:', sel.value);
}

// ── State ──
var currentConvId = null;
var isStreaming = false;

// ── Conversation Management ──

var allConversations = [];

function loadConversations() {
  try {
    var r = fetch('/api/conversations');
    r.then(function(res){ return res.json(); }).then(function(d){
      if (!d.ok) return;
      allConversations = d.data || [];
      renderConversations();
    });
  } catch(e) { console.error('loadConversations:', e); }
}

// ── Inline Rename ──
function startRename(span, convId) {
  if (span.getAttribute('contenteditable') === 'true') return;
  var oldTitle = span.textContent;
  span.setAttribute('contenteditable', 'true');
  span.focus();
  // Select all text
  var range = document.createRange();
  range.selectNodeContents(span);
  var sel = window.getSelection();
  sel.removeAllRanges();
  sel.addRange(range);
  
  function finish() {
    span.removeAttribute('contenteditable');
    var newTitle = span.textContent.trim();
    if (!newTitle || newTitle === oldTitle) {
      span.textContent = oldTitle;
      return;
    }
    // Save via API
    fetch('/api/conversations/' + convId, {
      method: 'PUT',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({title: newTitle})
    }).then(function(r) { return r.json(); }).then(function(d) {
      if (d.ok) {
        span.textContent = newTitle;
        if (currentConvId === convId) {
          document.getElementById('currentConvTitle').textContent = newTitle;
        }
      } else {
        span.textContent = oldTitle;
      }
    }).catch(function() { span.textContent = oldTitle; });
  }
  
  span.onblur = finish;
  span.onkeydown = function(e) {
    if (e.key === 'Enter') { e.preventDefault(); finish(); }
    if (e.key === 'Escape') { span.textContent = oldTitle; span.onblur = null; span.removeAttribute('contenteditable'); }
  };
}

function renderConversations() {
  var el = document.getElementById('convList');
  var q = (document.getElementById('searchInput').value || '').trim().toLowerCase();
  var sb = document.getElementById('sortBy').value;
  var convs = allConversations.slice();
  if (q) {
    convs = convs.filter(function(c) {
      return (c.title || '新对话').toLowerCase().indexOf(q) >= 0;
    });
  }
  if (sb === 'title') convs.sort(function(a,b){return (a.title||'').localeCompare(b.title||'')});
  else convs.sort(function(a,b){return (b.updated_at||'').localeCompare(a.updated_at||'')});

  if (!convs || convs.length === 0) {
    el.innerHTML = '<div style="padding:12px;color:#888;font-size:13px;">暂无对话</div>';
    return;
  }
  el.innerHTML = convs.map(function(c) {
    var title = c.title || '新对话';
    var time = formatTime(c.updated_at);
    var active = c.id === currentConvId ? ' active' : '';
    return '<div class="conv-item' + active + '" onclick="selectConversation(' + c.id + ')" data-cid="' + c.id + '">' +
      '<span class="title" ondblclick="startRename(this,' + c.id + ')">' + escapeHtml(title) + '</span>' +
      '<span class="time">' + time + '</span>' +
      '<span class="delete-btn" onclick="event.stopPropagation();deleteConversation(' + c.id + ')" title="删除">&times;</span>' +
    '</div>';
  }).join('');
}

function selectConversation(id) {
  // Update active state in DOM directly (no full reload to avoid race conditions)
  document.querySelectorAll('.conv-item').forEach(function(item) {
    item.classList.remove('active');
    if (parseInt(item.getAttribute('data-cid')) === id) {
      item.classList.add('active');
    }
  });
  
  currentConvId = id;
  var titleEl = document.querySelector('[data-cid="' + id + '"] .title');
  document.getElementById('currentConvTitle').textContent =
    (titleEl ? titleEl.textContent : '') || '对话';
  document.getElementById('emptyState').style.display = 'none';
  document.getElementById('sendBtn').disabled = false;
  loadMessages(id);    // load history
  // Update URL to /ai-chat/<id> so refresh/share keeps the session
  history.replaceState(null, '', '/ai-chat/' + id);
  // Close sidebar on mobile after selection
  if (window.innerWidth <= 600) {
    closeChatSidebar();
  }
}

async function newConversation() {
  // Don't POST immediately — defer creation until first message is sent.
  // ChatGPT behavior: click "New Chat" → blank page → type → send → create session.
  currentConvId = null;
  document.getElementById('currentConvTitle').textContent = '新对话';
  document.getElementById('emptyState').style.display = 'none';
  document.getElementById('msgList').innerHTML =
    '<div class="empty-state">输入消息开始新对话</div>';
  // Clear input + disable sendBtn (input handler will enable when user types)
  document.getElementById('msgInput').value = '';
  document.getElementById('msgInput').style.height = 'auto';
  document.getElementById('sendBtn').disabled = true;
  document.getElementById('msgInput').focus();
  // Update URL to /chat (no id)
  history.replaceState(null, '', '/chat');
  if (window.innerWidth <= 600) {
    closeChatSidebar();
  }
}

async function deleteConversation(id) {
  if (!confirm('确定删除这个对话?')) return;
  try {
    await fetch('/api/conversations/' + id, {method: 'DELETE'});
    if (currentConvId === id) {
      currentConvId = null;
      document.getElementById('currentConvTitle').textContent = '选择一个对话';
      document.getElementById('emptyState').style.display = 'flex';
      document.getElementById('msgList').innerHTML =
        '<div class="empty-state" id="emptyState">选择一个对话开始聊天</div>';
      document.getElementById('sendBtn').disabled = true;
    }
    loadConversations();
  } catch(e) { console.error('deleteConversation:', e); }
}

// ── Message Loading ──

async function loadMessages(convId) {
  if (!convId) return;
  try {
    var r = await fetch('/api/conversations/' + convId + '/messages');
    var d = await r.json();
    var list = document.getElementById('msgList');
    if (!d.ok || !d.data || d.data.length === 0) {
      list.innerHTML = '<div class="empty-state">开始对话吧</div>';
      document.getElementById('emptyState').style.display = 'none';
      return;
    }
    list.innerHTML = d.data.map(function(m) { return renderMsg(m); }).join('');
    // Apply syntax highlighting to code blocks
    if (typeof hljs !== 'undefined') {
      list.querySelectorAll('pre code').forEach(function(block) { hljs.highlightElement(block); });
    }
    scrollToBottom();
  } catch(e) { console.error('loadMessages:', e); }
}

function renderMsg(m) {
  var role = m.role;
  var content = escapeHtml(m.content || '');
  var time = formatTime(m.created_at);
  var formatted = content
    .replace(/```(\w+)?\n?([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
    .replace(/\n/g, '<br>');

  if (role === 'user') {
    return '<div class="msg-row user" data-msgid="' + m.id + '">' +
      '<div style="display:flex;flex-direction:column;align-items:flex-end;">' +
      '<div class="msg-bubble" ondblclick="editMessage(this,' + m.id + ')" title="双击编辑">' + formatted + '</div>' +
      '<div class="msg-time">' + time + '</div>' +
      '</div>' +
      '<div class="msg-avatar user-av">U</div>' +
    '</div>';
  } else {
    return '<div class="msg-row assistant" data-msgid="' + m.id + '">' +
      '<div class="msg-avatar ai">AI</div>' +
      '<div style="display:flex;flex-direction:column;align-items:flex-start;">' +
      '<div class="msg-bubble">' + formatted + '</div>' +
      '<div class="msg-time">' + time +
      ' <span class="regen-btn" onclick="regenerateReply(' + m.id + ')" title="重新生成" style="cursor:pointer;color:#888;margin-left:6px;">⟳</span>' +
      '</div>' +
      '</div>' +
    '</div>';
  }
}

// ── Message Edit ──

function editMessage(el, msgId) {
  if (isStreaming) return;
  if (el.getAttribute('contenteditable') === 'true') return;
  var oldContent = el.textContent;
  el.setAttribute('contenteditable', 'true');
  el.focus();
  el.style.outline = '2px solid #2563eb';
  el.style.borderRadius = '4px';

  function finish(save) {
    el.removeAttribute('contenteditable');
    el.style.outline = '';
    if (!save) {
      el.textContent = oldContent;
      return;
    }
    var newContent = el.textContent.trim();
    if (!newContent || newContent === oldContent) {
      el.textContent = oldContent;
      return;
    }
    // Save via API
    fetch('/api/conversations/' + currentConvId + '/messages/' + msgId, {
      method: 'PUT',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({content: newContent})
    }).then(function(r) { return r.json(); }).then(function(d) {
      if (d.ok) {
        el.textContent = newContent;
        // Auto-regenerate: delete old AI reply and get new one
        regenerateReply(null);
      } else {
        el.textContent = oldContent;
        alert('编辑失败: ' + (d.error || ''));
      }
    }).catch(function() { el.textContent = oldContent; });
  }

  el.onblur = function() { finish(true); };
  el.onkeydown = function(e) {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); finish(true); }
    if (e.key === 'Escape') { finish(false); }
  };
}

// ── Regenerate Reply ──

function regenerateReply(msgId) {
  if (isStreaming) return;
  isStreaming = true;
  document.getElementById('sendBtn').disabled = true;

  // Remove the last AI bubble visually
  var msgList = document.getElementById('msgList');
  var aiRows = msgList.querySelectorAll('.msg-row.assistant');
  if (aiRows.length > 0) {
    aiRows[aiRows.length - 1].remove();
  }

  // Add typing indicator
  var typingId = 'typing-' + Date.now();
  msgList.insertAdjacentHTML('beforeend',
    '<div class="msg-row assistant" id="' + typingId + '">' +
    '<div class="msg-avatar ai">AI</div>' +
    '<div class="typing-indicator">' +
    '<div class="typing-dots"><span></span><span></span><span></span></div>' +
    '重新生成中...' +
    '</div></div>');
  scrollToBottom();

  var es = new EventSource('/api/conversations/' + currentConvId + '/regenerate');
  var aiBubble = null;
  var fullReply = '';

  es.onmessage = function(e) {
    if (e.data === '[DONE]') {
      es.close();
      var typingEl = document.getElementById(typingId);
      if (typingEl) typingEl.remove();
      isStreaming = false;
      document.getElementById('sendBtn').disabled = false;
      document.getElementById('msgInput').focus();
      loadConversations();
      return;
    }
    var typingEl = document.getElementById(typingId);
    if (typingEl && !aiBubble) {
      typingEl.outerHTML = '<div class="msg-row assistant" id="ai-' + typingId + '">' +
        '<div class="msg-avatar ai">AI</div>' +
        '<div class="msg-bubble" id="ai-bubble-' + typingId + '"></div>' +
      '</div>';
      aiBubble = document.getElementById('ai-bubble-' + typingId);
    }
    if (aiBubble) {
      fullReply += e.data;
      aiBubble.innerHTML = escapeHtml(fullReply).replace(/\n/g, '<br>');
      scrollToBottom();
    }
  };

  es.onerror = function() {
    es.close();
    var typingEl = document.getElementById(typingId);
    if (typingEl) typingEl.remove();
    if (!fullReply && aiBubble) {
      aiBubble.textContent = '[连接中断]';
    }
    isStreaming = false;
    document.getElementById('sendBtn').disabled = false;
    loadConversations();
  };
}

// ── Send Message (SSE streaming) ──

function handleKeyDown(e) {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
}

async function sendMessage() {
  if (isStreaming) return;
  var input = document.getElementById('msgInput');
  var message = input.value.trim();
  if (!message) return;

  isStreaming = true;
  document.getElementById('sendBtn').disabled = true;

  // Deferred conversation creation: if no conversation yet, create one now
  if (!currentConvId) {
    try {
      var cr = await fetch('/api/conversations', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({title: message.slice(0, 30)})
      });
      var cd = await cr.json();
      if (!cd.ok) {
        alert('创建对话失败: ' + (cd.error || ''));
        isStreaming = false;
        document.getElementById('sendBtn').disabled = false;
        return;
      }
      currentConvId = cd.data.id;
      loadConversations();  // refresh sidebar
      // Update URL to /ai-chat/<id> so refresh/share keeps the session
      history.replaceState(null, '', '/ai-chat/' + currentConvId);
    } catch(e) {
      alert('网络错误: ' + e.message);
      isStreaming = false;
      document.getElementById('sendBtn').disabled = false;
      return;
    }
  }

  input.value = '';
  input.style.height = 'auto';

  // Add user message to UI immediately
  var msgList = document.getElementById('msgList');
  document.getElementById('emptyState').style.display = 'none';
  var now = new Date();
  var timeStr = now.toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'});
  msgList.insertAdjacentHTML('beforeend',
    '<div class="msg-row user">' +
    '<div style="display:flex;flex-direction:column;align-items:flex-end;">' +
    '<div class="msg-bubble">' + escapeHtml(message) + '</div>' +
    '<div class="msg-time">' + timeStr + '</div>' +
    '</div>' +
    '<div class="msg-avatar user-av">U</div>' +
    '</div>');

  // Add typing indicator
  var typingId = 'typing-' + Date.now();
  msgList.insertAdjacentHTML('beforeend',
    '<div class="msg-row assistant" id="' + typingId + '">' +
    '<div class="msg-avatar ai">AI</div>' +
    '<div class="typing-indicator">' +
    '<div class="typing-dots"><span></span><span></span><span></span></div>' +
    '思考中...' +
    '</div></div>');
  scrollToBottom();

  // Start SSE stream
  var agent = document.getElementById('agentSelect').value;
  var streamUrl = '/api/conversations/' + currentConvId + '/stream?message=' + encodeURIComponent(message) + '&agent=' + encodeURIComponent(agent);
  var es = new EventSource(streamUrl);
  var aiBubble = null;
  var fullReply = '';

  es.onmessage = function(e) {
    if (e.data === '[DONE]') {
      es.close();
      // Remove typing indicator
      var typingEl = document.getElementById(typingId);
      if (typingEl) typingEl.remove();
      isStreaming = false;
      document.getElementById('sendBtn').disabled = false;
      document.getElementById('msgInput').focus();

      // Reload conversations to update title/timestamp
      loadConversations();
      return;
    }
    // First chunk: replace typing indicator with actual bubble
    var typingEl = document.getElementById(typingId);
    if (typingEl && !aiBubble) {
      typingEl.outerHTML = '<div class="msg-row assistant" id="ai-' + typingId + '">' +
        '<div class="msg-avatar ai">AI</div>' +
        '<div class="msg-bubble" id="ai-bubble-' + typingId + '"></div>' +
      '</div>';
      aiBubble = document.getElementById('ai-bubble-' + typingId);
    }
    if (aiBubble) {
      fullReply += e.data;
      aiBubble.innerHTML = escapeHtml(fullReply).replace(/\n/g, '<br>');
      scrollToBottom();
    }
  };

  es.onerror = function() {
    es.close();
    var typingEl = document.getElementById(typingId);
    if (typingEl) typingEl.remove();
    if (!fullReply && aiBubble) {
      aiBubble.textContent = '[连接中断,请重试]';
    }
    isStreaming = false;
    document.getElementById('sendBtn').disabled = false;
    loadConversations();
  };

  // Auto-resize textarea
  input.style.height = 'auto';
}

// Auto-resize textarea + button state
document.getElementById('msgInput').addEventListener('input', function() {
  this.style.height = 'auto';
  this.style.height = Math.min(this.scrollHeight, 150) + 'px';
  // Enable send button only when there's text and not streaming
  var btn = document.getElementById('sendBtn');
  if (!isStreaming) {
    btn.disabled = !this.value.trim();
  }
});

// ── Utils ──

function scrollToBottom() {
  var list = document.getElementById('msgList');
  setTimeout(function() { list.scrollTop = list.scrollHeight; }, 50);
}

function formatTime(dt) {
  if (!dt) return '';
  var d = new Date(dt);
  var now = new Date();
  var diff = now - d;
  if (diff < 60000) return '刚刚';
  if (diff < 3600000) return Math.floor(diff/60000) + '分钟前';
  if (diff < 86400000) return Math.floor(diff/3600000) + '小时前';
  return d.toLocaleDateString('zh-CN');
}

function escapeHtml(s) {
  var d = document.createElement('div');
  d.textContent = s;
  return d.innerHTML;
}

// Init
loadConversations();
// Start with send button disabled until user types
document.getElementById('sendBtn').disabled = true;

// If Flask passed an initial_conv_id (from /chat/<conv_id>), auto-select it
{% if initial_conv_id is defined and initial_conv_id %}
(function() {
  var targetId = {{ initial_conv_id }};
  // Wait for conversation list to load, then select the target conversation
  var checkInterval = setInterval(function() {
    var item = document.querySelector('[data-cid="' + targetId + '"]');
    if (item) {
      clearInterval(checkInterval);
      selectConversation(targetId);
    }
  }, 100);
  // Safety timeout after 5s
  setTimeout(function() { clearInterval(checkInterval); }, 5000);
})();
{% endif %}
</script>
{% endblock %}