AgentPanelBody.vue 46.2 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 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
<template>
  <div class="agent-panel-body">
    <!-- 消息列表 -->
    <div class="messages-container" ref="messagesContainerRef">
      <div class="messages-list">
        <!-- Ask 模式消息列表 -->
        <template v-if="chatMode === 'ask'">
        <div
          v-for="(chatItem, index) in messages"
          :key="chatItem.questionId || index"
          class="chat-item"
        >
          <!-- 用户问题 -->
          <div class="user-question">
            <div class="message-body-question">{{ chatItem.question }}</div>
            <div class="message-actions-user">
              <button
                class="action-btn"
                :title="t('chat.copy')"
                @click="handleCopy(chatItem.question)"
              >
                <img src="/fuzhi.svg" alt="复制" class="icon-svg" />
              </button>
            </div>
          </div>

          <!-- AI回答 -->
          <div
            v-for="answer in chatItem.answers"
            :key="answer.id"
            class="ai-answer"
          >
            <!-- AI思考状态 -->
            <div v-if="answer.status === 'thinking'" class="ai-thinking">
              <div class="thinking-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
              <span class="thinking-text">{{
                t("agent.thinking") || "AI正在思考中..."
              }}</span>
            </div>

            <!-- 打字机效果显示回答内容 -->
            <div
              v-else-if="answer.status === 'typing'"
              class="message-body-answer typewriter"
            >
              <!-- 使用增强版 MarkdownPreview 渲染(支持完整 Markdown + KaTeX) -->
              <MarkdownPreview
                :content="getTypingDisplayContent(answer)"
                :is-streaming="true"
                model="external"
              />
            </div>

            <!-- 错误状态 -->
            <div
              v-else-if="answer.status === 'error'"
              class="message-body-answer error-message"
            >
              <el-icon><WarningFilled /></el-icon>
              <span>{{ answer.answerContent }}</span>
              <el-icon
                class="retry-icon"
                @click="handleRetry(chatItem)"
                :title="t('chat.retrySend')"
              >
                <RefreshRight />
              </el-icon>
            </div>

            <!-- 正常显示回答内容 -->
            <div v-else class="message-body-answer">
              <MarkdownPreview
                :content="answer.answerContent"
                :is-streaming="false"
                model="external"
              />
              <div
                class="message-actions-answer"
                v-if="
                  answer.answerContent &&
                  !['thinking', 'typing', 'error'].includes(answer.status || '')
                "
              >
                <button
                  class="action-btn"
                  :class="{ disabled: !isAnswerCompleted(answer) }"
                  :title="t('chat.generateDocument')"
                  @click="handleSaveAndEdit(chatItem, answer)"
                >
                  <img src="/bianji.svg" alt="生成文档并编辑" class="icon-svg" />
                </button>
                <button
                  class="action-btn"
                  :title="t('chat.copy')"
                  @click="handleCopyAnswer(answer)"
                >
                  <img src="/fuzhi.svg" alt="复制" class="icon-svg" />
                </button>
              </div>
            </div>
          </div>
        </div>
        </template>

        <!-- Agent 模式消息列表 -->
        <template v-else>
          <div
            v-for="(message, index) in messages"
            :key="message.id || index"
            class="chat-item"
          >
            <!-- 用户问题 -->
            <div v-if="message.role === 'user'" class="user-question">
              <div
                v-if="message.attachedFiles && message.attachedFiles.length > 0"
                class="user-attached-files"
              >
                <CodexUserAttachedFileCard
                  v-for="(af, ai) in message.attachedFiles"
                  :key="`${af.id}-${ai}`"
                  :id="af.id"
                  :name="af.name || `file-${af.id}`"
                  :file-path="af.filePath"
                  :type="af.type"
                />
              </div>
              <div class="message-body-question">{{ message.content }}</div>
              <div class="message-actions-user">
                <button
                  class="action-btn"
                  :title="t('chat.copy')"
                  @click="handleCopy(message.content)"
                >
                  <img src="/fuzhi.svg" alt="复制" class="icon-svg" />
                </button>
              </div>
            </div>

            <!-- AI回答 -->
            <div v-else-if="message.role === 'assistant'" class="ai-answer">
              <!-- AI思考状态 -->
              <div v-if="message.status === 'pending'" class="ai-thinking">
                <div class="thinking-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <span class="thinking-text">{{
                  t("agent.thinking") || "AI正在思考中..."
                }}</span>
              </div>

              <!-- 打字机效果显示回答内容 -->
              <div
                v-else-if="message.status === 'streaming' && message.isStreaming"
                class="message-body-answer typewriter"
              >
                <MarkdownPreview
                  :content="getTypingDisplayContent(message)"
                  :is-streaming="true"
                  model="external"
                />
              </div>

              <!-- 错误状态 -->
              <div
                v-else-if="message.status === 'error'"
                class="message-body-answer error-message"
              >
                <el-icon><WarningFilled /></el-icon>
                <span>{{ message.error || message.content }}</span>
                <el-icon
                  class="retry-icon"
                  @click="handleRetry(message)"
                  :title="t('chat.retrySend')"
                >
                  <RefreshRight />
                </el-icon>
              </div>

              <!-- 待审批状态 -->
              <div
                v-else-if="message.pendingApproval"
                class="message-body-answer approval-pending"
              >
                <div class="approval-content">
                  <div class="approval-header">
                    <el-icon><Warning /></el-icon>
                    <span>需要审批</span>
                  </div>
                  <div class="approval-body">
                    <div v-if="message.pendingApproval.type === 'command'">
                      <p><strong>命令:</strong> {{ message.pendingApproval.command }}</p>
                      <p v-if="message.pendingApproval.description">{{ message.pendingApproval.description }}</p>
                    </div>
                    <div v-else-if="message.pendingApproval.type === 'patch'">
                      <p><strong>文件:</strong> {{ message.pendingApproval.filePath }}</p>
                      <p v-if="message.pendingApproval.changes">
                        <strong>变更:</strong>
                        <pre>{{ message.pendingApproval.changes }}</pre>
                      </p>
                    </div>
                  </div>
                  <div class="approval-actions">
                    <el-button
                      size="small"
                      type="success"
                      @click="handleApprove(message, 'approved')"
                    >
                      批准
                    </el-button>
                    <el-button
                      size="small"
                      type="danger"
                      @click="handleApprove(message, 'denied')"
                    >
                      拒绝
                    </el-button>
                  </div>
                </div>
              </div>

              <!-- 正常显示回答内容 -->
              <div v-else class="message-body-answer">
                <MarkdownPreview
                  :content="message.content"
                  :is-streaming="false"
                  model="external"
                />
                <div
                  class="message-actions-answer"
                  v-if="
                    message.content &&
                    !['pending', 'streaming', 'error'].includes(message.status || '')
                  "
                >
                  <button
                    class="action-btn"
                    :class="{ disabled: !isMessageCompleted(message) }"
                    :title="t('chat.generateDocument')"
                    @click="handleSaveAndEditAgent(message)"
                  >
                    <img src="/bianji.svg" alt="生成文档并编辑" class="icon-svg" />
                  </button>
                  <button
                    class="action-btn"
                    :title="t('chat.copy')"
                    @click="handleCopyMessage(message)"
                  >
                    <img src="/fuzhi.svg" alt="复制" class="icon-svg" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 流式状态提示 -->
    <div v-if="streamingError" class="websocket-error">
      <el-icon><CircleCloseFilled /></el-icon>
      <span>{{ t("agent.connectionError", { error: streamingError }) }}</span>
    </div>
    <div v-else-if="streamingAnswer" class="websocket-success">
      <el-icon><SuccessFilled /></el-icon>
      <span>{{ t("agent.streamingConnected") }}</span>
    </div>

    <!-- 聊天输入框 -->
    <div class="chat-container">
      <AgentChat
        ref="agentChatRef"
        :loading="sendingMessage"
        :maxlength="2000"
        :mode="chatMode"
        @send="handleSend"
        @file-upload="handleFileUpload"
        @knowledge-reference="handleKnowledgeReference"
        @select-model="handleSelectModel"
        @mode-change="chatMode = $event"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  watch,
  nextTick,
  onMounted,
  onUnmounted,
  defineAsyncComponent,
} from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { ElMessage, ElLoading } from "element-plus";
import {
  WarningFilled,
  RefreshRight,
  CircleCloseFilled,
  SuccessFilled,
  Document,
  Warning,
} from "@element-plus/icons-vue";
import AgentChat from "./AgentChat.vue";
import CodexUserAttachedFileCard from "./CodexUserAttachedFileCard.vue";
import type { AttachedFilePayload } from "./agentAttachedPayload";
import {
  parseRefFileIdsList,
  resolveFileEntryId,
  buildAttachedFilesPayload,
  ensureAttachedPayloadCoversTurnFileIds,
} from "./agentAttachedPayload";
import MarkdownPreview from "@/components/Workspace/MarkdownPreview.vue";
import { useWorkspaceChatStore } from "@/stores/chatApi";
import { useCodexStore } from "@/stores/codex";
import { useAppStore } from "@/stores/app";
import { useWorkspaceStore } from "@/stores/workspace";
import {
  getFileContent,
} from "@/api/files";
import { getServicePrice, consumeBeans } from "@/api/pay";
import "katex/dist/katex.min.css";

