AgentChat.vue 72.3 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 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
<template>
  <div class="agent-chat-page">
    <AppNav />
    <div class="agent-chat-layout">

      <!-- 第1列: Agent 列表 (始终可见) -->
      <aside class="agent-sidebar">
        <div class="col-header">{{ $route.params.id ? '🏢 Agents' : '💻 System Agents' }}</div>
        <input
          v-model="agentSearchQuery"
          class="agent-search-input"
          type="text"
          placeholder="🔍 搜索 Agent..."
        />
        <div class="pinned-box" v-if="pinnedAgentsFlat.length">
          <div
            v-for="a in pinnedAgentsFlat" :key="a.id"
            class="agent-card" :class="{ active: agentId === a.id }"
            :title="a.name"
            @click="agentId = a.id; switchAgent()"
          >
            <span class="agent-card-emoji">{{ a.emoji || '🤖' }}</span>
            <div class="agent-card-info" style="flex:1;">
              <div style="display:flex; justify-content:space-between; align-items:center;">
                <div class="agent-card-name" style="flex:1;">
                  {{ a.name }}
                  <span v-if="a.name !== a.id" class="agent-card-id" style="margin-left:4px; font-weight:normal; font-family:monospace; opacity:0.55;" :title="a.id">{{ a.id }}</span>
                  <span class="agent-card-type" style="margin-left:4px; font-weight:normal;">{{ a.type }}</span>
                </div>
                <div class="agent-card-time" v-if="a.lastActiveAt">{{ formatTime(a.lastActiveAt) }}</div>
              </div>
              <div class="agent-card-msg" :title="a.lastMessage" v-if="a.lastMessage" style="margin-top:2px;">{{ a.lastMessage }}</div>
            </div>
            <button class="agent-card-menu-btn" @click.stop="toggleAgentMenu(a.id, $event)">⋯</button>
            <div v-if="openAgentMenuId === a.id" class="agent-card-menu" @click.stop>
              <div class="agent-card-menu-item" @click="togglePin(a)">{{ a.type === 'master' ? '🔒 常驻置顶' : '📌 取消置顶' }}</div>
            </div>
          </div>
        </div>
        <div class="agent-list">
          <template v-for="(group, compId) in groupedAgents" :key="compId">
            <div class="agent-group-title" v-if="$route.params.id">{{ compId === 'system' ? '💻 系统 Agent' : `🏢 ${compId}` }}</div>
            <div
              v-for="a in group.rest" :key="a.id"
              class="agent-card" :class="{ active: agentId === a.id }"
              :title="a.name"
              @click="agentId = a.id; switchAgent()"
            >
              <span class="agent-card-emoji">{{ a.emoji || '🤖' }}</span>
              <div class="agent-card-info" style="flex:1;">
                <div style="display:flex; justify-content:space-between; align-items:center;">
                  <div class="agent-card-name" style="flex:1;">
                    {{ a.name }}
                    <span v-if="a.name !== a.id" class="agent-card-id" style="margin-left:4px; font-weight:normal; font-family:monospace; opacity:0.55;" :title="a.id">{{ a.id }}</span>
                    <span class="agent-card-type" style="margin-left:4px; font-weight:normal;">{{ a.type }}</span>
                  </div>
                  <div class="agent-card-time" v-if="a.lastActiveAt">{{ formatTime(a.lastActiveAt) }}</div>
                </div>
                <div class="agent-card-msg" :title="a.lastMessage" v-if="a.lastMessage" style="margin-top:2px;">{{ a.lastMessage }}</div>
              </div>
              <button class="agent-card-menu-btn" @click.stop="toggleAgentMenu(a.id, $event)">⋯</button>
              <div v-if="openAgentMenuId === a.id" class="agent-card-menu" @click.stop>
                <div class="agent-card-menu-item" @click="togglePin(a)">📌 置顶</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-filter-bar">
            <button v-for="f in convFilterOptions" :key="f.key" class="conv-filter-btn" :class="{ active: convFilter === f.key }" @click="convFilter = f.key">{{ f.label }} <span class="conv-filter-count">{{ convFilterCount(f.key) }}</span></button>
          </div>
          <div class="conv-list">
            <div
              v-for="conv in filteredConversations"
              :key="conv.conversationId || conv.id"
              class="conv-card"
              :class="{ active: chatState.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-type-badge" :class="'ctype-' + getConvType(conv.conversationId || conv.id)">{{ getConvTypeLabel(conv.conversationId || conv.id) }}</span>
                <span class="conv-time">{{ formatTime(conv.updatedAt) }}</span>
                <span class="conv-count">{{ conv.messageCount || conv.stats?.messageCount || 0 }} 条</span>
              </div>
            </div>
            <div v-if="filteredConversations.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="chatState.messages.length === 0 && !chatState.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">
            <template v-for="(msg, idx) in chatState.messages" :key="idx">
              <div v-if="msg.role === 'divider'" class="msg-divider"><span>{{ msg.content }}</span></div>
              <div v-else 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>
                  <!-- Attachment cards -->
                  <div v-if="msg.attachments && msg.attachments.length" class="msg-attachments">
                    <div v-for="att in msg.attachments" :key="att.name" class="msg-attachment-card">
                      <span class="att-icon">{{ att.type === 'image' ? '🖼️' : '📄' }}</span>
                      <span class="att-name">{{ att.name }}</span>
                      <span class="att-size">{{ formatFileSize(att.size) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </template>
            <div v-if="chatState.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(chatState.streamContent)"></div>
              </div>
            </div>
            <div v-if="chatState.sending && chatState.thinkingContent" class="thinking-block">
              <div class="thinking-header" @click="chatState.showThinking = !chatState.showThinking">
                <div class="thinking-pulse"></div>
                <span class="thinking-label">{{ chatState.streaming ? '💭 思考完成' : '💭 思考中...' }}</span>
                <span class="thinking-toggle">{{ chatState.showThinking ? '▼' : '▶' }}</span>
              </div>
              <div v-if="chatState.showThinking" class="thinking-content">{{ chatState.thinkingContent }}</div>
            </div>
            <div v-if="chatState.sending && !chatState.streaming && !chatState.thinkingContent" class="thinking-row">
              <div class="thinking-pulse"></div>
              <span class="thinking-text">{{ chatState.thinkingText }}</span>
            </div>
          </div>
          <div class="chat-input-area" @dragover.prevent="dragOver = true" @dragleave.prevent="dragOver = false" @drop.prevent="handleDrop">
            <!-- Drag overlay -->
            <div v-if="dragOver" class="drag-overlay">
              <div class="drag-overlay-inner">📎 拖放文件到这里</div>
            </div>
            <!-- Pending files bar -->
            <div v-if="pendingFiles.length > 0" class="pending-files-bar">
              <div class="pending-file" v-for="(f, i) in pendingFiles" :key="i">
                <span class="pending-file-icon">{{ f.type === 'image' ? '🖼️' : '📄' }}</span>
                <span class="pending-file-name" :title="f.name">{{ f.name }}</span>
                <span class="pending-file-size">{{ formatFileSize(f.size) }}</span>
                <button class="pending-file-remove" @click="removePendingFile(i)">✕</button>
              </div>
            </div>
            <!-- Uploaded files indicator -->
            <div v-if="uploadedFiles.length > 0 && pendingFiles.length === 0" class="uploaded-files-bar">
              <span class="uploaded-files-label">📎 {{ uploadedFiles.length }} 个附件</span>
              <span v-for="f in uploadedFiles.slice(0, 3)" :key="f.name" class="uploaded-file-tag">{{ f.name }}</span>
              <span v-if="uploadedFiles.length > 3" class="uploaded-file-tag more">+{{ uploadedFiles.length - 3 }}</span>
            </div>
            <!-- sending 态下 stop 迟迟没确认清理完成时的兜底提示(40 号文档方案二) -->
            <div v-if="chatState.pendingForceSend" class="force-send-bar">
              <span>上一条还在收尾…</span>
              <button class="force-send-btn" @click="handleForceSend">强制发送</button>
            </div>
            <div class="input-box" :class="{ focused: inputFocused }">
              <button class="attach-btn" @click="triggerFileInput" title="上传文件">📎</button>
              <input type="file" ref="fileInputRef" multiple style="display:none" @change="handleFileSelect" />
              <textarea ref="inputRef" v-model="inputText" :placeholder="chatState.sending ? '输入新消息可打断当前回复...' : '跟 ' + agentInfo.name + ' 对话...'" class="msg-textarea" rows="1" @keydown="handleKeydown" @focus="inputFocused = true" @blur="inputFocused = false" @input="autoResize" @paste="handlePaste"></textarea>
              <button v-if="chatState.sending" class="send-btn stop-btn" title="仅停止,不发送新消息" @click="handleStop">⏹</button>
              <button v-if="chatState.sending" class="send-btn interrupt-btn" :class="{ ready: inputText.trim() || pendingFiles.length }" :disabled="(!inputText.trim() && !pendingFiles.length) || chatState.interrupting" title="发送并打断当前回复" @click="handleInterruptAndSend">⤴</button>
              <button v-else class="send-btn" :class="{ ready: (inputText.trim() || pendingFiles.length) && !chatState.sending }" :disabled="!inputText.trim() && !pendingFiles.length" @click="handleSend">➤</button>
            </div>
            <div class="input-hint">Shift+Enter 换行 · {{ chatState.messages.length }} 条消息<template v-if="pendingFiles.length"> · {{ pendingFiles.length }} 个待上传文件</template><template v-if="uploadedFiles.length"> · 📎 {{ uploadedFiles.length }} 个附件</template></div>
          </div>
        </section>

        <!-- 第4列: ACP 事件 -->
        <aside class="acp-panel">
          <div class="col-header"><span>⚡ ACP Events</span><span class="acp-count">{{ chatState.acpLog.length }}</span></div>
          <div class="acp-list">
            <div v-if="chatState.acpLog.length > 0" class="acp-card">
              <div class="acp-card-header"><span>⚡ Event Stream</span><span v-if="chatState.sending" class="badge-live">LIVE</span></div>
              <div class="acp-log-stream">
                <div v-for="(evt, i) in chatState.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 chatState.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 chatState.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="chatState.acpLog.length === 0 && chatState.subLogList.length === 0 && Object.keys(chatState.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">心跳设置 (Heartbeat)</div>
              <div class="detail-value" v-if="agentInfo.heartbeat">
                <label style="display:flex; align-items:center; gap:8px; cursor:pointer; margin-bottom: 6px;">
                  <input type="checkbox" v-model="agentInfo.heartbeat.enabled" @change="updateHeartbeat" />
                  开启心跳轮询
                </label>
                <div style="display:flex; align-items:center; gap:8px;">
                  间隔时间: 
                  <input type="number" v-model.number="agentInfo.heartbeat.intervalMinutes" @change="updateHeartbeat" style="width: 60px; padding: 2px 4px; border-radius: 4px; border: 1px solid var(--border-primary); background: var(--bg-input); color: var(--text-primary);" /> 分钟
                </div>
              </div>
            </div>

            <div class="detail-section">
              <div class="detail-label">定时任务 (Cron Jobs) <button @click="addCron" style="float:right; background:none; border:none; color:var(--accent); cursor:pointer; font-weight: 600;">+ 新增</button></div>
              <div class="detail-value" v-if="agentInfo.cron">
                <div v-if="agentInfo.cron.length === 0" style="color:var(--text-faint); font-style:italic; font-size:11px;">无定时任务</div>
                <div v-for="(job, index) in agentInfo.cron" :key="index" style="margin-bottom:8px; padding: 6px; background:var(--bg-overlay); border-radius:4px; border: 1px solid var(--border-primary); font-size:11px;">
                  <div style="display:flex; justify-content:space-between; align-items: center; margin-bottom: 4px;">
                    <input v-model="job.schedule" placeholder="cron表达式 e.g. 0 8 * * *" style="width:120px; padding:2px 4px; border:1px solid var(--border-primary); border-radius:2px; background:var(--bg-input); color:var(--text-primary);" @change="updateCron" />
                    <button @click="removeCron(index)" style="background:none; border:none; color:#ef4444; cursor:pointer; font-size:12px;">✖删除</button>
                  </div>
                  <input v-model="job.task" placeholder="任务指令" style="width:100%; box-sizing: border-box; padding:2px 4px; border:1px solid var(--border-primary); border-radius:2px; background:var(--bg-input); color:var(--text-primary); margin-bottom: 4px;" @change="updateCron" />
                  <label style="display:flex; align-items:center; gap:4px; cursor:pointer; color:var(--text-muted);">
                    <input type="checkbox" v-model="job.enabled" @change="updateCron" /> 启用
                  </label>
                </div>
              </div>
            </div>

            <div class="detail-section">
              <div class="detail-label">API 外部调用 Endpoint</div>
              <div class="detail-value mono" style="word-break: break-all; margin-bottom: 8px;">
                {{ getAgentApiUrl(agentId) }}
              </div>
              <button class="action-btn" style="padding: 4px 10px; font-size: 11px; background: rgba(16,185,129,0.1); border: 1px solid rgba(16,185,129,0.3); color: #34d399; border-radius: 4px; cursor: pointer;" @click="copyText(getAgentApiUrl(agentId))">📋 复制 URL</button>
            </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, reactive, computed, nextTick, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppNav from '@/components/AppNav.vue'
import FileNode from '@/components/FileNode.vue'
import { marked } from 'marked'
import { createAgentChatEventHandler, flushTypewriter } from '@/composables/agentChatEvents.js'

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

const PINNED_AGENTS_KEY = 'lemonboss.pinnedAgentIds'
const pinnedAgentIds = ref(new Set(JSON.parse(localStorage.getItem(PINNED_AGENTS_KEY) || '[]')))
const openAgentMenuId = ref(null)

function isPinned(a) {
  return a.type === 'master' || pinnedAgentIds.value.has(a.id)
}
function togglePin(a) {
  if (a.type === 'master') return // master 常驻置顶,不可取消
  const next = new Set(pinnedAgentIds.value)
  if (next.has(a.id)) next.delete(a.id)
  else next.add(a.id)
  pinnedAgentIds.value = next
  localStorage.setItem(PINNED_AGENTS_KEY, JSON.stringify([...next]))
  openAgentMenuId.value = null
}
function toggleAgentMenu(id, evt) {
  evt.stopPropagation()
  openAgentMenuId.value = openAgentMenuId.value === id ? null : id
}
function closeAgentMenu() { openAgentMenuId.value = null }
onMounted(() => document.addEventListener('click', closeAgentMenu))
onUnmounted(() => document.removeEventListener('click', closeAgentMenu))

const groupedAgents = computed(() => {
  const q = agentSearchQuery.value.trim().toLowerCase()
  const groups = {}
  agentList.value.forEach(a => {
    const comp = a.companyId || 'system'
    // If we are in a company context, filter out other companies and system agents
    if (route.params.id) {
      if (comp !== route.params.id) return
    } else {
      // If we are in the System Agents context, ONLY show system agents
      if (comp !== 'system') return
    }
    if (q && !(a.name || '').toLowerCase().includes(q) && !(a.id || '').toLowerCase().includes(q)) return

    if (!groups[comp]) groups[comp] = []
    groups[comp].push(a)
  })

  const byRecency = (a, b) => {
    const ta = a.lastActiveAt ? new Date(a.lastActiveAt).getTime() : 0
    const tb = b.lastActiveAt ? new Date(b.lastActiveAt).getTime() : 0
    return tb - ta
  }

  // 每组拆成「置顶区」(master + 用户手动置顶)与「其余」,置顶区单独渲染成
  // 一个跟滚动列表分开的框(见 pinnedAgentsFlat),列表滚动时不会互相干扰
  const result = {}
  Object.keys(groups).forEach(k => {
    const pinned = []
    const rest = []
    groups[k].forEach(a => (isPinned(a) ? pinned : rest).push(a))
    pinned.sort((a, b) => {
      if (a.type === 'master') return -1
      if (b.type === 'master') return 1
      return byRecency(a, b)
    })
    rest.sort(byRecency)
    result[k] = { pinned, rest }
  })

  // 确保 system 永远在最上面排第一
  const sortedKeys = Object.keys(result).sort((a,b) => {
    if (a === 'system') return -1;
    if (b === 'system') return 1;
    return a.localeCompare(b);
  })

  const sortedGroups = {}
  sortedKeys.forEach(k => { sortedGroups[k] = result[k] })
  return sortedGroups
})

const pinnedAgentsFlat = computed(() => {
  const list = []
  Object.values(groupedAgents.value).forEach(g => list.push(...g.pinned))
  return list
})
const activeTab = ref('chat') // 'chat' | 'detail'

// 每个 agent 独立一份聊天态(messages/sending/streaming/思考栏/ACP 面板…),
// 键是 agentId。切换 agent 只是换了 chatState 指向哪个 slice 来渲染,
// 后台的 fetch 读流循环(handleSend/handleEvent) 认准发起时捕获的 agentId 写自己那份,
// 不认"当前选中的 agent 是谁"——这样 A 在流式输出时切去看 B,A 不会被打断,
// B 也不会被 A 的内容/思考栏/等待态污染,回切 A 能看到它这期间的完整进度。
const chatStates = reactive(new Map())
function ensureChatState(id) {
  if (!chatStates.has(id)) {
    chatStates.set(id, {
      messages: [], activeConvId: null,
      sending: false, streaming: false, streamContent: '',
      subAgents: {}, subLogList: [], acpLog: [],
      thinkingText: '🏗️ 启动中...', thinkingContent: '', showThinking: true,
      interrupting: false, pendingForceSend: false,
    })
  }
  return chatStates.get(id)
}
const chatState = computed(() => ensureChatState(agentId.value))

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 convFilter = ref('all')  // default filter to all conversations
const convFilterOptions = [
  { key: 'all', label: '全部' },
  { key: 'user', label: '用户对话' },
  { key: 'callback', label: '回调' },
  { key: 'task', label: '任务' },
  { key: 'train', label: '训练' },
]

function getConvType(convId) {
  if (!convId) return 'user'
  if (convId.startsWith('callback-')) return 'callback'
  if (convId.startsWith('task-') || convId.startsWith('T-')) return 'task'
  if (convId.startsWith('tpl-train-') || convId.startsWith('train-') || convId.startsWith('tpl-gen-')) return 'train'
  return 'user'
}

function getConvTypeLabel(convId) {
  const t = getConvType(convId)
  const map = { user: '💬', callback: '🔙', task: '📨', train: '🎓' }
  return map[t] || '💬'
}

function convFilterCount(key) {
  if (key === 'all') return conversations.value.length
  return conversations.value.filter(c => getConvType(c.conversationId || c.id) === key).length
}

const filteredConversations = computed(() => {
  if (convFilter.value === 'all') return conversations.value
  return conversations.value.filter(c => getConvType(c.conversationId || c.id) === convFilter.value)
})
const inputText = ref('')
const inputFocused = ref(false)
const messageListRef = ref(null)
const inputRef = 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)

// Upload state
const pendingFiles = ref([])   // Files selected but not yet uploaded
const uploadedFiles = ref([])  // Files already uploaded for current conv
const dragOver = ref(false)
const fileInputRef = ref(null)

const IMG_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.bmp'])
function getFileType(name) {
  const ext = '.' + name.split('.').pop().toLowerCase()
  return IMG_EXTS.has(ext) ? 'image' : 'text'
}
function formatFileSize(bytes) {
  if (bytes < 1024) return bytes + 'B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB'
  return (bytes / (1024 * 1024)).toFixed(1) + 'MB'
}

function triggerFileInput() { fileInputRef.value?.click() }

function handleFileSelect(e) {
  const files = Array.from(e.target.files || [])
  addPendingFiles(files)
  e.target.value = '' // reset so same file can be picked again
}

function handleDrop(e) {
  dragOver.value = false
  const files = Array.from(e.dataTransfer?.files || [])
  addPendingFiles(files)
}

function handlePaste(e) {
  const items = e.clipboardData?.items
  if (!items) return
  const files = []
  for (const item of items) {
    if (item.kind === 'file') {
      const f = item.getAsFile()
      if (f) files.push(f)
    }
  }
  if (files.length) addPendingFiles(files)
}

function addPendingFiles(files) {
  for (const f of files) {
    if (f.size > 10 * 1024 * 1024) {
      alert(`文件 "${f.name}" 超过 10MB 限制`)
      continue
    }
    pendingFiles.value.push({ file: f, name: f.name, size: f.size, type: getFileType(f.name) })
  }
}

function removePendingFile(index) {
  pendingFiles.value.splice(index, 1)
}

async function uploadPendingFiles() {
  if (pendingFiles.value.length === 0) return
  const formData = new FormData()
  for (const pf of pendingFiles.value) {
    formData.append('files', pf.file)
  }
  if (chatState.value.activeConvId) {
    formData.append('conversationId', chatState.value.activeConvId)
  }
  try {
    const r = await fetch(`/api/agent/${agentId.value}/upload`, { method: 'POST', body: formData })
    if (r.ok) {
      const data = await r.json()
      // Auto-set convId if server created one
      if (data.conversationId && !chatState.value.activeConvId) {
        chatState.value.activeConvId = data.conversationId
      }
      uploadedFiles.value.push(...(data.uploaded || []))
      pendingFiles.value = []
    } else {
      console.error('Upload failed:', await r.text())
    }
  } catch (e) { console.error('Upload error:', e) }
}

async function loadUploadedFiles() {
  if (!agentId.value || !chatState.value.activeConvId) { uploadedFiles.value = []; return }
  try {
    const r = await fetch(`/api/agent/${agentId.value}/uploads/${chatState.value.activeConvId}`)
    if (r.ok) uploadedFiles.value = await r.json()
    else uploadedFiles.value = []
  } catch { uploadedFiles.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 updateHeartbeat() {
  if (!agentId.value || !agentInfo.value.heartbeat) return
  try {
    await fetch(`/api/agent/${agentId.value}/heartbeat`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(agentInfo.value.heartbeat)
    })
  } catch (e) { console.error('Heartbeat update error:', e) }
}

async function updateCron() {
  if (!agentId.value || !agentInfo.value.cron) return
  try {
    await fetch(`/api/agent/${agentId.value}/cron`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cron: agentInfo.value.cron })
    })
  } catch (e) { console.error('Cron update error:', e) }
}

