File size: 42,082 Bytes
ea775bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useQuery } from "@tanstack/react-query";
import { createColumnHelper } from "@tanstack/react-table";
import { AlertTriangle, Eraser, RefreshCw, Sparkles, X } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Badge } from "../../components/ui/Badge";
import { Button } from "../../components/ui/Button";
import { Card } from "../../components/ui/Card";
import { DataTable } from "../../components/ui/DataTable";
import { CursorPagination } from "../../components/ui/CursorPagination";
import { Input } from "../../components/ui/Input";
import { Select } from "../../components/ui/Select";
import { ToastContainer } from "../../components/ui/Toast";
import { useToast } from "../../hooks/useToast";
import { useI18n } from "../../i18n";
import { getCurrentLocale, isEnglishLocale } from "../../i18n/locale";
import { formatBytes } from "../../lib/bytes";
import { formatApiErrorMessage } from "../../lib/error-message";
import { formatDateTime } from "../../lib/time";
import { getSystemConfig } from "../systemConfig/api";
import { getRequestLog, getRequestLogPayloads, listRequestLogs } from "./api";
import type { RequestLogItem, RequestLogListFilters } from "./types";

type BoolFilter = "all" | "true" | "false";
type ProxyTypeFilter = "all" | "1" | "2" | "3";

type FilterDraft = {
  from_local: string;
  to_local: string;
  platform_name: string;
  account: string;
  target_host: string;
  egress_ip: string;
  proxy_type: ProxyTypeFilter;
  net_ok: BoolFilter;
  http_status: string;
  limit: number;
};

const defaultFilters: FilterDraft = {
  from_local: "",
  to_local: "",
  platform_name: "",
  account: "",
  target_host: "",
  egress_ip: "",
  proxy_type: "all",
  net_ok: "all",
  http_status: "",
  limit: 100,
};
const PAGE_SIZE_OPTIONS = [20, 50, 100, 200, 500, 1000, 2000] as const;
const REQUEST_LOGS_FORWARD_BADGE_CLASS = "request-logs-proxy-badge-forward";
const REQUEST_LOGS_REVERSE_BADGE_CLASS = "request-logs-proxy-badge-reverse";
const REQUEST_LOGS_SOCKS_BADGE_CLASS = "request-logs-proxy-badge-socks";

const PAYLOAD_TABS = ["request", "response"] as const;
type PayloadTab = (typeof PAYLOAD_TABS)[number];
const EMPTY_LOGS: RequestLogItem[] = [];
const BASE64_DECODE_FAILED = "[Base64 解码失败]";
const UNSUPPORTED_CONTENT_ENCODING_PREFIX = "暂不支持的 Content-Encoding: ";
const CONTENT_ENCODING_DECODE_FAILED_PREFIX = "Content-Encoding=";
const CONTENT_ENCODING_DECODE_FAILED_SUFFIX = " 解压失败";

function toRFC3339(localDateTime: string): string {
  if (!localDateTime) {
    return "";
  }
  const date = new Date(localDateTime);
  if (Number.isNaN(date.getTime())) {
    return "";
  }
  return date.toISOString();
}

function boolFromFilter(value: BoolFilter): boolean | undefined {
  if (value === "true") {
    return true;
  }
  if (value === "false") {
    return false;
  }
  return undefined;
}

function decodeBase64ToBytes(raw: string): Uint8Array | null {
  if (!raw) {
    return new Uint8Array(0);
  }

  try {
    const binary = atob(raw);
    return Uint8Array.from(binary, (char) => char.charCodeAt(0));
  } catch {
    return null;
  }
}

function decodeBytesToText(bytes: Uint8Array, charset?: string): string {
  if (!bytes.length) {
    return "";
  }

  if (charset) {
    try {
      return new TextDecoder(charset).decode(bytes);
    } catch {
      // Fallback to UTF-8 when charset is unsupported.
    }
  }

  return new TextDecoder().decode(bytes);
}

function decodeBase64ToText(raw: string): string {
  const bytes = decodeBase64ToBytes(raw);
  if (!bytes) {
    return BASE64_DECODE_FAILED;
  }
  return decodeBytesToText(bytes);
}

function parseHeaderMap(headersText: string): Map<string, string> {
  const map = new Map<string, string>();

  for (const line of headersText.split(/\r?\n/)) {
    const separatorIndex = line.indexOf(":");
    if (separatorIndex <= 0) {
      continue;
    }

    const key = line.slice(0, separatorIndex).trim().toLowerCase();
    const value = line.slice(separatorIndex + 1).trim();
    if (!key || !value) {
      continue;
    }

    const current = map.get(key);
    map.set(key, current ? `${current}, ${value}` : value);
  }

  return map;
}