const { t } = useI18n();
const router = useRouter();
const chatApiStore = useWorkspaceChatStore();
const codexStore = useCodexStore();
const workspaceStore = useWorkspaceStore();

const emit = defineEmits<{
  (e: "mode-change", mode: "ask" | "agent"): void;
}>();

// 聊天模式:ask (提问) 或 agent (智能体)
const props = defineProps<{
  mode?: "ask" | "agent";
}>();

const chatMode = ref<"ask" | "agent">(props.mode || "ask");

// 监听 props.mode 变化
watch(() => props.mode, (newMode) => {
  if (newMode && newMode !== chatMode.value) {
    chatMode.value = newMode;
  }
});

// 监听模式变化并通知父组件
watch(chatMode, (newMode) => {
  emit("mode-change", newMode);
});

// 引用
const filesArray = ref<number[]>([]);
const messagesContainerRef = ref<HTMLElement | null>(null);
const agentChatRef = ref<InstanceType<typeof AgentChat> | null>(null);

// 响应式数据
const shouldAutoScroll = ref(true);
const userScrolled = ref(false);
const isTypingActive = ref(false); // 标记当前是否有打字机效果在进行

// 打字机效果:为每个 typing 状态的 answer 维护显示内容
const typingDisplayContent = ref<Map<string, string>>(new Map());
// 打字机效果:追踪打字机动画帧
const typingAnimationFrames = ref<Map<string, number>>(new Map());