function addCron() {
  if (!agentInfo.value.cron) agentInfo.value.cron = []
  agentInfo.value.cron.push({ "schedule": "0 8 * * *", "task": "新提醒任务", "enabled": true })
  updateCron()
}

function removeCron(index) {
  if (confirm('确认删除该定时任务?')) {
    agentInfo.value.cron.splice(index, 1)
    updateCron()
  }
}

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
  const st = chatState.value
  try {
    const r = await fetch(`/api/agent/${agentId.value}/conversations/${convId}`)
    if (r.ok) {
      const conv = await r.json()
      st.messages = conv.messages || []
      if (conv.subLogs && conv.subLogs.length > 0) {
        st.subLogList = conv.subLogs.map(l => ({ ...l, collapsed: true }))
      } else { st.subLogList = [] }
    }
  } catch { st.messages = []; st.subLogList = [] }
}

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() {
  const st = chatState.value
  st.activeConvId = null
  st.messages = []
  st.streamContent = ''
  st.subAgents = {}
  st.subLogList = []
  st.acpLog = []
  pendingFiles.value = []
  uploadedFiles.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 }})
  }
}

// 切 agent:不清空目标 agent 已经攒下的后台状态(可能正在生成中,或者刚刚生成完毕
// 还没被看到)——只有它是空闲态时才去定位/刷新它的会话,正在 sending 就原样展示缓存。
async function switchAgent() {
  selectedFile.value = null
  previewContent.value = null
  fileTree.value = null
  const st = chatState.value
  if (route.params.id) {
    router.replace({ params: { id: route.params.id, agentId: agentId.value, convId: st.activeConvId || undefined }})
  } else {
    router.replace({ params: { agentId: agentId.value, convId: st.activeConvId || undefined }})
  }
  await loadAgentInfo()
  await loadConversations()
  if (!st.sending) {
    if (st.activeConvId) {
      await loadConversation(st.activeConvId)
    } else if (filteredConversations.value.length > 0) {
      const firstId = filteredConversations.value[0].conversationId || filteredConversations.value[0].id
      await switchConversation(firstId)
    }
  }
  await loadFileTree()
  scrollToBottom()
}

