AgentChat.vue 44.7 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 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
<template>
  <div class="agent-chat-page">
    <AppNav />
    <div class="agent-chat-layout">

      <!-- 第1列: Agent 列表 (始终可见) -->
      <aside class="agent-sidebar">
        <div class="col-header">🏢 Agents</div>
        <div class="agent-list">
          <template v-for="(agents, compId) in groupedAgents" :key="compId">
            <div class="agent-group-title">{{ compId === 'system' ? '💻 系统 Agent' : `🏢 ${compId}` }}</div>
            <div
              v-for="a in agents" :key="a.id"
              class="agent-card" :class="{ active: agentId === a.id }"
              @click="agentId = a.id; switchAgent()"
            >
              <span class="agent-card-emoji">{{ a.emoji || '🤖' }}</span>
              <div class="agent-card-info">
                <div class="agent-card-name">{{ a.name }}</div>
                <div class="agent-card-type">{{ a.type }}</div>
              </div>
            </div>
          </template>
        </div>
      </aside>

      <!-- ═══ Chat 模式 ═══ -->
      <template v-if="activeTab === 'chat'">

        <!-- 第2列: 对话列表 -->
        <aside class="conv-sidebar">
          <div class="col-header">
            <div class="tab-bar">
              <button class="tab active" @click="activeTab='chat'">💬 Chat</button>
              <button class="tab" @click="activeTab='detail'">📋 Detail</button>
            </div>
            <button class="new-chat-btn" @click="newConversation"><span>+</span></button>
          </div>
          <div class="conv-list">
            <div
              v-for="conv in conversations"
              :key="conv.conversationId || conv.id"
              class="conv-card"
              :class="{ active: activeConvId === (conv.conversationId || conv.id) }"
              @click="switchConversation(conv.conversationId || conv.id)"
            >
              <div class="conv-card-top">
                <div class="conv-title">{{ conv.title || '新对话' }}</div>
                <button class="conv-delete-btn" title="删除对话" @click.stop="deleteConversation(conv.conversationId || conv.id)">🗑</button>
              </div>
              <div class="conv-meta">
                <span class="conv-time">{{ formatTime(conv.updatedAt) }}</span>
                <span class="conv-count">{{ conv.messageCount || conv.stats?.messageCount || 0 }} 条</span>
              </div>
            </div>
            <div v-if="conversations.length === 0" class="empty-state">还没有对话</div>
          </div>
          <div class="sidebar-footer">
            <div class="agent-badge">
              <span class="agent-emoji">{{ agentInfo.emoji || '🏗️' }}</span>
              <div>
                <div class="agent-name-small">{{ agentInfo.name }}</div>
                <div class="agent-status-small" :class="agentInfo.status">{{ getDisplayStatus(agentInfo.status) }}</div>
              </div>
            </div>
          </div>
        </aside>

        <!-- 第3列: 消息区 -->
        <section class="chat-panel">
          <div v-if="messages.length === 0 && !streaming" class="welcome-screen">
            <div class="welcome-content">
              <div class="welcome-emoji">{{ agentInfo.emoji || '🏗️' }}</div>
              <h2 class="welcome-title">{{ agentInfo.name || 'Agent' }}</h2>
              <p class="welcome-greeting">{{ agentInfo.greeting || '准备就绪。' }}</p>
              <div class="welcome-hints">
                <button class="hint-chip" @click="quickSend('帮我创建一个写诗的 Agent')">✍️ 创建诗人</button>
                <button class="hint-chip" @click="quickSend('你有哪些技能?')">🧠 技能</button>
                <button class="hint-chip" @click="quickSend('你好')">👋 招呼</button>
              </div>
            </div>
          </div>
          <div v-else ref="messageListRef" class="message-list">
            <div v-for="(msg, idx) in messages" :key="idx" class="msg-row" :class="`msg-${msg.role}`">
              <div class="msg-avatar" :class="`avatar-${msg.role}`">{{ msg.role === 'user' ? '👤' : (agentInfo.emoji || '🏗️') }}</div>
              <div class="msg-body">
                <div class="msg-header">
                  <span class="msg-role">{{ msg.role === 'user' ? '你' : agentInfo.name }}</span>
                  <span class="msg-time">{{ formatMsgTime(msg.timestamp) }}</span>
                </div>
                <div class="msg-content" v-html="renderMarkdown(msg.content)"></div>
              </div>
            </div>
            <div v-if="streaming" class="msg-row msg-assistant streaming">
              <div class="msg-avatar avatar-assistant">{{ agentInfo.emoji || '🏗️' }}</div>
              <div class="msg-body">
                <div class="msg-header"><span class="msg-role">{{ agentInfo.name }}</span><span class="typing-indicator"><span></span><span></span><span></span></span></div>
                <div class="msg-content" v-html="renderMarkdown(streamContent)"></div>
              </div>
            </div>
            <div v-if="sending && thinkingContent" class="thinking-block">
              <div class="thinking-header" @click="showThinking = !showThinking">
                <div class="thinking-pulse"></div>
                <span class="thinking-label">{{ streaming ? '💭 思考完成' : '💭 思考中...' }}</span>
                <span class="thinking-toggle">{{ showThinking ? '▼' : '▶' }}</span>
              </div>
              <div v-if="showThinking" class="thinking-content">{{ thinkingContent }}</div>
            </div>
            <div v-if="sending && !streaming && !thinkingContent" class="thinking-row">
              <div class="thinking-pulse"></div>
              <span class="thinking-text">{{ thinkingText }}</span>
            </div>
          </div>
          <div class="chat-input-area">
            <div class="input-box" :class="{ focused: inputFocused }">
              <textarea ref="inputRef" v-model="inputText" :disabled="sending" :placeholder="sending ? '等待回复中...' : '跟 ' + agentInfo.name + ' 对话...'" class="msg-textarea" rows="1" @keydown="handleKeydown" @focus="inputFocused = true" @blur="inputFocused = false" @input="autoResize"></textarea>
              <button v-if="sending" class="send-btn stop-btn" @click="handleStop">⏹</button>
              <button v-else class="send-btn" :class="{ ready: inputText.trim() && !sending }" :disabled="!inputText.trim()" @click="handleSend">➤</button>
            </div>
            <div class="input-hint">Shift+Enter 换行 · {{ messages.length }} 条消息</div>
          </div>
        </section>

        <!-- 第4列: ACP 事件 -->
        <aside class="acp-panel">
          <div class="col-header"><span>⚡ ACP Events</span><span class="acp-count">{{ acpLog.length }}</span></div>
          <div class="acp-list">
            <div v-if="acpLog.length > 0" class="acp-card">
              <div class="acp-card-header"><span>⚡ Event Stream</span><span v-if="sending" class="badge-live">LIVE</span></div>
              <div class="acp-log-stream">
                <div v-for="(evt, i) in acpLog" :key="i" class="acp-event-line" :class="'acp-' + evt.type">
                  <span class="acp-icon">{{ evt.icon }}</span>
                  <span class="acp-text">{{ evt.text }}</span>
                </div>
              </div>
            </div>
            <div v-for="(sub, callId) in subAgents" :key="'live-'+callId" class="sub-log-card" :class="sub.status">
              <div class="sub-log-card-header" @click="sub.collapsed = !sub.collapsed">
                <span class="sub-log-icon">{{ sub.status === 'running' ? '🚀' : (sub.status === 'success' ? '✅' : '❌') }}</span>
                <span class="sub-log-agent">{{ sub.agent }}</span>
                <span class="badge-live">LIVE</span>
                <span class="sub-log-toggle">{{ sub.collapsed ? '▶' : '▼' }}</span>
              </div>
              <div v-if="!sub.collapsed" class="sub-log-content terminal">{{ sub.content || '等待输出...' }}</div>
            </div>
            <div v-for="log in subLogList" :key="log.file" class="sub-log-card" :class="log.status">
              <div class="sub-log-card-header" @click="log.collapsed = !log.collapsed">
                <span class="sub-log-icon">{{ log.status === 'success' ? '✅' : (log.status === 'error' ? '❌' : '⏳') }}</span>
                <span class="sub-log-agent">{{ log.agent }}</span>
                <span class="sub-log-toggle">{{ log.collapsed ? '▶' : '▼' }}</span>
              </div>
              <div v-if="!log.collapsed" class="sub-log-content terminal">{{ log.content }}</div>
            </div>
            <div v-if="acpLog.length === 0 && subLogList.length === 0 && Object.keys(subAgents).length === 0" class="acp-empty">
              发送消息后,ACP 事件<br>将在这里实时显示
            </div>
          </div>
        </aside>
      </template>

      <!-- ═══ Detail 模式 ═══ -->
      <template v-else>

        <!-- 第2列: Agent 详情 -->
        <aside class="conv-sidebar">
          <div class="col-header">
            <div class="tab-bar">
              <button class="tab" @click="activeTab='chat'">💬 Chat</button>
              <button class="tab active" @click="activeTab='detail'">📋 Detail</button>
            </div>
          </div>
          <div class="col-scroll">
            <div class="detail-hero">
              <span class="detail-emoji">{{ agentInfo.emoji || '🤖' }}</span>
              <div>
                <h2 class="detail-name">{{ agentInfo.name }}</h2>
                <div class="detail-meta">
                  <span class="detail-type-badge">{{ agentInfo.type }}</span>
                  <span class="detail-status" :class="agentInfo.status">{{ getDisplayStatus(agentInfo.status) }}</span>
                </div>
              </div>
            </div>
            <div class="detail-section">
              <div class="detail-label">ID</div>
              <div class="detail-value mono">{{ agentId }}</div>
            </div>
            <div class="detail-section">
              <div class="detail-label">问候语</div>
              <div class="detail-value">{{ agentInfo.greeting || '(无)' }}</div>
            </div>
            <div class="detail-section">
              <div class="detail-label">Bootstrap 文件</div>
              <div class="detail-files">
                <span v-for="f in (agentInfo.bootstrapFiles||[])" :key="f" class="file-tag" @click="previewFile(f)">{{ f }}</span>
              </div>
            </div>
            <div class="detail-section">
              <div class="detail-label">统计</div>
              <div class="detail-stats">
                <div class="stat-item"><span class="stat-num">{{ fileTree?.totalFiles || 0 }}</span> 文件</div>
                <div class="stat-item"><span class="stat-num">{{ conversations.length }}</span> 对话</div>
              </div>
            </div>
          </div>
        </aside>

        <!-- 第3列: 文件树 -->
        <section class="chat-panel" style="min-width:220px;max-width:280px;flex:none;">
          <div class="col-header">📁 文件 <span v-if="fileTree" class="acp-count">{{ fileTree.totalFiles }}</span></div>
          <div class="col-scroll" v-if="fileTree">
            <div class="file-tree">
              <template v-for="node in fileTree.tree" :key="node.path">
                <FileNode :node="node" :depth="0" :selected="selectedFile" @select="previewFile" @delete="deleteFile" />
              </template>
            </div>
          </div>
          <div v-else class="acp-empty">加载中...</div>
        </section>

        <!-- 第4列: 文件编辑器 -->
        <aside class="acp-panel" style="flex:1;min-width:300px;">
          <div class="col-header">
            <span>✏️ {{ selectedFile || '编辑器' }}</span>
            <div v-if="previewContent !== null" class="editor-actions">
              <span v-if="fileDirty" class="dirty-badge">未保存</span>
              <button v-if="fileDirty" class="editor-btn reset-btn" @click="resetPreview">↩ 重置</button>
              <button v-if="fileDirty" class="editor-btn save-btn" @click="saveFile">💾 保存</button>
            </div>
          </div>
          <div class="col-scroll editor-scroll">
            <textarea v-if="previewContent !== null" v-model="editContent" class="editor-textarea" spellcheck="false"></textarea>
            <div v-else class="acp-empty">← 点击文件以编辑</div>
          </div>
        </aside>
      </template>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppNav from '@/components/AppNav.vue'