// 计算属性
const messages = computed(() => 
  chatMode.value === "ask" ? chatApiStore.messages : codexStore.messages
);
const currentSession = computed(() => 
  chatMode.value === "ask" ? chatApiStore.currentSession : codexStore.currentSession
);
const sendingMessage = computed(() => 
  chatMode.value === "ask" 
    ? (chatApiStore.messagesLoading || false)
    : (codexStore.messagesLoading || codexStore.aiThinking || false)
);
const streamingAnswer = computed(() => 
  chatMode.value === "ask"
    ? (chatApiStore.streamingAnswer || false)
    : (codexStore.streaming || codexStore.aiTyping || false)
);
const streamingError = computed(() => 
  chatMode.value === "ask" ? chatApiStore.streamingError : codexStore.streamingError
);

// 获取打字机显示内容
const getTypingDisplayContent = (item: any): string => {
  if (chatMode.value === "ask") {
    const answerId = item.id || item.questionId;
    if (!answerId) return item.answerContent || "";

  if (!typingDisplayContent.value.has(answerId)) {
    typingDisplayContent.value.set(answerId, "");
      startTypingEffect(answerId, item.answerContent || "");
    return "";
  }
  return typingDisplayContent.value.get(answerId) || "";
  } else {
    // Agent 模式
    const messageId = item.id;
    if (!messageId) return item.content || "";

    if (!typingDisplayContent.value.has(messageId)) {
      typingDisplayContent.value.set(messageId, "");
      startTypingEffect(messageId, item.content || "");
      return "";
    }
    return typingDisplayContent.value.get(messageId) || "";
  }
};

// 监听消息变化
watch(
  messages,
  (newMessages, oldMessages) => {
    console.log("消息列表变化:", newMessages.length, "条消息");

    // 如果消息被清空(例如点击新建对话),清理打字机状态和动画
    if (newMessages.length === 0) {
      typingDisplayContent.value.clear();
      typingAnimationFrames.value.forEach((frameId) => {
        if (frameId) cancelAnimationFrame(frameId);
      });
      typingAnimationFrames.value.clear();
      typingTargetContent.value.clear();
      isTypingActive.value = false;
      return;
    }

    if (newMessages.length > (oldMessages ? oldMessages.length : 0)) {
      nextTick(() => {
        scrollToBottom();
      });
    }

    // 检查是否有打字机效果正在进行
    let hasTyping = false;

    if (chatMode.value === "ask") {
    newMessages.forEach((message: any) => {
      if (message.answers && message.answers.length > 0) {
        const answer = message.answers[0];
        const answerId = answer.id || answer.questionId;

        if (answer.status === "typing" && answer.answerContent) {
          hasTyping = true;
          if (answerId) {
            updateTypingTarget(answerId, answer.answerContent);
          }
        } else if (answer.status === "completed") {
          if (answerId) {
            stopTypingEffect(answerId);
          }
          setTimeout(() => {
            forceScrollToBottom();
          }, 50);
        }
      }
    });
    } else {
      // Agent 模式
      newMessages.forEach((message: any) => {
        const messageId = message.id;

        if (message.status === "streaming" && message.isStreaming && message.content) {
          hasTyping = true;
          if (messageId) {
            updateTypingTarget(messageId, message.content);
          }
        } else if (message.status === "completed") {
          if (messageId) {
            stopTypingEffect(messageId);
          }
          setTimeout(() => {
            forceScrollToBottom();
          }, 50);
        }
      });
    }

    // 更新打字机活跃状态
    isTypingActive.value = hasTyping;

    // 历史回放:loadTurns 会一次性灌入 messages,且每条 user message 可能带 attachedFiles
    // 这里仅在“从空到有”的首次加载时恢复绿条(上一轮附件)
    if (
      agentChatRef.value &&
      (!oldMessages || oldMessages.length === 0) &&
      newMessages.length > 0
    ) {
      const lastUserWithFiles = [...newMessages]
        .reverse()
        .find(
          (m: any) =>
            m?.role === "user" &&
            Array.isArray(m?.attachedFiles) &&
            m.attachedFiles.length > 0,
        );
      if (lastUserWithFiles) {
        (agentChatRef.value as any).setLastRoundAttachments?.(
          lastUserWithFiles.attachedFiles,
        );
      }
    }
  },
  { deep: true },
);

// 方法
const handleSend = async (msg: any) => {
  if (chatMode.value === "ask") {
    await handleSendAsk(msg);
  } else {
    await handleSendAgent(msg);
  }
};