async function switchConversation(convId) {
  chatState.value.activeConvId = 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)
  await loadUploadedFiles()
  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)
      const st = chatState.value
      if (st.activeConvId === convId) {
        st.activeConvId = null
        st.messages = []
        st.streamContent = ''
        st.subAgents = {}
        st.subLogList = []
        st.acpLog = []
      }
    }
  } catch (e) { console.error('Delete conv error:', e) }
}

function getAgentApiUrl(fullAgentId) {
  if (!fullAgentId) return '';
  let companyId = "system";
  let targetAgentId = fullAgentId;
  const parts = fullAgentId.split(':');
  if (parts.length > 1) {
    companyId = parts[0];
    targetAgentId = parts.slice(1).join(':'); 
  }
  const host = window.location.hostname;
  return `http://${host}:3010/api/open/companies/${companyId}/agents/${targetAgentId}/invoke`;
}

async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);
    alert('✅ URL 已复制到剪贴板');
  } catch (e) {
    console.error(e);
  }
}

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

// requestAgentId 是发起这次发送时的 agent——从这里往下,全部认这个快照,不认
// "用户现在选中的是谁"。这样切走了也不会打断/污染,切回来能看到完整的后台进度。
async function handleSend() {
  const text = inputText.value.trim()
  const requestAgentId = agentId.value
  const st = ensureChatState(requestAgentId)
  if ((!text && pendingFiles.value.length === 0) || st.sending || !requestAgentId) return
  const isCurrent = () => agentId.value === requestAgentId

  // Upload pending files first
  if (pendingFiles.value.length > 0) {
    await uploadPendingFiles()
  }

  const finalText = text || '请处理我上传的文件。'
  const attachments = uploadedFiles.value.length > 0 ? [...uploadedFiles.value] : []
  st.messages.push({ role: 'user', content: finalText, timestamp: new Date().toISOString(), attachments })
  inputText.value = ''
  if (inputRef.value) inputRef.value.style.height = 'auto'
  st.sending = true; st.streaming = false; st.streamContent = ''
  st.subAgents = {}; st.acpLog = []; st.thinkingContent = ''
  st.showThinking = true
  st.thinkingText = `${agentInfo.value.emoji} ${agentInfo.value.name} 思考中...`
  if (isCurrent()) { activeTab.value = 'chat'; scrollToBottom() }

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

  try {
    const r = await fetch(`/api/agent/${requestAgentId}/chat`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message: finalText, conversationId: st.activeConvId }),
    })
    if (!r.ok) {
      // 非 200(比如 429 并发锁冲突)的响应体是普通 JSON,不是 SSE——不能当流读,
      // 否则逐行解析全部匹配不上 event/data 前缀,会静默吞掉、界面上像没回复一样。
      const errBody = await r.json().catch(() => ({}))
      const errText = r.status === 429
        ? `⏳ ${errBody.error || 'Agent 正忙,请稍后重试'}`
        : `❌ 错误 (${r.status}): ${errBody.error || r.statusText}`
      st.messages.push({ role: 'assistant', content: errText, timestamp: new Date().toISOString() })
      return
    }
    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(st, requestAgentId, lastEventType, JSON.parse(line.slice(6))) } catch {}
        }
      }
    }
    flushTypewriter(st) // 流已经读完,剩下排队的字符没必要再演匀速,直接吐光再拼进消息
    if (st.streamContent) {
      st.messages.push({ role: 'assistant', content: st.streamContent, timestamp: new Date().toISOString() })
    }
    if (isCurrent()) await loadConversations()
    if (st.activeConvId) await loadSubLogsFor(requestAgentId, st)
  } catch (err) {
    st.messages.push({ role: 'assistant', content: `❌ 错误: ${err.message}`, timestamp: new Date().toISOString() })
  } finally {
    st.sending = false; st.streaming = false; st.streamContent = ''; st.thinkingContent = ''
  }
}

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

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