import FileNode from '@/components/FileNode.vue'
import { marked } from 'marked'

const route = useRoute()
const router = useRouter()
const agentId = ref(route.params.agentId || '')
const agentList = ref([])

const groupedAgents = computed(() => {
  const groups = {}
  agentList.value.forEach(a => {
    const comp = a.companyId || 'system'
    // If we are in a company context, filter out other companies
    if (route.params.id && comp !== route.params.id) return

    if (!groups[comp]) groups[comp] = []
    groups[comp].push(a)
  })
  
  // 确保 system 永远在最上面排第一
  const sortedKeys = Object.keys(groups).sort((a,b) => {
    if (a === 'system') return -1;
    if (b === 'system') return 1;
    return a.localeCompare(b);
  })
  
  const sortedGroups = {}
  sortedKeys.forEach(k => { sortedGroups[k] = groups[k] })
  return sortedGroups
})
const activeTab = ref('chat') // 'chat' | 'detail'

const agentInfo = ref({ name: 'Agent Creator', emoji: '🏗️', type: 'meta', status: 'ready', greeting: '', bootstrapFiles: [] })

// 状态映射:英文 -> 中文
const statusMap = {
  'ready': '待命',
  'running': '运行中',
  'completed': '已完成',
  'failed': '失败',
  'stopped': '已停止',
  'pending': '等待中',
  'inactive': '未激活'
}