const handleSendAsk = async (msg: any) => {
  try {
    const content = typeof msg === "string" ? msg : msg.question;
    const knowledgeReferences = msg.knowledgeReferences || [];
    // 处理知识库引用
    let contextArray: number[] = [];
    if (knowledgeReferences.length > 0) {
      knowledgeReferences.forEach((ref: any) => {
        if (ref.type === "files" && ref.files && ref.files.length > 0) {
          // 将所有引用的文件 ID 添加到 context 数组中
          ref.files.forEach((file: any) => {
            const id = file.id || file.fileId;
            const fileId = typeof id === 'string' ? parseInt(id, 10) : id;
            if (typeof fileId === 'number' && !isNaN(fileId)) {
              contextArray.push(fileId);
            }
          });
        }
      });
      filesArray.value = contextArray;
    }
    // 发送文本消息
    if (content.trim()) {
      const tempQuestionId = `temp_${Date.now()}`;
      const userMessage = {
        questionId: tempQuestionId,
        question: content.trim(),
        questionCreatedAt: new Date().toISOString(),
        chatId: currentSession.value
          ? String((currentSession.value as any).sessionId || currentSession.value.id)
          : undefined,
        answers: [
          {
            id: `answer_${Date.now()}`,
            questionId: tempQuestionId,
            answerContent: "",
            createdAt: new Date().toISOString(),
            status: "thinking" as const,
          },
        ],
      };
      chatApiStore.messages.push(userMessage);
      resetAutoScrollState();
      nextTick(scrollToBottom);
      const result = await chatApiStore.sendMessage({
        sessionId: currentSession.value
          ? (currentSession.value as any).sessionId || currentSession.value.id
          : undefined,
        question: content.trim(),
        context: contextArray,
        provider: "doubao", // AgentPanel 工作台默认使用 doubao
      });
      if (!result.success) {
        console.error("发送消息失败:", result.error);
        chatApiStore.updateMessageStatus({
          questionId: tempQuestionId,
          status: "error",
          content: "发送失败,请重试",
        });
        return;
      }
      const { data } = await getServicePrice({ serviceTypeId: 3 });
      if (data !== undefined && data !== null) {
        try {
          const consumeResult = await consumeBeans({
            serviceType: "文档生成",
            beanQuantity: data,
            agentTaskId: result.data?.questionId,
          });
        } catch (error) {
          console.error("消费领医豆失败:", error);
        }
      }
    }
  } catch (error) {
    console.error("发送消息失败:", error);
  }
};

const handleSendAgent = async (msg: any) => {
  try {
    const content = typeof msg === "string" ? msg : msg.question;
    const knowledgeReferences = msg.knowledgeReferences || [];
    const localFiles = msg.files || [];

    let newContextFileIds: number[] = [];
    const uploadedMeta: { id: number; name: string }[] = [];

    if (localFiles.length > 0) {
      try {
        const { uploadBatchFiles } = await import("@/api/files");
        const uploadResult = await uploadBatchFiles(localFiles, -1);
        if (uploadResult) {
          const apiData = uploadResult.data;
          const uploadedItems = Array.isArray(apiData)
            ? apiData
            : apiData?.files || apiData?.items || [];

          uploadedItems.forEach((file: any) => {
            const fileId = file.id || file.fileId;
            const nm =
              file.name ||
              file.fileName ||
              file.itemName ||
              (fileId ? `file-${fileId}` : "");
            if (fileId) {
              const nid = Number(fileId);
              newContextFileIds.push(nid);
              uploadedMeta.push({ id: nid, name: nm || `file-${nid}` });
            }
          });
          ElMessage.success(
            t("KnowledgeBase.uploadToRootJoinChatSuccess") ||
              "文件已保存至知识库根目录并加入对话",
          );
        }
      } catch (uploadError) {
        console.error("Agent 模式拖拽文件上传失败:", uploadError);
        ElMessage.error(
          t("KnowledgeBase.uploadFailed") || "文件上传失败,请稍后重试",
        );
      }
    }

    if (knowledgeReferences.length > 0) {
      knowledgeReferences.forEach((ref: any) => {
        if (ref.type === "files" && ref.files && ref.files.length > 0) {
          const refIdList = parseRefFileIdsList(ref);
          ref.files.forEach((file: any, idx: number) => {
            const id = resolveFileEntryId(file, idx, refIdList);
            if (id !== undefined) {
              newContextFileIds.push(id);
            }
          });
        }
      });
    }

    const turnFileIds = [...new Set(newContextFileIds)];

    let attachedPayload = buildAttachedFilesPayload(
      knowledgeReferences,
      uploadedMeta,
    );
    attachedPayload = ensureAttachedPayloadCoversTurnFileIds(
      attachedPayload,
      turnFileIds,
      knowledgeReferences,
      uploadedMeta,
    );

    if (content.trim()) {
      resetAutoScrollState();
      nextTick(scrollToBottom);

      console.log("[AgentPanelBody Workspace] send turn", {
        turnFileIds,
        attachedPayload,
        knowledgeRefsCount: knowledgeReferences.length,
      });

      const result = await codexStore.sendMessage(
        content.trim(),
        currentSession.value ? (currentSession.value as any).sessionId : undefined,
        turnFileIds,
        attachedPayload.length > 0 ? attachedPayload : undefined,
      );

      if (!result.success) {
        console.error("发送消息失败:", result.error);
        ElMessage.error(result.error || "发送消息失败");
      } else if (agentChatRef.value) {
        // 发送成功后:编辑态引用仅用于发送前展示,清空后改用绿条提示“上一轮附件”
        (agentChatRef.value as any).clearEditingAttachments?.();
        // 仅当本轮有附件时才覆盖绿条;纯文字发送不清空上一轮绿条
        if (attachedPayload.length > 0) {
          (agentChatRef.value as any).setLastRoundAttachments(attachedPayload);
        }
      }
    }
  } catch (error) {
    console.error("发送消息失败:", error);
    ElMessage.error("发送消息失败");
  }
};