// 40 号文档方案二:执行中把已生成的部分内容 + 一条分隔标记落进历史,再当作一轮全新对话
// 重置 sending 相关状态——不依赖"旧的 fetch 循环自己发现流已结束"这件事的时序,
// 保证接下来立刻调用 handleSend() 是安全的(旧循环之后自己走到 finally 时,
// st.streamContent 已经是空的,不会重复 push)。
function finalizeInterruptedTurn(st) {
  flushTypewriter(st)
  if (st.streamContent) {
    st.messages.push({ role: 'assistant', content: st.streamContent, timestamp: new Date().toISOString() })
  }
  st.messages.push({ role: 'divider', content: '已打断上一条回复', timestamp: new Date().toISOString() })
  st.sending = false; st.streaming = false; st.streamContent = ''; st.thinkingContent = ''
}

// sending 态下点发送 = "打断并发送":先中止当前 turn,服务端确认清理完成(cleaned)后
// 再把这条新消息接上;服务端 3 秒还没确认的话不自动强发(避免撞上同 convId 并发的坑),
// 交给用户自己点"强制发送"。
async function handleInterruptAndSend() {
  const st = chatState.value
  if (!inputText.value.trim() && pendingFiles.value.length === 0) return
  if (!st.activeConvId) return handleSend()

  st.interrupting = true
  let cleaned = false
  try {
    const r = await fetch(`/api/agent/${agentId.value}/chat/${st.activeConvId}/stop`, { method: 'POST' })
    const data = await r.json().catch(() => ({}))
    cleaned = !!data.cleaned
  } catch (e) {
    console.error('Interrupt error:', e)
  }
  st.interrupting = false

  if (!cleaned) { st.pendingForceSend = true; return }
  finalizeInterruptedTurn(st)
  await handleSend()
}