// 获取显示状态
function getDisplayStatus(status) {
  if (!status) return '未知'
  return statusMap[status] || status
}
const conversations = ref([])
const messages = ref([])
const inputText = ref('')
const inputFocused = ref(false)
const sending = ref(false)
const streaming = ref(false)
const streamContent = ref('')
const subAgents = ref({})
const subLogList = ref([])
const acpLog = ref([])
const thinkingText = ref('🏗️ 启动中...')
const thinkingContent = ref('')
const showThinking = ref(true)
const messageListRef = ref(null)
const inputRef = ref(null)
const activeConvId = ref(null)

// Detail mode state
const fileTree = ref(null)
const selectedFile = ref(null)
const previewContent = ref(null)
const editContent = ref(null)
const fileDirty = computed(() => editContent.value !== null && previewContent.value !== null && editContent.value !== previewContent.value)

// ─── Load ───

async function loadAgentList() {
  try {
    const r = await fetch('/api/agent/list')
    if (r.ok) {
      agentList.value = await r.json()
    }

    // 公司上下文: 额外拉取该公司的 Agent 列表并合并
    const companyId = route.params.id
    if (companyId) {
      try {
        const cr = await fetch(`/api/company/${companyId}/agents`)
        if (cr.ok) {
          const companyAgents = await cr.json()
          // 将公司 Agent 转换为统一格式并合并(去重)
          const existingIds = new Set(agentList.value.map(a => a.id))
          for (const ca of companyAgents) {
            const aid = ca.id || ca.role
            if (!existingIds.has(aid) && !existingIds.has(`${companyId}:${aid}`)) {
              agentList.value.push({
                id: `${companyId}:${aid}`,
                name: ca.name || aid,
                type: ca.type || 'specialist',
                emoji: ca.emoji || '🤖',
                status: ca.status || 'idle',
                companyId: companyId,
              })
            }
          }
        }
      } catch (e) { console.error('Failed to load company agents', e) }
    }
      
    // Auto-select first available agent if none or invalid is selected
    const currentValid = agentList.value.some(a => a.id === agentId.value)
    if (!agentId.value || !currentValid) {
       const grpKey = route.params.id || 'system'
       const avail = groupedAgents.value[grpKey] 
       if (avail && avail.length > 0) {
          agentId.value = avail[0].id
          // Update URL without triggering reload
          if (route.params.id) {
             router.replace({ params: { id: route.params.id, agentId: agentId.value }})
          } else {
             router.replace({ params: { agentId: agentId.value }})
          }
       } else if (!route.params.id) {
          agentId.value = 'agent-creator'
       }
    }
  } catch (e) { console.error('Failed to load agent list', e) }
}

async function loadAgentInfo() {
  if (!agentId.value) return
  try {
    const r = await fetch(`/api/agent/${agentId.value}/info`)
    if (r.ok) agentInfo.value = await r.json()
  } catch (e) { console.error('Agent info error:', e) }
}

async function loadConversations() {
  if (!agentId.value) return
  try {
    const r = await fetch(`/api/agent/${agentId.value}/conversations`)
    if (r.ok) conversations.value = await r.json()
  } catch (e) { console.error('Conv list error:', e) }
}

async function loadConversation(convId) {
  if (!agentId.value) return
  try {
    const r = await fetch(`/api/agent/${agentId.value}/conversations/${convId}`)
    if (r.ok) {
      const conv = await r.json()
      messages.value = conv.messages || []
      if (conv.subLogs && conv.subLogs.length > 0) {
        subLogList.value = conv.subLogs.map(l => ({ ...l, collapsed: true }))
      } else { subLogList.value = [] }
    }
  } catch { messages.value = []; subLogList.value = [] }
}