watch(
  () => (currentSession.value as any)?.sessionId,
  (sid, prev) => {
    if (!agentChatRef.value) return;
    if (sid && prev && sid === prev) return;
    // 切换/新建会话时清空:避免上一会话绿条串到下一会话
    (agentChatRef.value as any).clearEditingAttachments?.();
    (agentChatRef.value as any).clearLastRoundAttachments?.();
  },
);

const handleRetry = async (item: any) => {
  if (chatMode.value === "ask") {
    await handleRetryAsk(item);
  } else {
    await handleRetryAgent(item);
  }
};

const handleRetryAsk = async (chatItem: any) => {
  if (!currentSession.value || !chatItem.question) {
    console.warn("无法重试:缺少会话或问题内容");
    return;
  }

  try {
    console.log("重试发送消息:", chatItem.question);
    chatApiStore.updateMessageStatus({
      questionId: chatItem.questionId,
      status: "thinking",
      content: "",
    });

    resetAutoScrollState();
    nextTick(scrollToBottom);

    const result = await chatApiStore.sendMessage({
      sessionId: (currentSession.value as any).sessionId || currentSession.value.id,
      question: chatItem.question,
      context: filesArray.value,
      provider: "doubao", // AgentPanel 工作台默认使用 doubao
    });

    if (!result.success) {
      console.error("重试发送失败:", result.error);
      chatApiStore.updateMessageStatus({
        questionId: chatItem.questionId,
        status: "error",
        content: "发送失败,请重试",
      });
    }
  } catch (error) {
    console.error("重试发送过程中出错:", error);
    chatApiStore.updateMessageStatus({
      questionId: chatItem.questionId,
      status: "error",
      content: "发送失败,请重试",
    });
  }
};

const handleRetryAgent = async (message: any) => {
  if (!currentSession.value) {
    console.warn("无法重试:缺少会话");
    return;
  }

  const messageIndex = messages.value.findIndex((m: any) => m.id === message.id);
  if (messageIndex <= 0) {
    ElMessage.warning("无法找到原始问题");
    return;
  }

  const userMessage = messages.value[messageIndex - 1];
  if (!userMessage || userMessage.role !== "user") {
    ElMessage.warning("无法找到原始问题");
    return;
  }

  try {
    message.status = "pending";
    message.error = null;

    resetAutoScrollState();
    nextTick(scrollToBottom);

    const retryAttached = (userMessage as any).attachedFiles as
      | AttachedFilePayload[]
      | undefined;
    const retryFileIds =
      Array.isArray(retryAttached) && retryAttached.length > 0
        ? retryAttached.map((f) => Number(f.id)).filter((n) => !Number.isNaN(n))
        : null;

    const result = await codexStore.sendMessage(
      userMessage.content,
      (currentSession.value as any).sessionId,
      retryFileIds,
      retryAttached && retryAttached.length > 0 ? retryAttached : undefined,
    );

    if (!result.success) {
      console.error("重试发送失败:", result.error);
      message.status = "error";
      message.error = result.error || "发送失败,请重试";
    }
  } catch (error: any) {
    console.error("重试发送过程中出错:", error);
    message.status = "error";
    message.error = error.message || "发送失败,请重试";
  }
};

const handleApprove = async (message: any, decision: string) => {
  if (!message.pendingApproval) return;

  try {
    const approval = message.pendingApproval;
    let result;

    if (approval.type === "command") {
      result = await codexStore.approveCommand(
        approval.approvalId,
        decision as any,
      );
    } else if (approval.type === "patch") {
      result = await codexStore.approvePatch(
        approval.approvalId,
        decision as any,
        approval.fileChangeId,
      );
    }

    if (result && !result.success) {
      ElMessage.error(result.error || "审批操作失败");
    }
  } catch (error: any) {
    console.error("审批操作失败:", error);
    ElMessage.error(error.message || "审批操作失败");
  }
};

const isMessageCompleted = (message: any) => {
  if (!message.status) return true;
  return message.status === "completed";
};

const handleCopy = async (content: string) => {
  try {
    if (!content) {
      ElMessage.warning(t("chat.noContentToCopy") || "没有可复制的内容");
      return;
    }
    await navigator.clipboard.writeText(content);
    ElMessage.success(t("chat.contentCopied") || "内容已复制到剪贴板");
  } catch (error) {
    try {
      const textArea = document.createElement("textarea");
      textArea.value = content;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
      ElMessage.success(t("chat.contentCopied") || "内容已复制到剪贴板");
    } catch (fallbackError) {
      console.error("降级复制也失败:", fallbackError);
      ElMessage.error(t("chat.copyFailed") || "复制失败,请手动复制");
    }
  }
};

const handleCopyMessage = async (message: any) => {
  await handleCopy(message.content);
};