function handleForceSend() {
  const st = chatState.value
  st.pendingForceSend = false
  finalizeInterruptedTurn(st)
  handleSend()
}

// st/requestAgentId 是 handleSend 传下来的快照;只有 requestAgentId 仍是当前选中 agent 时
// 才动 DOM(滚动)/URL/全局对话列表——避免把某个后台 agent 的进度"带"到当前正看的页面上。
// 分发逻辑本体已抽到 composables/agentChatEvents.js(40 号文档方案三,便于单独做回归测试)。
function scrollSubLogs() {
  setTimeout(() => { document.querySelectorAll('.sub-log-content').forEach(el => el.scrollTop = el.scrollHeight) }, 50)
}
const handleEvent = createAgentChatEventHandler({
  getCurrentAgentId: () => agentId.value,
  scrollToBottom,
  scrollAcpLog,
  scrollSubLogs,
  onNewConversation(requestAgentId, data, st) {
    if (route.params.id) {
      router.replace({ params: { id: route.params.id, agentId: requestAgentId, convId: data.conversationId } })
    } else {
      router.replace({ params: { agentId: requestAgentId, convId: data.conversationId } })
    }
    const existsInList = conversations.value.some(c => (c.conversationId || c.id) === data.conversationId)
    if (!existsInList) {
      conversations.value.unshift({ conversationId: data.conversationId, title: st.messages.find(m => m.role === 'user')?.content?.slice(0, 50) || '新对话', updatedAt: new Date().toISOString(), messageCount: 1, status: 'running' })
    }
  },
})