async function loadFileTree() {
  if (!agentId.value) return
  try {
    const r = await fetch(`/api/agent/${agentId.value}/files`)
    if (r.ok) fileTree.value = await r.json()
  } catch { fileTree.value = null }
}

async function previewFile(filePath) {
  if (!agentId.value) return
  selectedFile.value = filePath
  // If in chat mode, switch to detail to show preview
  if (activeTab.value === 'chat') activeTab.value = 'detail'
  try {
    const r = await fetch(`/api/agent/${agentId.value}/file/${filePath}`)
    if (r.ok) {
      const data = await r.json()
      previewContent.value = data.content
      editContent.value = data.content
    }
  } catch { previewContent.value = '(加载失败)'; editContent.value = previewContent.value }
}

function resetPreview() {
  editContent.value = previewContent.value
}

async function saveFile() {
  if (!agentId.value || !selectedFile.value) return
  try {
    const r = await fetch(`/api/agent/${agentId.value}/file/${selectedFile.value}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content: editContent.value }),
    })
    if (r.ok) {
      previewContent.value = editContent.value
      // Refresh file tree to update sizes
      await loadFileTree()
    }
  } catch (e) { console.error('Save file error:', e) }
}

async function deleteFile(filePath) {
  if (!agentId.value) return
  try {
    const r = await fetch(`/api/agent/${agentId.value}/file/${filePath}`, { method: 'DELETE' })
    if (r.ok) {
      // If the deleted file was being previewed, clear the editor
      if (selectedFile.value === filePath || selectedFile.value?.startsWith(filePath + '/')) {
        selectedFile.value = null
        previewContent.value = null
        editContent.value = null
      }
      await loadFileTree()
    }
  } catch (e) { console.error('Delete file error:', e) }
}

function newConversation() {
  activeConvId.value = null
  messages.value = []
  streamContent.value = ''
  subAgents.value = {}
  subLogList.value = []
  acpLog.value = []
  
  if (route.params.id) {
    router.replace({ params: { id: route.params.id, agentId: agentId.value, convId: undefined }})
  } else {
    router.replace({ params: { agentId: agentId.value, convId: undefined }})
  }
}

async function switchAgent() {
  newConversation()
  selectedFile.value = null
  previewContent.value = null
  fileTree.value = null
  await loadAgentInfo()
  await loadConversations()
  await loadFileTree()
}

async function switchConversation(convId) {
  activeConvId.value = convId
  if (route.params.id) {
    router.replace({ params: { id: route.params.id, agentId: agentId.value, convId } })
  } else {
    router.replace({ params: { agentId: agentId.value, convId } })
  }
  await loadConversation(convId)
  scrollToBottom()
}

function quickSend(text) { inputText.value = text; handleSend() }

async function deleteConversation(convId) {
  if (!confirm('确定删除这个对话?对话内容和日志将被永久清除。')) return
  try {
    const r = await fetch(`/api/agent/${agentId.value}/conversations/${convId}`, { method: 'DELETE' })
    if (r.ok) {
      conversations.value = conversations.value.filter(c => (c.conversationId || c.id) !== convId)
      if (activeConvId.value === convId) {
        activeConvId.value = null
        messages.value = []
        streamContent.value = ''
        subAgents.value = {}
        subLogList.value = []
        acpLog.value = []
      }
    }
  } catch (e) { console.error('Delete conv error:', e) }
}

// ─── Chat (SSE) ───

async function handleSend() {
  const text = inputText.value.trim()
  if (!text || sending.value || !agentId.value) return
  messages.value.push({ role: 'user', content: text, timestamp: new Date().toISOString() })
  inputText.value = ''
  if (inputRef.value) inputRef.value.style.height = 'auto'
  sending.value = true; streaming.value = false; streamContent.value = ''
  subAgents.value = {}; acpLog.value = []; thinkingContent.value = ''
  showThinking.value = true
  thinkingText.value = `${agentInfo.value.emoji} ${agentInfo.value.name} 思考中...`
  activeTab.value = 'chat' // ensure we're in chat mode
  scrollToBottom()

  if (activeConvId.value) {
    const existsInList = conversations.value.some(c => (c.conversationId || c.id) === activeConvId.value)
    if (!existsInList) {
      conversations.value.unshift({ conversationId: activeConvId.value, title: text.slice(0, 50), updatedAt: new Date().toISOString(), messageCount: messages.value.length, status: 'running' })
    }
  }

  try {
    const r = await fetch(`/api/agent/${agentId.value}/chat`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message: text, conversationId: activeConvId.value }),
    })
    const reader = r.body.getReader()
    const decoder = new TextDecoder()
    let buffer = '', lastEventType = ''
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''
      for (const line of lines) {
        if (line.startsWith('event: ')) lastEventType = line.slice(7)
        else if (line.startsWith('data: ')) {
          try { handleEvent(lastEventType, JSON.parse(line.slice(6))) } catch {}
        }
      }
    }
    if (streamContent.value) {
      messages.value.push({ role: 'assistant', content: streamContent.value, timestamp: new Date().toISOString() })
    }
    await loadConversations()
    if (activeConvId.value) await loadSubLogs()
  } catch (err) {
    messages.value.push({ role: 'assistant', content: `❌ 错误: ${err.message}`, timestamp: new Date().toISOString() })
  } finally {
    sending.value = false; streaming.value = false; streamContent.value = ''; thinkingContent.value = ''
  }
}

async function loadSubLogs() {
  try {
    const r = await fetch(`/api/agent/${agentId.value}/conversations/${activeConvId.value}/sub-logs`)
    if (r.ok) { const logs = await r.json(); subLogList.value = logs.map(l => ({ ...l, collapsed: true })) }
  } catch {}
}

async function handleStop() {
  if (!activeConvId.value) return
  try { await fetch(`/api/agent/${agentId.value}/chat/${activeConvId.value}/stop`, { method: 'POST' }) } catch(e) { console.error('Stop error:', e) }
  sending.value = false; streaming.value = false
  messages.value.push({ role: 'assistant', content: `*[已终止]*`, timestamp: new Date().toISOString() })
  scrollToBottom()
}

function handleEvent(type, data) {
  switch (type) {
    case 'session':
      if (data.conversationId && !activeConvId.value) {
        activeConvId.value = data.conversationId
        if (route.params.id) {
          router.replace({ params: { id: route.params.id, agentId: agentId.value, convId: data.conversationId } })
        } else {
          router.replace({ params: { agentId: agentId.value, convId: data.conversationId } })
        }
        const existsInList = conversations.value.some(c => (c.conversationId || c.id) === data.conversationId)
        if (!existsInList) {
          conversations.value.unshift({ conversationId: data.conversationId, title: messages.value.find(m => m.role === 'user')?.content?.slice(0, 50) || '新对话', updatedAt: new Date().toISOString(), messageCount: 1, status: 'running' })
        }
      }
      break
    case 'thinking':
      if (data.message && !data.message.startsWith('🏗️')) { thinkingContent.value += data.message; scrollToBottom() }
      else { thinkingText.value = data.message || '思考中...' }
      break
    case 'agent_output':
      streaming.value = true; streamContent.value += (data.message || ''); scrollToBottom(); break
    case 'tool_call':
      thinkingText.value = data.message || `🔧 ${data.tool}`
      acpLog.value.push({ type: 'tool', icon: '🔧', text: `${data.tool}`, ts: Date.now() }); scrollAcpLog(); break
    case 'tool_input':
      acpLog.value.push({ type: 'input', icon: '📥', text: data.input?.slice(0, 300) || '', ts: Date.now() }); scrollAcpLog(); break
    case 'tool_result':
      acpLog.value.push({ type: 'result', icon: '📤', text: data.result?.slice(0, 300) || '', ts: Date.now() }); scrollAcpLog(); break
    case 'session_cost':
      acpLog.value.push({ type: 'cost', icon: '💰', text: `$${data.cost?.toFixed(4)} (${((data.duration||0)/1000).toFixed(1)}s)`, ts: Date.now() }); break
    case 'acp_raw':
      if (data.method && !data.method.includes('content_block_delta') && !data.method.includes('message_start')) {
        acpLog.value.push({ type: 'raw', icon: '⚡', text: data.method, ts: Date.now() }); scrollAcpLog()
      }
      break
    case 'sub_agent':
      if (!subAgents.value[data.callId]) subAgents.value[data.callId] = { agent: data.agent, status: 'running', content: '', collapsed: false }
      if (data.event === 'chunk' && data.chunk) {
        subAgents.value[data.callId].content += data.chunk
        setTimeout(() => { document.querySelectorAll('.sub-log-content').forEach(el => el.scrollTop = el.scrollHeight) }, 50)
      } else if (data.event === 'done') subAgents.value[data.callId].status = data.status
      else if (data.event === 'start') subAgents.value[data.callId].status = 'running'
      scrollToBottom(); break
    case 'error':
      messages.value.push({ role: 'assistant', content: `❌ ${data.message}`, timestamp: new Date().toISOString() })
      acpLog.value.push({ type: 'error', icon: '🚨', text: data.message, ts: Date.now() })
      thinkingText.value = ''; thinkingContent.value = ''
      scrollToBottom(); scrollAcpLog(); break
  }
}

function handleKeydown(e) { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); handleSend() } }
function scrollAcpLog() { nextTick(() => { const el = document.querySelector('.acp-log-stream'); if (el) el.scrollTop = el.scrollHeight }) }
function autoResize() { const el = inputRef.value; if (!el) return; el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 160) + 'px' }
function scrollToBottom() { nextTick(() => { if (messageListRef.value) messageListRef.value.scrollTop = messageListRef.value.scrollHeight }) }

function formatTime(d) {
  if (!d) return ''
  const diff = Date.now() - new Date(d)
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  return new Date(d).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
}
function formatMsgTime(t) { if (!t) return ''; return new Date(t).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) }
function renderMarkdown(text) {
  try { return marked.parse(text || '', { breaks: true, gfm: true }) }
  catch { return (text || '').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>') }
}

watch([messages, streamContent], () => scrollToBottom(), { deep: true })
// Load file tree when switching to detail tab
watch(activeTab, async (tab) => { if (tab === 'detail' && !fileTree.value) await loadFileTree() })

// Catch inter-company navigations or direct parameter changes
watch(() => route.params.id, async (newId, oldId) => {
  if (newId !== oldId) {
    agentId.value = ''
    await loadAgentList()
    await switchAgent()
  }
})

onMounted(async () => {
  await loadAgentList()
  await loadAgentInfo()
  await loadConversations()
  if (route.params.convId) {
    activeConvId.value = route.params.convId
    await loadConversation(route.params.convId)
    scrollToBottom()
  }
})
</script>

<style scoped>
.agent-chat-page {
  height: 100vh; display: flex; flex-direction: column;
  background: var(--bg-primary);
  color: var(--text-primary); font-family: 'Inter', -apple-system, sans-serif;
  transition: background 0.3s, color 0.3s;
}
.agent-chat-layout { flex: 1; display: flex; overflow: hidden; }

/* ═══ 共用 ═══ */
.col-header {
  padding: 8px 12px; font-size: 12px; font-weight: 700; color: var(--text-tertiary);
  border-bottom: 1px solid var(--border-primary);
  display: flex; align-items: center; justify-content: space-between; gap: 6px;
}
.col-scroll { flex: 1; overflow-y: auto; padding: 8px; }
.empty-state { text-align: center; padding: 24px 12px; color: var(--text-faint); font-size: 11px; }

/* Tab bar */
.tab-bar { display: flex; gap: 2px; }
.tab {
  padding: 4px 10px; border-radius: 6px; border: none;
  background: transparent; color: var(--text-muted); font-size: 11px; font-weight: 600;
  cursor: pointer; transition: all 0.15s;
}
.tab:hover { background: var(--bg-surface-hover); color: var(--text-tertiary); }
.tab.active { background: var(--accent-bg-hover); color: var(--accent-light); }

/* ═══ 第1列: Agent 列表 ═══ */
.agent-sidebar {
  width: 170px; min-width: 150px; border-right: 1px solid var(--border-primary);
  background: var(--bg-overlay); display: flex; flex-direction: column;
}
.agent-list { flex: 1; overflow-y: auto; padding: 6px; }
.agent-group-title { font-size: 10px; font-weight: 700; color: var(--text-tertiary); padding: 8px 6px 4px; text-transform: uppercase; }
.agent-card {
  display: flex; align-items: center; gap: 8px;
  padding: 7px 10px; border-radius: 8px; cursor: pointer;
  transition: all 0.15s; margin-bottom: 2px; border: 1px solid transparent;
}
.agent-card:hover { background: var(--accent-bg); }
.agent-card.active { background: var(--bg-surface-active); border-color: var(--border-active); }
.agent-card-emoji { font-size: 18px; flex-shrink: 0; }
.agent-card-info { min-width: 0; }
.agent-card-name { font-size: 11px; font-weight: 600; color: var(--text-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.agent-card-type { font-size: 9px; color: var(--text-faint); }

/* ═══ 第2列: 对话列表 / 详情 ═══ */
.conv-sidebar {
  width: 200px; min-width: 180px; border-right: 1px solid var(--border-primary);
  background: var(--bg-surface); display: flex; flex-direction: column;
}
.new-chat-btn {
  background: var(--accent); color: #fff; border: none; padding: 3px 8px; border-radius: 5px;
  cursor: pointer; font-size: 12px; font-weight: 600; transition: all 0.2s;
}
.new-chat-btn:hover { box-shadow: 0 3px 10px rgba(16,185,129,0.3); }
.conv-list { flex: 1; overflow-y: auto; padding: 6px; }
.conv-card {
  padding: 7px 9px; border-radius: 7px; cursor: pointer; transition: all 0.15s;
  margin-bottom: 2px; border: 1px solid transparent;
}
.conv-card:hover { background: var(--accent-bg); }
.conv-card:hover .conv-delete-btn { opacity: 1; }
.conv-card.active { background: var(--accent-bg); border-color: var(--border-active); }
.conv-card-top { display: flex; align-items: center; gap: 4px; }
.conv-title { font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
.conv-delete-btn {
  opacity: 0; border: none; background: transparent; cursor: pointer; font-size: 11px;
  padding: 2px 4px; border-radius: 4px; transition: all 0.15s; flex-shrink: 0; line-height: 1;
}
.conv-delete-btn:hover { background: rgba(239,68,68,0.15); transform: scale(1.15); }
.conv-meta { display: flex; align-items: center; gap: 6px; }
.conv-time { font-size: 9px; color: var(--text-faint); }
.conv-count { font-size: 9px; color: var(--text-faint); }
.sidebar-footer { padding: 8px; border-top: 1px solid var(--border-primary); }
.agent-badge { display: flex; align-items: center; gap: 6px; }
.agent-emoji { font-size: 16px; }
.agent-name-small { font-size: 11px; font-weight: 600; color: var(--accent-light); }
.agent-status-small { font-size: 9px; color: var(--text-muted); }
.agent-status-small.ready { color: var(--accent); }

/* Detail mode - col 2 */
.detail-hero { display: flex; align-items: center; gap: 10px; padding: 12px 4px; margin-bottom: 10px; border-bottom: 1px solid var(--border-primary); }
.detail-emoji { font-size: 30px; filter: drop-shadow(0 3px 8px rgba(16,185,129,0.3)); }
.detail-name { font-size: 14px; font-weight: 700; margin: 0 0 3px; color: var(--text-primary); }
.detail-meta { display: flex; gap: 5px; align-items: center; }
.detail-type-badge { font-size: 9px; padding: 1px 6px; border-radius: 5px; background: var(--purple-bg); color: var(--purple-text); font-weight: 600; }
.detail-status { font-size: 9px; color: var(--text-muted); }
.detail-status.ready { color: var(--accent); }
.detail-section { margin-bottom: 10px; padding: 0 4px; }
.detail-label { font-size: 9px; font-weight: 600; color: var(--text-muted); margin-bottom: 2px; text-transform: uppercase; letter-spacing: 0.5px; }
.detail-value { font-size: 11px; color: var(--text-secondary); line-height: 1.5; }
.detail-value.mono { font-family: 'JetBrains Mono', monospace; font-size: 10px; color: var(--text-tertiary); }
.detail-files { display: flex; flex-wrap: wrap; gap: 3px; }
.file-tag { font-size: 9px; padding: 2px 6px; border-radius: 3px; background: var(--bg-input); color: var(--text-tertiary); border: 1px solid var(--border-primary); cursor: pointer; transition: all 0.15s; }
.file-tag:hover { background: var(--accent-bg); color: var(--accent-light); }
.detail-stats { display: flex; gap: 14px; }
.stat-item { font-size: 11px; color: var(--text-tertiary); }
.stat-num { font-weight: 700; color: var(--accent-light); font-size: 14px; margin-right: 3px; }

/* ═══ 第3列: 消息区 ═══ */
.chat-panel { flex: 1; display: flex; flex-direction: column; overflow: hidden; min-width: 340px; }

.welcome-screen { flex: 1; display: flex; align-items: center; justify-content: center; }
.welcome-content { text-align: center; max-width: 400px; }
.welcome-emoji { font-size: 44px; margin-bottom: 8px; filter: drop-shadow(0 6px 16px rgba(16,185,129,0.4)); animation: float 3s ease-in-out infinite; }
@keyframes float { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-6px)} }
.welcome-title { font-size: 20px; font-weight: 800; margin: 0 0 6px; background: linear-gradient(135deg,var(--accent),var(--accent-light),#6ee7b7); -webkit-background-clip:text; -webkit-text-fill-color:transparent; background-clip:text; }
.welcome-greeting { font-size: 12px; color: var(--text-muted); line-height: 1.8; margin: 0 0 16px; white-space: pre-line; }
.welcome-hints { display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }
.hint-chip { padding: 5px 10px; border-radius: 7px; border: 1px solid var(--border-primary); background: var(--bg-input); color: var(--text-secondary); font-size: 11px; cursor: pointer; transition: all 0.2s; }
.hint-chip:hover { background: var(--accent-bg); border-color: var(--border-active); color: var(--accent-light); transform: translateY(-1px); }

.message-list { flex: 1; overflow-y: auto; padding: 14px; display: flex; flex-direction: column; gap: 10px; }
.msg-row { display: flex; gap: 7px; max-width: 92%; animation: msgIn 0.3s ease-out; }
@keyframes msgIn { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:translateY(0)} }
.msg-user { align-self: flex-end; flex-direction: row-reverse; }
.msg-assistant { align-self: flex-start; }
.msg-avatar { width: 26px; height: 26px; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 13px; flex-shrink: 0; }
.avatar-user { background: var(--avatar-user-bg); }
.avatar-assistant { background: var(--avatar-assistant-bg); }
.msg-body { flex: 1; min-width: 0; }
.msg-header { display: flex; align-items: center; gap: 4px; margin-bottom: 2px; }
.msg-role { font-size: 10px; font-weight: 600; color: var(--text-tertiary); }
.msg-time { font-size: 9px; color: var(--text-faint); }
.msg-content { padding: 7px 11px; border-radius: 9px; font-size: 12px; line-height: 1.7; }
.msg-user .msg-content { background: var(--msg-user-bg); border: 1px solid var(--msg-user-border); color: var(--text-primary); }
.msg-assistant .msg-content { background: var(--msg-assistant-bg); border: 1px solid var(--msg-assistant-border); color: var(--text-secondary); }
.msg-content :deep(pre) { background: var(--bg-code); padding: 7px; border-radius: 5px; overflow-x: auto; font-size: 10px; margin: 3px 0; }
.msg-content :deep(code) { font-family: 'JetBrains Mono', monospace; font-size: 10px; }
.msg-content :deep(p) { margin: 0 0 3px; } .msg-content :deep(p:last-child) { margin: 0; }
.msg-content :deep(ul),.msg-content :deep(ol) { margin: 3px 0; padding-left: 16px; }

.typing-indicator { display: inline-flex; gap: 3px; margin-left: 5px; }
.typing-indicator span { width: 4px; height: 4px; border-radius: 50%; background: var(--accent-light); animation: td 1.4s ease-in-out infinite; }
.typing-indicator span:nth-child(2) { animation-delay: 0.2s; } .typing-indicator span:nth-child(3) { animation-delay: 0.4s; }
@keyframes td { 0%,80%,100%{opacity:0.3;transform:scale(0.8)} 40%{opacity:1;transform:scale(1.2)} }

.thinking-row { display: flex; align-items: center; gap: 7px; padding: 8px 12px; animation: msgIn 0.3s ease-out; }
.thinking-pulse { width: 7px; height: 7px; border-radius: 50%; background: var(--accent-light); animation: pulse 1.5s ease-in-out infinite; flex-shrink: 0; }
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.4} }
.thinking-text { font-size: 11px; color: var(--text-muted); }

.thinking-block { margin: 0 12px; animation: msgIn 0.3s ease-out; }
.thinking-header { display: flex; align-items: center; gap: 4px; padding: 4px 8px; border-radius: 5px 5px 0 0; background: var(--accent-bg); border: 1px solid var(--border-active); border-bottom: none; cursor: pointer; user-select: none; }
.thinking-label { font-size: 10px; color: var(--accent-light); flex: 1; }
.thinking-toggle { font-size: 9px; color: var(--text-faint); }
.thinking-content { max-height: 120px; overflow-y: auto; padding: 5px 8px; font-size: 10px; line-height: 1.5; color: var(--text-muted); font-family: 'JetBrains Mono', monospace; white-space: pre-wrap; background: var(--accent-bg); border: 1px solid var(--border-active); border-radius: 0 0 5px 5px; word-break: break-word; }

.chat-input-area { padding: 8px 14px 12px; border-top: 1px solid var(--border-primary); }
.input-box { display: flex; align-items: flex-end; gap: 6px; padding: 7px 10px; border-radius: 10px; background: var(--bg-input); border: 1px solid var(--border-primary); transition: all 0.2s; }
.input-box.focused { border-color: var(--border-active); box-shadow: 0 0 0 2px var(--accent-bg); background: var(--bg-input-focus); }
.msg-textarea { flex: 1; border: none; outline: none; background: transparent; color: var(--text-primary); font-size: 12px; line-height: 1.5; resize: none; font-family: inherit; max-height: 120px; }
.msg-textarea::placeholder { color: var(--text-faint); }
.send-btn { width: 28px; height: 28px; border-radius: 7px; border: none; font-size: 12px; cursor: pointer; transition: all 0.2s; flex-shrink: 0; background: var(--bg-input); color: var(--text-muted); }
.send-btn.ready { background: linear-gradient(135deg,var(--accent),var(--accent-light)); color: #fff; box-shadow: 0 3px 10px rgba(16,185,129,0.3); }
.send-btn.ready:hover { transform: scale(1.05); }
.input-hint { margin-top: 2px; font-size: 9px; color: var(--text-faint); text-align: center; }

/* ═══ 第4列: ACP / 预览 ═══ */
.acp-panel {
  width: 280px; min-width: 240px; border-left: 1px solid var(--border-primary);
  background: var(--bg-overlay); display: flex; flex-direction: column; overflow: hidden;
}
.acp-count { background: var(--purple-bg); color: var(--purple-text); padding: 1px 6px; border-radius: 8px; font-size: 9px; font-weight: 600; }
.acp-list { flex: 1; overflow-y: auto; padding: 6px; display: flex; flex-direction: column; gap: 5px; }
.acp-card { border-radius: 7px; border: 1px solid rgba(139,92,246,0.2); background: rgba(139,92,246,0.04); overflow: hidden; }
.acp-card-header { display: flex; align-items: center; gap: 5px; padding: 5px 8px; font-size: 10px; font-weight: 600; color: var(--text-tertiary); background: var(--bg-surface); }
.badge-live { font-size: 7px; font-weight: 700; padding: 1px 4px; border-radius: 3px; background: rgba(59,130,246,0.2); color: var(--blue-text); animation: pulse 1.5s ease-in-out infinite; text-transform: uppercase; }
.acp-log-stream { max-height: 500px; overflow-y: auto; background: var(--bg-code); font-family: 'JetBrains Mono', 'Menlo', monospace; }
.acp-event-line { padding: 2px 6px; font-size: 10px; line-height: 1.4; border-bottom: 1px solid var(--border-primary); display: flex; gap: 4px; align-items: flex-start; }
.acp-icon { flex-shrink: 0; width: 13px; text-align: center; }
.acp-text { word-break: break-all; white-space: pre-wrap; color: var(--text-tertiary); }
.acp-tool .acp-text { color: var(--cyan-text); font-weight: 600; }
.acp-input .acp-text { color: var(--yellow-text); }
.acp-result .acp-text { color: var(--green-text); }
.acp-cost .acp-text { color: var(--purple-text); font-weight: 500; }
.acp-raw .acp-text { color: var(--text-faint); }
.acp-empty { text-align: center; padding: 30px 10px; color: var(--text-faint); font-size: 10px; line-height: 1.8; }

.sub-log-card { border-radius: 7px; border: 1px solid var(--border-primary); background: var(--bg-surface); overflow: hidden; }
.sub-log-card.running { border-color: rgba(59,130,246,0.3); }
.sub-log-card.success { border-color: rgba(16,185,129,0.2); }
.sub-log-card.error { border-color: rgba(239,68,68,0.3); }
.sub-log-card-header { display: flex; align-items: center; gap: 4px; padding: 5px 7px; cursor: pointer; user-select: none; background: var(--bg-surface); transition: background 0.15s; }
.sub-log-card-header:hover { background: var(--bg-surface-hover); }
.sub-log-icon { font-size: 11px; }
.sub-log-agent { font-size: 10px; font-weight: 600; color: var(--text-secondary); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sub-log-toggle { font-size: 8px; color: var(--text-faint); }
.sub-log-content { max-height: 200px; overflow-y: auto; padding: 5px 7px; font-size: 10px; line-height: 1.4; color: var(--text-muted); background: var(--bg-code); white-space: pre-wrap; word-wrap: break-word; border-top: 1px solid var(--border-primary); }
.sub-log-content.terminal { font-family: 'JetBrains Mono', 'Menlo', monospace; }

/* File tree (detail mode col 3) */
.file-tree { font-size: 11px; }

/* Preview (detail mode col 4) */
.preview-code { font-family: 'JetBrains Mono', 'Menlo', monospace; font-size: 11px; line-height: 1.6; color: var(--text-secondary); white-space: pre-wrap; word-break: break-all; margin: 0; padding: 4px; }

/* Editor */
.editor-scroll { display: flex; flex-direction: column; flex: 1; padding: 0 !important; }
.editor-textarea {
  flex: 1; width: 100%; border: none; outline: none; resize: none;
  background: var(--bg-code); color: var(--text-secondary);
  font-family: 'JetBrains Mono', monospace; font-size: 11px;
  line-height: 1.6; padding: 10px; box-sizing: border-box;
  tab-size: 2;
}
.editor-textarea:focus { background: var(--bg-input-focus); }
.editor-actions { display: flex; align-items: center; gap: 4px; }
.dirty-badge {
  font-size: 8px; padding: 1px 5px; border-radius: 4px;
  background: rgba(251,191,36,0.15); color: var(--yellow-text); font-weight: 600;
}
.editor-btn {
  border: none; padding: 2px 7px; border-radius: 4px; font-size: 10px;
  cursor: pointer; transition: all 0.15s; font-weight: 600;
}
.reset-btn { background: var(--bg-input); color: var(--text-muted); }
.reset-btn:hover { background: var(--bg-surface-hover); }
.save-btn { background: var(--accent); color: #fff; }
.save-btn:hover { box-shadow: 0 2px 8px rgba(16,185,129,0.3); }
</style>