function parseCharset(contentType?: string): string | undefined {
  if (!contentType) {
    return undefined;
  }
  const match = contentType.match(/charset\s*=\s*["']?([^;"'\s]+)/i);
  return match?.[1]?.trim();
}

function parseContentEncodings(contentEncoding?: string): string[] {
  if (!contentEncoding) {
    return [];
  }

  return contentEncoding
    .split(",")
    .map((token) => token.trim().toLowerCase())
    .filter((token) => token && token !== "identity");
}

function normalizeContentEncoding(token: string): "gzip" | "deflate" | "br" | "zstd" | null {
  switch (token) {
    case "gzip":
    case "x-gzip":
      return "gzip";
    case "deflate":
      return "deflate";
    case "br":
      return "br";
    case "zstd":
    case "x-zstd":
      return "zstd";
    default:
      return null;
  }
}

function translatePayloadDecodeErrorMessage(rawMessage: string, t: (text: string, options?: Record<string, unknown>) => string): string {
  if (rawMessage.startsWith(UNSUPPORTED_CONTENT_ENCODING_PREFIX)) {
    const token = rawMessage.slice(UNSUPPORTED_CONTENT_ENCODING_PREFIX.length).trim();
    return t("暂不支持的 Content-Encoding: {{token}}", { token });
  }

  if (rawMessage.startsWith(CONTENT_ENCODING_DECODE_FAILED_PREFIX) && rawMessage.endsWith(CONTENT_ENCODING_DECODE_FAILED_SUFFIX)) {
    const token = rawMessage
      .slice(CONTENT_ENCODING_DECODE_FAILED_PREFIX.length, rawMessage.length - CONTENT_ENCODING_DECODE_FAILED_SUFFIX.length)
      .trim();
    return t("Content-Encoding={{token}} 解压失败", { token });
  }

  return t(rawMessage);
}

async function decompressWithEncoding(bytes: Uint8Array, encoding: "gzip" | "deflate" | "br" | "zstd"): Promise<Uint8Array> {
  if (typeof DecompressionStream === "undefined") {
    throw new Error("当前浏览器不支持 DecompressionStream,无法自动解压");
  }

  const stream = new Blob([new Uint8Array(bytes)]).stream().pipeThrough(new DecompressionStream(encoding as never));
  const arrayBuffer = await new Response(stream).arrayBuffer();
  return new Uint8Array(arrayBuffer);
}

async function decodeContentEncodings(bytes: Uint8Array, encodings: string[]): Promise<Uint8Array> {
  let decoded = bytes;

  // Content-Encoding is listed in the order applied, so decoding must reverse it.
  for (let i = encodings.length - 1; i >= 0; i -= 1) {
    const token = encodings[i];
    const encoding = normalizeContentEncoding(token);
    if (!encoding) {
      throw new Error(`暂不支持的 Content-Encoding: ${token}`);
    }
    try {
      decoded = await decompressWithEncoding(decoded, encoding);
    } catch {
      throw new Error(`Content-Encoding=${token} 解压失败`);
    }
  }

  return decoded;
}

async function decodePayloadBodyForDisplay(rawBodyBase64: string, headersText: string): Promise<string> {
  const bodyBytes = decodeBase64ToBytes(rawBodyBase64);
  if (!bodyBytes) {
    return BASE64_DECODE_FAILED;
  }
  if (!bodyBytes.length) {
    return "";
  }

  const headerMap = parseHeaderMap(headersText);
  const encodings = parseContentEncodings(headerMap.get("content-encoding"));
  const contentType = headerMap.get("content-type");
  let decodedBytes = bodyBytes;
  if (encodings.length) {
    try {
      decodedBytes = await decodeContentEncodings(bodyBytes, encodings);
    } catch {
      // Best-effort: fallback to undecoded bytes when content-encoding decode fails.
    }
  }

  return decodeBytesToText(decodedBytes, parseCharset(contentType));
}

function isFromBeforeTo(fromISO?: string, toISO?: string): boolean {
  if (!fromISO || !toISO) {
    return true;
  }
  return new Date(fromISO).getTime() < new Date(toISO).getTime();
}

function buildActiveFilters(draft: FilterDraft): Omit<RequestLogListFilters, "cursor"> {
  const status = Number(draft.http_status);
  const hasValidStatus = Number.isInteger(status) && status >= 100 && status <= 599;
  const from = toRFC3339(draft.from_local);
  const to = toRFC3339(draft.to_local);
  const validRange = isFromBeforeTo(from, to);

  return {
    from,
    to: validRange ? to : undefined,
    platform_name: draft.platform_name,
    account: draft.account,
    target_host: draft.target_host,
    egress_ip: draft.egress_ip,
    proxy_type: draft.proxy_type === "all" ? undefined : Number(draft.proxy_type),
    net_ok: boolFromFilter(draft.net_ok),
    http_status: hasValidStatus ? status : undefined,
    limit: draft.limit,
    fuzzy: true,
  };
}

function proxyTypeLabel(proxyType: number): string {
  if (proxyType === 1) {
    return "HTTP 正向代理";
  }
  if (proxyType === 2) {
    return "HTTP 反向代理";
  }
  if (proxyType === 3) {
    return "SOCKS5 正向代理";
  }
  return String(proxyType);
}

function proxyTypeBadgeClassName(proxyType: number): string | null {
  if (proxyType === 1) {
    return REQUEST_LOGS_FORWARD_BADGE_CLASS;
  }
  if (proxyType === 2) {
    return REQUEST_LOGS_REVERSE_BADGE_CLASS;
  }
  if (proxyType === 3) {
    return REQUEST_LOGS_SOCKS_BADGE_CLASS;
  }
  return null;
}

function dateLocale(): string {
  return isEnglishLocale(getCurrentLocale()) ? "en-US" : "zh-CN";
}


function splitDateTime(input: string): { date: string; time: string } {
  if (!input) {
    return { date: "-", time: "-" };
  }

  const value = new Date(input);
  if (Number.isNaN(value.getTime())) {
    return { date: input, time: "-" };
  }

  const date = new Intl.DateTimeFormat(dateLocale(), {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(value);

  const time = new Intl.DateTimeFormat(dateLocale(), {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: false,
  }).format(value);

  return { date, time };
}

export function RequestLogsPage() {
  const { t } = useI18n();
  const [filters, setFilters] = useState<FilterDraft>(defaultFilters);
  const [cursorStack, setCursorStack] = useState<string[]>([""]);
  const [pageIndex, setPageIndex] = useState(0);
  const [selectedLogId, setSelectedLogId] = useState("");
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [payloadTab, setPayloadTab] = useState<PayloadTab>("request");
  const [payloadData, setPayloadData] = useState<{ headers: string; body: string }>({
    headers: "",
    body: "",
  });
  const [payloadDecodePending, setPayloadDecodePending] = useState(false);
  const { toasts, dismissToast } = useToast();

  const configQuery = useQuery({
    queryKey: ["system-config"],
    queryFn: getSystemConfig,
    staleTime: 60_000,
  });

  const activeFilters = useMemo(() => buildActiveFilters(filters), [filters]);
  const cursor = cursorStack[pageIndex] || "";

  const rangeInvalid = useMemo(() => {
    const from = toRFC3339(filters.from_local);
    const to = toRFC3339(filters.to_local);
    return Boolean(from && to && !isFromBeforeTo(from, to));
  }, [filters.from_local, filters.to_local]);

  const httpStatusInvalid = useMemo(() => {
    const raw = filters.http_status.trim();
    if (!raw) {
      return false;
    }
    const value = Number(raw);
    return !(Number.isInteger(value) && value >= 100 && value <= 599);
  }, [filters.http_status]);

  const logsQuery = useQuery({
    queryKey: ["request-logs", activeFilters, cursor],
    queryFn: () => listRequestLogs({ ...activeFilters, cursor }),
    refetchInterval: pageIndex === 0 ? 15_000 : false,
    placeholderData: (prev) => prev,
  });

  const logs = logsQuery.data?.items ?? EMPTY_LOGS;
  const isPageTransitioning = logsQuery.isFetching && logsQuery.isPlaceholderData;

  const visibleLogs = isPageTransitioning ? EMPTY_LOGS : logs;

  const selectedLog = useMemo(() => {
    if (!selectedLogId) {
      return null;
    }
    return logs.find((item) => item.id === selectedLogId) ?? null;
  }, [logs, selectedLogId]);

  const detailLogId = selectedLogId;
  const drawerVisible = drawerOpen && Boolean(detailLogId);

  const detailQuery = useQuery({
    queryKey: ["request-log", detailLogId],
    queryFn: () => getRequestLog(detailLogId),
    enabled: drawerVisible,
  });

  const detailLog: RequestLogItem | null = detailQuery.data ?? selectedLog ?? null;

  const payloadQuery = useQuery({
    queryKey: ["request-log-payload", detailLogId],
    queryFn: () => getRequestLogPayloads(detailLogId),
    enabled: drawerVisible && Boolean(detailLog?.payload_present),
    staleTime: 30_000,
  });

  useEffect(() => {
    if (!drawerVisible) {
      return;
    }

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "Escape") {
        return;
      }
      setDrawerOpen(false);
    };

    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [drawerVisible]);

  const updateFilter = <K extends keyof FilterDraft>(key: K, value: FilterDraft[K]) => {
    setFilters((prev) => ({ ...prev, [key]: value }));
    setCursorStack([""]);
    setPageIndex(0);
    setSelectedLogId("");
    setDrawerOpen(false);
  };

  const resetFilters = () => {
    setFilters(defaultFilters);
    setCursorStack([""]);
    setPageIndex(0);
    setSelectedLogId("");
    setDrawerOpen(false);
  };

  const openDrawer = (logId: string) => {
    setSelectedLogId(logId);
    setDrawerOpen(true);
    setPayloadTab("request");
  };

  const moveNext = () => {
    if (isPageTransitioning) {
      return;
    }

    const nextCursor = logsQuery.data?.next_cursor;
    if (!nextCursor) {
      return;
    }

    setCursorStack((prev) => {
      const expectedNextIndex = pageIndex + 1;
      if (prev[expectedNextIndex] === nextCursor) {
        return prev;
      }
      return [...prev.slice(0, expectedNextIndex), nextCursor];
    });
    setPageIndex((prev) => prev + 1);
    setSelectedLogId("");
    setDrawerOpen(false);
  };

  const movePrev = () => {
    if (isPageTransitioning) {
      return;
    }

    setPageIndex((prev) => Math.max(0, prev - 1));
    setSelectedLogId("");
    setDrawerOpen(false);
  };

  useEffect(() => {
    let cancelled = false;
    const payload = payloadQuery.data;

    if (!payload) {
      setPayloadData({ headers: "", body: "" });
      setPayloadDecodePending(false);
      return () => {
        cancelled = true;
      };
    }

    setPayloadData({ headers: "", body: "" });
    setPayloadDecodePending(true);

    const decodePayload = async () => {
      const [headersBase64, bodyBase64] =
        payloadTab === "request"
          ? [payload.req_headers_b64, payload.req_body_b64]
          : [payload.resp_headers_b64, payload.resp_body_b64];

      const rawHeaders = decodeBase64ToText(headersBase64).trimEnd();
      const rawBody = (await decodePayloadBodyForDisplay(bodyBase64, rawHeaders)).trimEnd();
      const headers = rawHeaders === BASE64_DECODE_FAILED ? t(rawHeaders) : rawHeaders;
      const body = rawBody === BASE64_DECODE_FAILED ? t(rawBody) : rawBody;

      if (cancelled) {
        return;
      }
      setPayloadData({ headers, body });
      setPayloadDecodePending(false);
    };

    void decodePayload().catch((error: unknown) => {
      if (cancelled) {
        return;
      }
      const message = error instanceof Error ? translatePayloadDecodeErrorMessage(error.message, t) : t("未知错误");
      setPayloadData({ headers: "", body: t("[Body 解码失败:{{message}}]", { message }) });
      setPayloadDecodePending(false);
    });

    return () => {
      cancelled = true;
    };
  }, [payloadQuery.data, payloadTab, t]);

  const hasMore = Boolean(logsQuery.data?.has_more && logsQuery.data?.next_cursor);
  const renderProxyTypeBadge = (proxyType: number, context: "table" | "drawer" = "table") => {
    const className = proxyTypeBadgeClassName(proxyType);
    if (!className) {
      return t(proxyTypeLabel(proxyType));
    }

    let label = "";
    if (proxyType === 1) {
      label = context === "drawer" ? t("HTTP") : t("正向");
    } else if (proxyType === 2) {
      label = t("反向");
    } else {
      label = t("SOCKS5");
    }

    return <Badge className={className}>{label}</Badge>;
  };

  const col = useMemo(() => createColumnHelper<RequestLogItem>(), []);

  const logColumns = useMemo(
    () => [
      col.accessor("ts", {
        header: t("时间"),
        cell: (info) => {
          const timeParts = splitDateTime(info.getValue());
          return (
            <div className="logs-cell-stack logs-time-cell">
              <span>{timeParts.time}</span>
              <small>{timeParts.date}</small>
            </div>
          );
        },
      }),
      col.accessor("proxy_type", {
        header: t("代理"),
        cell: (info) => renderProxyTypeBadge(info.getValue()),
      }),
      col.display({
        id: "platform_account",
        header: t("平台 / 账号"),
        cell: (info) => {
          const log = info.row.original;
          return (
            <div className="logs-cell-stack">
              <span>{log.platform_name || "-"}</span>
              <small>{log.account || "-"}</small>
            </div>
          );
        },
      }),
      col.display({
        id: "target",
        header: t("目标"),
        cell: (info) => {
          const log = info.row.original;
          return (
            <div className="logs-cell-stack">
              <span title={log.target_host}>{log.target_host || "-"}</span>
              <small title={log.target_url}>{log.target_url || "-"}</small>
            </div>
          );
        },
      }),
      col.display({
        id: "http",
        header: t("HTTP"),
        cell: (info) => {
          const log = info.row.original;
          return (
            <div className="logs-cell-stack">
              <span>{log.http_method || "-"}</span>
              <small>{log.http_status || "-"}</small>
            </div>
          );
        },
      }),

      col.accessor("net_ok", {
        header: t("网络"),
        cell: (info) => (
          <Badge variant={info.getValue() ? "success" : "warning"}>
            {info.getValue() ? t("成功") : t("失败")}
          </Badge>
        ),
      }),
      col.accessor("duration_ms", {
        header: t("耗时"),
        cell: (info) => `${info.getValue()} ms`,
      }),
      col.display({
        id: "traffic",
        header: t("流量"),
        cell: (info) => {
          const log = info.row.original;
          return formatBytes((log.ingress_bytes || 0) + (log.egress_bytes || 0));
        },
      }),
      col.display({
        id: "node",
        header: t("节点"),
        cell: (info) => {
          const log = info.row.original;
          return (
            <div className="logs-cell-stack">
              {log.node_tag ? (
                <Link
                  to={`/nodes?tag_keyword=${encodeURIComponent(log.node_tag)}`}
                  title={t("在节点池搜索 {{tag}}", { tag: log.node_tag })}
                  onClick={(event) => event.stopPropagation()}
                  style={{
                    color: "var(--accent-primary)",
                    textDecoration: "none",
                    width: "fit-content",
                  }}
                >
                  {log.node_tag}
                </Link>
              ) : (
                <span>-</span>
              )}
              <small title={log.egress_ip}>{log.egress_ip || "-"}</small>
            </div>
          );
        },
      }),
    ],
    [col, t]
  );

  return (
    <section className="nodes-page">
      <header className="module-header">
        <div>
          <h2>{t("请求日志")}</h2>
          <p className="module-description">{t("按条件检索请求记录,快速定位问题。")}</p>
        </div>
        {!configQuery.isLoading && configQuery.data && (
          <Link to="/system-config" style={{ display: "flex", textDecoration: "none" }}>
            <Badge variant={configQuery.data.request_log_enabled ? "success" : "warning"} style={{ cursor: "pointer", fontSize: "13px", padding: "6px 12px" }}>
              {configQuery.data.request_log_enabled ? t("当前实时日志记录已开启") : t("当前实时日志记录未开启")}
            </Badge>
          </Link>
        )}
      </header>

      <ToastContainer toasts={toasts} onDismiss={dismissToast} />

      <Card className="filter-card platform-list-card platform-directory-card">
        <div className="list-card-header">
          <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem", width: "100%" }}>
            {/* 时间与路由信息 */}
            <div
              className="logs-inline-filters"
              style={{ display: "flex", flexWrap: "wrap", gap: "0.75rem", alignItems: "flex-end" }}
            >
              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                <label htmlFor="logs-from" style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>
                  {t("开始时间")}
                </label>
                <Input
                  id="logs-from"
                  type="datetime-local"
                  value={filters.from_local}
                  onChange={(event) => updateFilter("from_local", event.target.value)}
                  style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }}
                />
              </div>

              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                <label htmlFor="logs-to" style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>
                  {t("结束时间")}
                </label>
                <Input
                  id="logs-to"
                  type="datetime-local"
                  value={filters.to_local}
                  onChange={(event) => updateFilter("to_local", event.target.value)}
                  style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }}
                />
              </div>

              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                <label htmlFor="logs-platform-name" style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>
                  {t("平台")}
                </label>
                <Input
                  id="logs-platform-name"
                  value={filters.platform_name}
                  onChange={(event) => updateFilter("platform_name", event.target.value)}
                  style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }}
                />
              </div>

              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                <label htmlFor="logs-account" style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>
                  {t("账号")}
                </label>
                <Input
                  id="logs-account"
                  value={filters.account}
                  onChange={(event) => updateFilter("account", event.target.value)}
                  style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }}
                />
              </div>

              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                <label htmlFor="logs-target-host" style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>
                  {t("目标主机")}
                </label>
                <Input
                  id="logs-target-host"
                  value={filters.target_host}
                  onChange={(event) => updateFilter("target_host", event.target.value)}
                  style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }}
                />
              </div>
            </div>

            {/* 网络状态与操作 */}
            <div
              className="logs-inline-filters"
              style={{ display: "flex", flexWrap: "wrap", gap: "0.75rem", alignItems: "flex-end" }}
            >
              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                <label htmlFor="logs-proxy-type" style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>
                  {t("代理类型")}
                </label>
                <Select
                  id="logs-proxy-type"
                  value={filters.proxy_type}
                  onChange={(event) => updateFilter("proxy_type", event.target.value as ProxyTypeFilter)}
                  style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }}
                >
                  <option value="all">{t("全部")}</option>
                  <option value="1">{t("HTTP 正向代理")}</option>
                  <option value="2">{t("HTTP 反向代理")}</option>
                  <option value="3">{t("SOCKS5 正向代理")}</option>
                </Select>
              </div>

              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                <label htmlFor="logs-egress-ip" style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>
                  {t("出口 IP")}
                </label>
                <Input
                  id="logs-egress-ip"
                  value={filters.egress_ip}
                  onChange={(event) => updateFilter("egress_ip", event.target.value)}
                  style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }}
                />
              </div>

              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                <label htmlFor="logs-net-ok" style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>
                  {t("网络状态")}
                </label>
                <Select
                  id="logs-net-ok"
                  value={filters.net_ok}
                  onChange={(event) => updateFilter("net_ok", event.target.value as BoolFilter)}
                  style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }}
                >
                  <option value="all">{t("全部")}</option>
                  <option value="true">{t("成功")}</option>
                  <option value="false">{t("失败")}</option>
                </Select>
              </div>

              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                <label htmlFor="logs-http-status" style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>
                  {t("HTTP 状态")}
                </label>
                <Input
                  id="logs-http-status"
                  placeholder="100-599"
                  value={filters.http_status}
                  onChange={(event) => updateFilter("http_status", event.target.value)}
                  style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }}
                />
              </div>

              <div style={{ flex: "0 0 auto", display: "flex", gap: "0.5rem", marginBottom: "0.125rem", marginLeft: "auto" }}>
                <Button
                  size="sm"
                  variant="secondary"
                  onClick={() => void logsQuery.refetch()}
                  disabled={logsQuery.isFetching}
                  style={{ minHeight: "32px", height: "32px", padding: "0 0.75rem", display: "flex", alignItems: "center", gap: "0.25rem" }}
                >
                  <RefreshCw size={14} className={logsQuery.isFetching ? "spin" : undefined} />
                  {t("刷新")}
                </Button>
                <Button
                  size="sm"
                  variant="secondary"
                  onClick={resetFilters}
                  style={{ minHeight: "32px", height: "32px", padding: "0 0.75rem", display: "flex", alignItems: "center", gap: "0.25rem" }}
                >
                  <Eraser size={14} />
                  {t("重置")}
                </Button>
              </div>
            </div>
          </div>
        </div>

        {rangeInvalid ? <div className="callout callout-warning">{t("时间范围错误:开始时间必须早于结束时间,已暂不应用结束时间筛选。")}</div> : null}
        {httpStatusInvalid ? <div className="callout callout-warning">{t("HTTP 状态码需为 100-599 的整数,当前输入暂不应用。")}</div> : null}
      </Card>

      <Card className="nodes-table-card platform-cards-container subscriptions-table-card">
        {logsQuery.isLoading || isPageTransitioning ? <p className="muted">{t("正在加载日志...")}</p> : null}

        {logsQuery.isError ? (
          <div className="callout callout-error">
            <AlertTriangle size={14} />
            <span>{formatApiErrorMessage(logsQuery.error, t)}</span>
          </div>
        ) : null}

        {!logsQuery.isLoading && !isPageTransitioning && !visibleLogs.length ? (
          <div className="empty-box">
            <Sparkles size={16} />
            <p>{t("没有匹配日志")}</p>
          </div>
        ) : null}

        {visibleLogs.length ? (
          <DataTable
            data={visibleLogs}
            columns={logColumns}
            onRowClick={(log) => openDrawer(log.id)}
            selectedRowId={drawerVisible ? detailLogId : undefined}
            getRowId={(log) => log.id}
            wrapClassName="data-table-wrap-logs"
          />
        ) : null}

        <CursorPagination
          pageIndex={pageIndex}
          hasMore={hasMore}
          pageSize={filters.limit}
          pageSizeOptions={PAGE_SIZE_OPTIONS}
          disabled={isPageTransitioning}
          onPageSizeChange={(limit) => updateFilter("limit", limit)}
          onPrev={movePrev}
          onNext={moveNext}
        />
      </Card>

      {drawerVisible && detailLog ? (
        <div
          className="drawer-overlay"
          role="dialog"
          aria-modal="true"
          aria-label={t("请求日志详情 {{id}}", { id: detailLog.id })}
          onClick={() => setDrawerOpen(false)}
        >
          <Card className="drawer-panel" onClick={(event) => event.stopPropagation()}>
            <div className="drawer-header">
              <div>
                <h3>{detailLog.target_host || detailLog.account || t("请求日志详情")}</h3>
                <p>{detailLog.id}</p>
              </div>
              <div className="drawer-header-actions">
                <Button variant="ghost" size="sm" aria-label={t("关闭详情面板")} onClick={() => setDrawerOpen(false)}>
                  <X size={16} />
                </Button>
              </div>
            </div>

            <div className="platform-drawer-layout">
              <section className="platform-drawer-section">
                <div className="platform-drawer-section-head">
                  <h4>{t("日志摘要")}</h4>
                  <p>{t("请求时间、协议结果与平台路由信息。")}</p>
                </div>

                {detailQuery.isError ? (
                  <div className="callout callout-error">
                    <AlertTriangle size={14} />
                    <span>{formatApiErrorMessage(detailQuery.error, t)}</span>
                  </div>
                ) : null}

                <div className="stats-grid">
                  <div>
                    <span>{t("时间")}</span>
                    <p>{formatDateTime(detailLog.ts)}</p>
                  </div>
                  <div>
                    <span>{t("代理类型")}</span>
                    <p>{renderProxyTypeBadge(detailLog.proxy_type, "drawer")}</p>
                  </div>
                  <div>
                    <span>{t("HTTP")}</span>
                    <p>
                      {detailLog.http_method || "-"} {detailLog.http_status || "-"}
                    </p>
                  </div>

                  <div>
                    <span>{t("耗时")}</span>
                    <p>{detailLog.duration_ms} ms</p>
                  </div>
                  <div>
                    <span>{t("平台")}</span>
                    <p>{detailLog.platform_name || "-"}</p>
                  </div>
                  <div>
                    <span>{t("账号")}</span>
                    <p>{detailLog.account || "-"}</p>
                  </div>
                  <div>
                    <span>{t("出口 IP")}</span>
                    <p>{detailLog.egress_ip || "-"}</p>
                  </div>
                  <div>
                    <span>{t("客户端 IP")}</span>
                    <p>{detailLog.client_ip || "-"}</p>
                  </div>
                </div>
              </section>

              <section className="platform-drawer-section">
                <div className="platform-drawer-section-head">
                  <h4>{t("诊断")}</h4>
                  <p>{t("异常排查与连接状态分析。")}</p>
                </div>
                <div style={{
                  backgroundColor: "var(--surface)",
                  border: "1px solid var(--border)",
                  borderRadius: "12px",
                  padding: "16px",
                  fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
                  fontSize: "13px",
                  color: "var(--text-secondary)",
                  lineHeight: "1.6",
                }}>
                  {(detailLog.resin_error || detailLog.upstream_stage || detailLog.upstream_err_kind || detailLog.upstream_errno || detailLog.upstream_err_msg) ? (
                    <table style={{ borderCollapse: "collapse", width: "100%" }}>
                      <tbody>
                        {detailLog.resin_error ? (
                          <tr>
                            <td style={{ color: "var(--danger)", fontWeight: 600, paddingBottom: "8px", paddingRight: "16px", whiteSpace: "nowrap", verticalAlign: "top", width: "1%" }}>{t("Resin 错误:")}</td>
                            <td style={{ color: "var(--text)", paddingBottom: "8px", wordBreak: "break-all", verticalAlign: "top" }}>{detailLog.resin_error}</td>
                          </tr>
                        ) : null}
                        {detailLog.upstream_stage ? (
                          <tr>
                            <td style={{ color: "var(--warning)", fontWeight: 600, paddingBottom: "8px", paddingRight: "16px", whiteSpace: "nowrap", verticalAlign: "top", width: "1%" }}>{t("失败阶段:")}</td>
                            <td style={{ color: "var(--text)", paddingBottom: "8px", wordBreak: "break-all", verticalAlign: "top" }}>{detailLog.upstream_stage}</td>
                          </tr>
                        ) : null}
                        {detailLog.upstream_err_kind ? (
                          <tr>
                            <td style={{ fontWeight: 600, paddingBottom: "8px", paddingRight: "16px", whiteSpace: "nowrap", verticalAlign: "top", width: "1%" }}>{t("错误类型:")}</td>
                            <td style={{ color: "var(--text)", paddingBottom: "8px", wordBreak: "break-all", verticalAlign: "top" }}>{detailLog.upstream_err_kind}</td>
                          </tr>
                        ) : null}
                        {detailLog.upstream_errno ? (
                          <tr>
                            <td style={{ fontWeight: 600, paddingBottom: "8px", paddingRight: "16px", whiteSpace: "nowrap", verticalAlign: "top", width: "1%" }}>Errno:</td>
                            <td style={{ color: "var(--text)", paddingBottom: "8px", wordBreak: "break-all", verticalAlign: "top" }}>{detailLog.upstream_errno}</td>
                          </tr>
                        ) : null}
                        {detailLog.upstream_err_msg ? (
                          <tr>
                            <td style={{ fontWeight: 600, paddingBottom: "8px", paddingRight: "16px", whiteSpace: "nowrap", verticalAlign: "top", width: "1%" }}>{t("错误详情:")}</td>
                            <td style={{ color: "var(--text)", paddingBottom: "8px", wordBreak: "break-all", verticalAlign: "top" }}>{detailLog.upstream_err_msg}</td>
                          </tr>
                        ) : null}
                      </tbody>
                    </table>
                  ) : null}
                  {!detailLog.resin_error && !detailLog.upstream_stage && !detailLog.upstream_err_kind && !detailLog.upstream_err_msg ? (
                    <div style={{ color: "var(--success)", display: "flex", alignItems: "center", gap: "6px" }}>
                      <span style={{ display: "inline-block", width: "8px", height: "8px", borderRadius: "50%", backgroundColor: "var(--success)" }}></span>
                      {t("当前请求未产生异常诊断信息")}
                    </div>
                  ) : null}
                </div>
              </section>

              <section className="platform-drawer-section">
                <div className="platform-drawer-section-head">
                  <h4>{t("目标与节点")}</h4>
                  <p>{t("请求目标与命中节点信息。")}</p>
                </div>

                <div className="stats-grid">
                  <div>
                    <span>{t("目标地址")}</span>
                    <p>{detailLog.target_host || "-"}</p>
                    <code style={{ display: 'block', marginTop: '4px', fontSize: '11px', color: 'var(--text-muted)', wordBreak: 'break-all' }}>{detailLog.target_url || "-"}</code>
                  </div>

                  <div>
                    <span>{t("流量")}</span>
                    <p>{formatBytes((detailLog.ingress_bytes || 0) + (detailLog.egress_bytes || 0))}</p>
                    <div style={{ display: 'flex', gap: '8px', marginTop: '4px', fontSize: '11px', color: 'var(--text-muted)' }}>
                      <span>↓ {formatBytes(detailLog.ingress_bytes || 0)}</span>
                      <span>↑ {formatBytes(detailLog.egress_bytes || 0)}</span>
                    </div>
                  </div>

                  <div>
                    <span>{t("节点")}</span>
                    <p>{detailLog.node_tag || "-"}</p>
                    <code style={{ display: 'block', marginTop: '4px', fontSize: '11px', color: 'var(--text-muted)', wordBreak: 'break-all' }}>{detailLog.node_hash || "-"}</code>
                  </div>
                </div>
              </section>

              <section className="platform-drawer-section">
                <div className="platform-drawer-section-head">
                  <h4>{t("报文内容")}</h4>
                  <p>{t("查看请求/响应内容。")}</p>
                </div>

                {!detailLog.payload_present ? (
                  <p className="muted" style={{ fontSize: "13px" }}>{t("该条日志未记录报文内容。")}</p>
                ) : (
                  <section className="logs-payload-section">
                    <div className="logs-payload-tabs">
                      {PAYLOAD_TABS.map((tab) => {
                        const labelMap: Record<PayloadTab, string> = {
                          request: t("请求"),
                          response: t("响应"),
                        };

                        const truncated = payloadQuery.data
                          ? (tab === "request"
                            ? payloadQuery.data.truncated.req_headers || payloadQuery.data.truncated.req_body
                            : payloadQuery.data.truncated.resp_headers || payloadQuery.data.truncated.resp_body)
                          : false;

                        return (
                          <button
                            key={tab}
                            type="button"
                            className={`payload-tab ${payloadTab === tab ? "payload-tab-active" : ""}`}
                            onClick={() => setPayloadTab(tab)}
                          >
                            <span>{labelMap[tab]}</span>
                            {truncated ? <Badge variant="warning">{t("已截断")}</Badge> : null}
                          </button>
                        );
                      })}
                    </div>

                    {payloadQuery.isError ? (
                      <div className="callout callout-error">
                        <AlertTriangle size={14} />
                        <span>{formatApiErrorMessage(payloadQuery.error, t)}</span>
                      </div>
                    ) : null}

                    {(payloadQuery.isFetching || payloadDecodePending) && !(payloadData.headers || payloadData.body) ? (
                      <div className="callout" style={{ marginTop: "12px", color: "var(--text-secondary)" }}>
                        <RefreshCw size={14} className="spin" />
                        <span>{t("加载报文内容中...")}</span>
                      </div>
                    ) : (
                      <>
                        <pre className="logs-payload-box" style={{ minHeight: "auto", border: "1px solid var(--border)", marginBottom: "8px" }}>
                          {payloadData.headers || t("(空 Headers)")}
                        </pre>
                        <pre className="logs-payload-box">
                          {payloadData.body || t("(空 Body)")}
                        </pre>
                      </>
                    )}
                  </section>
                )}
              </section>
            </div>
          </Card>
        </div>
      ) : null}
    </section>
  );
}