function handleKeydown(e) {
  if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
    e.preventDefault()
    chatState.value.sending ? handleInterruptAndSend() : 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(chatState, () => 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) {
    chatState.value.activeConvId = route.params.convId
    await loadConversation(route.params.convId)
    scrollToBottom()
  } else if (filteredConversations.value.length > 0) {
    const firstId = filteredConversations.value[0].conversationId || filteredConversations.value[0].id
    await switchConversation(firstId)
  }
})
</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: 260px; min-width: 220px; border-right: 1px solid var(--border-primary);
  background: var(--bg-overlay); display: flex; flex-direction: column;
}
.agent-search-input {
  margin: 0 6px 6px; padding: 5px 8px; border-radius: 6px;
  border: 1px solid var(--border-primary); background: var(--bg-input);
  color: var(--text-primary); font-size: 11px; box-sizing: border-box;
}
.pinned-box {
  flex-shrink: 0; margin: 0 6px 8px; padding: 4px;
  border: 1px solid var(--border-primary); border-radius: 10px;
  background: var(--bg-surface);
}
.pinned-box .agent-card { margin-bottom: 2px; }
.pinned-box .agent-card:last-child { margin-bottom: 0; }
.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; position: relative;
  padding: 7px 10px; border-radius: 8px; cursor: pointer;
  transition: all 0.15s; margin-bottom: 2px; border: 1px solid transparent;
  background: var(--bg-primary);
}
.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); white-space: normal; word-break: break-word; }
.agent-card-type { font-size: 9px; color: var(--text-faint); }
.agent-card-time { font-size: 9px; color: var(--text-faint); white-space: nowrap; margin-left: 6px; }
.agent-card-msg { font-size: 10px; color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }
.agent-card-menu-btn {
  flex-shrink: 0; width: 18px; height: 18px; padding: 0; border: none; border-radius: 4px;
  background: transparent; color: var(--text-faint); font-size: 13px; line-height: 1; cursor: pointer;
  display: flex; align-items: center; justify-content: center;
}
.agent-card-menu-btn:hover { background: var(--bg-surface-hover); color: var(--text-secondary); }
.agent-card-menu {
  position: absolute; top: 100%; right: 8px; z-index: 10; min-width: 96px;
  background: var(--bg-primary); border: 1px solid var(--border-primary); border-radius: 6px;
  box-shadow: var(--shadow-lg); padding: 4px;
}
.agent-card-menu-item {
  padding: 5px 8px; border-radius: 4px; font-size: 11px; color: var(--text-secondary);
  white-space: nowrap; cursor: pointer;
}
.agent-card-menu-item:hover { background: var(--accent-bg); }