const handleSaveAndEditAgent = async (message: any) => {
  try {
    console.log("AgentPanelBody: 处理保存并编辑", { message });

    if (!message.content) {
      ElMessage.warning("没有可保存的内容");
      return;
    }

    // 检查消息状态
    if (message.status === "pending") {
      ElMessage.warning("AI正在思考中,请等待回答完成后再保存");
      return;
    }

    if (message.status === "streaming") {
      ElMessage.warning("回答正在生成中,请等待完成后再保存");
      return;
    }

    if (message.status === "error") {
      ElMessage.warning("回答出现错误,无法保存");
      return;
    }

    // 只有当状态为 completed 或者没有状态字段时才允许保存
    if (message.status && message.status !== "completed") {
      ElMessage.warning("回答尚未完成,请稍后再试");
      return;
    }

    if (!currentSession.value) {
      ElMessage.error("缺少会话信息,无法保存");
      return;
    }

    const messageIndex = messages.value.findIndex((m: any) => m.id === message.id);
    let questionContent = "";
    if (messageIndex > 0) {
      const prevMessage = messages.value[messageIndex - 1];
      if (prevMessage && prevMessage.role === "user") {
        questionContent = prevMessage.content;
      }
    }
    
    const title = questionContent || message.content;

    await workspaceStore.generateDocument({
      title,
      content: message.content,
      isDeepSearch: true,
      onSuccess: async (fileInfo, draftContent) => {
        // 5. 添加到对话框引用
        if (agentChatRef.value) {
          agentChatRef.value.addFileReferences(
            [
              {
                id: fileInfo.id || fileInfo.fileId,
                name: fileInfo.name || fileInfo.fileName,
                type: "md",
              },
            ],
            [(fileInfo.id || fileInfo.fileId).toString()],
          );
        }

        // 6. 跳转到工作台编辑器
        await openInWorkspace({
          id: fileInfo.id,
          title: fileInfo.name || fileInfo.fileName,
          isDraft: false,
          preloadContent: draftContent,
        });
      }
    });
  } catch (error) {
    console.error("保存并编辑失败:", error);
    ElMessage.error("操作失败,请重试");
  }
};

const handleFileUpload = (file: File) => {
  console.log("文件上传:", file);
};

const handleKnowledgeReference = (doc: any) => {
  console.log("知识库引用:", doc);
};

const handleSelectModel = (model: any) => {
  console.log("选择模型:", model);
};

const isAnswerCompleted = (answer: any) => {
  if (!answer.status) return true;
  return answer.status === "completed";
};

const handleCopyAnswer = async (answer: any) => {
  await handleCopy(answer.answerContent);
};

const handleSaveAndEdit = async (chatItem: any, answer: any) => {
  try {
    console.log("AgentPanelBody: 处理保存并编辑", { chatItem, answer });

    if (!answer.answerContent) {
      ElMessage.warning("没有可保存的内容");
      return;
    }

    if (answer.status === "thinking") {
      ElMessage.warning("AI正在思考中,请等待回答完成后再保存");
      return;
    }

    if (answer.status === "typing") {
      ElMessage.warning("回答正在生成中,请等待完成后再保存");
      return;
    }

    if (answer.status === "error") {
      ElMessage.warning("回答出现错误,无法保存");
      return;
    }

    if (answer.status && answer.status !== "completed") {
      ElMessage.warning("回答尚未完成,请稍后再试");
      return;
    }

    if (!chatItem.questionId) {
      ElMessage.error("缺少问题ID,无法保存");
      return;
    }

    if (!currentSession.value) {
      ElMessage.error("缺少会话信息,无法保存");
      return;
    }

    const title = chatItem.question || "未命名文档";

    await workspaceStore.generateDocument({
      title,
      content: answer.answerContent,
      questionId: chatItem.questionId,
      isDeepSearch: false,
      onSuccess: async (fileInfo, draftContent) => {
        // 5. 添加到对话框引用
        if (agentChatRef.value) {
          agentChatRef.value.addFileReferences(
            [
              {
                id: fileInfo.id || fileInfo.fileId,
                name: fileInfo.name || fileInfo.fileName,
                type: "md",
              },
            ],
            [(fileInfo.id || fileInfo.fileId).toString()],
          );
        }

        // 6. 跳转到工作台编辑器
        await openInWorkspace({
          id: fileInfo.id,
          title: fileInfo.name || fileInfo.fileName,
          isDraft: false,
          preloadContent: draftContent,
        });
      }
    });
  } catch (error) {
    console.error("保存并编辑失败:", error);
    ElMessage.error("操作失败,请重试");
  }
};

const openInWorkspace = async (fileInfo: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: "正在准备文档...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    console.log("准备在工作台中打开文件:", fileInfo);

    let fileContent = fileInfo.preloadContent || "";
    // 先下载文件内容,确保文件可以正常访问
    try {
      if (!fileContent) {
        console.log("开始下载文件内容,fileId:", fileInfo.id);
        // 统一使用常规文件 API
        const contentResponse = await getFileContent(fileInfo.id);
        fileContent = contentResponse.data;
        console.log("文件内容下载成功,内容长度:", fileContent.length);
      } else {
        console.log("使用预传递的文件内容,内容长度:", fileContent.length);
      }
    } catch (downloadError) {
      console.error("下载文件内容失败:", downloadError);
      ElMessage.warning("文件内容预加载失败,将尝试在编辑器中重新加载");
    }

    const params: any = {
      fileId: fileInfo.id,
      fileName: fileInfo.title || fileInfo.name,
      fileType: "md", // 默认为 markdown
      isChatAnswer: fileInfo.isDraft === false ? "false" : "true", // 明确标记是否为智能体回答文件(草稿)
    };

    if (fileContent) {
      params.preloadContent = encodeURIComponent(fileContent);
    }

    await performRouterNavigation(params);
  } catch (error) {
    console.error("打开工作台编辑器失败:", error);
    ElMessage.error("打开编辑器失败,请重试");
  } finally {
    loading.close();
  }
};