/* ═══ 第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 filter bar */
.conv-filter-bar {
  display: flex; gap: 2px; padding: 4px 6px;
  border-bottom: 1px solid var(--border-primary);
  flex-shrink: 0;
}
.conv-filter-btn {
  flex: 1; padding: 3px 0; border: none; border-radius: 5px;
  background: transparent; color: var(--text-muted); font-size: 10px; font-weight: 600;
  cursor: pointer; transition: all 0.15s; white-space: nowrap;
  display: flex; align-items: center; justify-content: center; gap: 2px;
}
.conv-filter-btn:hover { background: var(--bg-surface-hover); color: var(--text-secondary); }
.conv-filter-btn.active { background: var(--accent-bg); color: var(--accent); }
.conv-filter-count {
  font-size: 9px; font-weight: 500; color: var(--text-faint);
  background: var(--bg-overlay); padding: 0 4px; border-radius: 6px; min-width: 14px; text-align: center;
}
.conv-filter-btn.active .conv-filter-count { background: rgba(16,185,129,0.15); color: var(--accent); }

/* Conv type badge */
.conv-type-badge { font-size: 10px; flex-shrink: 0; }

.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; }
/* sending 态下:Stop(纯中止)与 interrupt-btn(打断并发送)视觉上要能一眼区分开 */
.interrupt-btn.ready { background: linear-gradient(135deg,#f59e0b,#fbbf24); color: #fff; box-shadow: 0 3px 10px rgba(245,158,11,0.35); }
.interrupt-btn.ready:hover { transform: scale(1.05); }
.force-send-bar { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 6px; padding: 6px 10px; font-size: 11px; color: var(--text-muted); background: var(--accent-bg); border: 1px solid var(--border-active); border-radius: 7px; }
.force-send-btn { border: none; border-radius: 6px; padding: 4px 10px; font-size: 11px; cursor: pointer; background: #f59e0b; color: #fff; }
.force-send-btn:hover { opacity: 0.9; }
.msg-divider { display: flex; align-items: center; gap: 8px; margin: 10px 0; font-size: 10px; color: var(--text-faint); }
.msg-divider::before, .msg-divider::after { content: ''; flex: 1; height: 1px; background: var(--border-primary); }

/* ═══ 第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); }

/* ═══ File Upload ═══ */
.attach-btn {
  background: none; border: none; cursor: pointer; font-size: 18px; padding: 4px 8px;
  border-radius: 6px; transition: background 0.15s; flex-shrink: 0;
}
.attach-btn:hover { background: var(--bg-surface-hover); }

.pending-files-bar {
  display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 12px;
  border-bottom: 1px solid var(--border-primary); background: var(--bg-surface);
  border-radius: 10px 10px 0 0;
}
.pending-file {
  display: flex; align-items: center; gap: 4px; padding: 4px 8px;
  background: var(--accent-bg); border-radius: 6px; font-size: 11px;
  border: 1px solid var(--border-primary);
}
.pending-file-icon { font-size: 13px; }
.pending-file-name {
  max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  color: var(--text-primary); font-weight: 600;
}
.pending-file-size { color: var(--text-muted); font-size: 10px; }
.pending-file-remove {
  background: none; border: none; cursor: pointer; color: var(--text-muted);
  font-size: 12px; padding: 0 2px; border-radius: 3px; line-height: 1;
}
.pending-file-remove:hover { color: #ef4444; background: rgba(239,68,68,0.1); }

.uploaded-files-bar {
  display: flex; align-items: center; gap: 6px; padding: 6px 12px;
  font-size: 11px; color: var(--text-muted); border-bottom: 1px solid var(--border-primary);
  background: var(--bg-surface); border-radius: 10px 10px 0 0;
}
.uploaded-files-label { font-weight: 600; }
.uploaded-file-tag {
  padding: 2px 6px; border-radius: 4px; background: var(--bg-overlay);
  border: 1px solid var(--border-primary); font-size: 10px; color: var(--text-secondary);
  max-width: 80px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.uploaded-file-tag.more { background: var(--accent-bg); color: var(--accent-light); }

.drag-overlay {
  position: absolute; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center;
  background: rgba(16,185,129,0.08); border: 2px dashed var(--accent); border-radius: 12px;
}
.drag-overlay-inner {
  font-size: 18px; font-weight: 700; color: var(--accent); padding: 20px 40px;
  background: var(--bg-primary); border-radius: 12px; box-shadow: var(--shadow-lg);
}

.chat-input-area { position: relative; }

/* Attachment cards in messages */
.msg-attachments { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
.msg-attachment-card {
  display: flex; align-items: center; gap: 5px; padding: 5px 10px;
  background: var(--bg-surface); border: 1px solid var(--border-primary);
  border-radius: 8px; font-size: 11px; cursor: default; transition: background 0.15s;
}
.msg-attachment-card:hover { background: var(--bg-surface-hover); }
.att-icon { font-size: 14px; }
.att-name { font-weight: 600; color: var(--text-primary); max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.att-size { color: var(--text-muted); font-size: 10px; }
</style>