const performRouterNavigation = async (params: any) => {
  try {
    console.log("开始执行路由跳转,参数:", params);

    try {
      await router.push({
        name: "Workspace",
        query: params,
      });
      console.log("使用路由名称跳转成功");
      return;
    } catch (nameError) {
      console.warn("路由名称跳转失败:", nameError);
    }

    try {
      await router.push({
        path: "/app/workspace",
        query: params,
      });
      console.log("使用路径跳转成功");
      return;
    } catch (pathError) {
      console.warn("路径跳转失败:", pathError);
    }

    const possiblePaths = ["/workspace", "/Workspace", "/app/Workspace"];

    for (const path of possiblePaths) {
      try {
        await router.push({
          path: path,
          query: params,
        });
        console.log(`使用路径 ${path} 跳转成功`);
        return;
      } catch (error) {
        console.warn(`路径 ${path} 跳转失败:`, error);
      }
    }

    console.error("所有路由跳转方式都失败");
    ElMessage.error("无法跳转到工作台,请手动导航到工作台页面");

    const queryString = new URLSearchParams(params).toString();
    const targetUrl = `#/app/workspace?${queryString}`;
    console.log("如需手动跳转,请访问:", targetUrl);
  } catch (error) {
    console.error("路由跳转过程中发生错误:", error);
    ElMessage.error("跳转失败,请重试");
  }
};

const scrollToBottom = () => {
  if (!shouldAutoScroll.value) {
    console.log("用户手动滚动过,跳过自动滚动到底部");
    return;
  }

  nextTick(() => {
    const container = messagesContainerRef.value;
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  });
};

const forceScrollToBottom = () => {
  const container = messagesContainerRef.value;
  if (container) {
    requestAnimationFrame(() => {
      if (container) {
        container.scrollTop = container.scrollHeight;
        shouldAutoScroll.value = true;
        userScrolled.value = false;
        console.log("打字机效果结束,强制滚动到底部并恢复自动滚动");
      }
    });
  }
};

const typingTargetContent = ref<Map<string, string>>(new Map());

const TYPING_CONFIG = {
  charsPerFrame: 3,
  minCharsPerFrame: 2,
  maxCharsPerFrame: 10,
};

const startTypingEffect = (answerId: string, targetContent: string) => {
  if (typingAnimationFrames.value.has(answerId)) {
    return;
  }

  typingTargetContent.value.set(answerId, targetContent);

  const charsPerFrame = TYPING_CONFIG.charsPerFrame;

  const typeNextChars = () => {
    const currentContent = typingDisplayContent.value.get(answerId) || "";
    const targetContent = typingTargetContent.value.get(answerId) || "";

    if (targetContent.length > currentContent.length) {
      const nextIndex = Math.min(
        currentContent.length + charsPerFrame,
        targetContent.length,
      );

      const nextContent = targetContent.substring(0, nextIndex);
      typingDisplayContent.value.set(answerId, nextContent);

      if (shouldAutoScroll.value) {
        nextTick(() => {
          const container = messagesContainerRef.value;
          if (container) {
            container.scrollTop = container.scrollHeight;
          }
        });
      }

      const frameId = requestAnimationFrame(typeNextChars);
      typingAnimationFrames.value.set(answerId, frameId);
    } else {
      typingAnimationFrames.value.delete(answerId);

      if (shouldAutoScroll.value) {
        nextTick(() => {
          const container = messagesContainerRef.value;
          if (container) {
            container.scrollTop = container.scrollHeight;
          }
        });
      }
    }
  };

  const frameId = requestAnimationFrame(typeNextChars);
  typingAnimationFrames.value.set(answerId, frameId);
};

const updateTypingTarget = (answerId: string, newTargetContent: string) => {
  const oldTarget = typingTargetContent.value.get(answerId) || "";

  if (newTargetContent !== oldTarget) {
    typingTargetContent.value.set(answerId, newTargetContent);

    if (!typingAnimationFrames.value.has(answerId)) {
      startTypingEffect(answerId, newTargetContent);
    }
  }
};

const stopTypingEffect = (answerId: string) => {
  const frameId = typingAnimationFrames.value.get(answerId);
  if (frameId) {
    cancelAnimationFrame(frameId);
    typingAnimationFrames.value.delete(answerId);
  }

  typingDisplayContent.value.delete(answerId);
  typingTargetContent.value.delete(answerId);
};

let scrollCheckTimeout: number | null = null;

const handleScroll = (event: Event) => {
  const container = event.target as HTMLElement;
  if (!container) return;

  if (scrollCheckTimeout) {
    clearTimeout(scrollCheckTimeout);
  }

  scrollCheckTimeout = window.setTimeout(() => {
    const scrollTop = container.scrollTop;
    const scrollHeight = container.scrollHeight;
    const clientHeight = container.clientHeight;
    const distanceFromBottom = scrollHeight - scrollTop - clientHeight;

    const isAtBottom = distanceFromBottom <= 50;

    if (isAtBottom) {
      if (!shouldAutoScroll.value) {
        console.log("用户滚动到底部,恢复自动滚动");
        shouldAutoScroll.value = true;
        userScrolled.value = false;
      }
    } else {
      if (shouldAutoScroll.value && isTypingActive.value) {
        console.log("打字机效果中,用户手动滚动离开底部,停止自动滚动");
        shouldAutoScroll.value = false;
        userScrolled.value = true;
      }
    }
  }, 100);
};

const resetAutoScrollState = () => {
  shouldAutoScroll.value = true;
  userScrolled.value = false;
  console.log("重置自动滚动状态");
};

onMounted(() => {
  console.log("AgentPanelBody mounted");
  nextTick(() => {
    const container = messagesContainerRef.value;
    if (container) {
      container.addEventListener("scroll", handleScroll);
    }
  });
});

onUnmounted(() => {
  const container = messagesContainerRef.value;
  if (container) {
    container.removeEventListener("scroll", handleScroll);
  }

  if (scrollCheckTimeout) {
    clearTimeout(scrollCheckTimeout);
    scrollCheckTimeout = null;
  }

  typingAnimationFrames.value.forEach((frameId) => {
    cancelAnimationFrame(frameId);
  });
  typingAnimationFrames.value.clear();
  typingDisplayContent.value.clear();
  typingTargetContent.value.clear();
});

defineExpose({
  agentChatRef,
});
</script>

<style scoped>
.agent-panel-body {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px 10px 16px 10px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
}

.chat-container {
  flex-shrink: 0;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.user-question {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-bottom: 26px;
}

.user-attached-files {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  max-width: 100%;
  margin-bottom: 8px;
}

.ai-answer {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 10px;
}

.message-body-question {
  padding: 8px 12px 8px 12px;
  border-radius: 8px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
  max-width: 100%;
  word-wrap: break-word;
  font-size: 14px;
  background: var(--user-question-bg);
  color: var(--user-question-text);
}

.message-body-answer {
  border-radius: 8px;
  line-height: 1.5;
  word-break: break-word;
  max-width: 100%;
  word-wrap: break-word;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  background: var(--ai-answer-bg);
  color: var(--ai-answer-text);
}

.markdown-content {
  width: 100%;
  padding: 8px 12px;
  line-height: 1.6;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.message-actions-answer {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 12px;
  gap: 4px;
}

.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 6px;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  &:hover {
    background: rgba(0, 0, 0, 0.05);
  }

  &.disabled {
    opacity: 0.3;
    cursor: not-allowed;
    filter: grayscale(100%);
    
    &:hover {
      background: none;
    }
  }
}

.icon-svg {
  width: 16px !important;
  height: 16px !important;
  object-fit: contain;
  flex-shrink: 0;
}

.ai-thinking {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: var(--ai-answer-bg);
  border: 1px solid transparent;
  border-radius: 8px;
  color: var(--ai-answer-text);
  min-height: 60px;
  transition: all 0.3s ease;
}

.thinking-dots {
  display: flex;
  gap: 4px;
  align-items: center;
}

.thinking-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--color-primary, #2871f6);
  animation: thinking 1.4s infinite ease-in-out;
  display: inline-block;
}

.thinking-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.thinking-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

.thinking-text {
  font-size: 14px;
  color: var(--color-text-secondary, #999);
  font-weight: 500;
}

@keyframes thinking {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.error-message {
  background: rgba(244, 67, 54, 0.1) !important;
  border: 1px solid #eaa8a3 !important;
  color: #f44336 !important;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 4px 2px 4px 12px;
  border-radius: 4px;
  gap: 8px;
}

.retry-icon {
  cursor: pointer;
  transition: all 0.2s ease;
}

.retry-icon:hover {
  color: #d32f2f;
  transform: rotate(180deg);
}

.websocket-error {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(244, 67, 54, 0.1);
  border: 1px solid #eaa8a3 !important;
  color: #f44336;
  padding: 8px 12px;
  border-radius: 4px;
  margin: 8px 16px;
  font-size: 12px;
}

.websocket-success {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(76, 175, 80, 0.1);
  border: 1px solid #4caf50;
  color: #4caf50;
  padding: 8px 12px;
  border-radius: 4px;
  margin: 8px 16px;
  font-size: 12px;
}

.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background: var(--color-border);
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: var(--color-secondary);
}

.typewriter {
  position: relative;
}

.typewriter-content {
  white-space: normal !important;
  word-wrap: break-word;
}

.approval-pending {
  background: rgba(255, 193, 7, 0.1) !important;
  border: 1px solid #ffc107 !important;
  padding: 12px;
  border-radius: 8px;
}

.approval-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.approval-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #ff9800;
}

.approval-body {
  padding: 8px 0;
  font-size: 13px;
}

.approval-body pre {
  background: rgba(0, 0, 0, 0.05);
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  margin-top: 4px;
}

.approval-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.message-actions-user {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 4px;
  gap: 4px;
}

</style>