File size: 47,424 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
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, RefreshCw, RotateCcw, Save, Sparkles } from "lucide-react";
import { useMemo, useState } from "react";
import { Badge } from "../../components/ui/Badge";
import { Button } from "../../components/ui/Button";
import { Card } from "../../components/ui/Card";
import { Input } from "../../components/ui/Input";
import { Switch } from "../../components/ui/Switch";
import { Textarea } from "../../components/ui/Textarea";
import { ToastContainer } from "../../components/ui/Toast";
import { useToast } from "../../hooks/useToast";
import i18next, { useI18n } from "../../i18n";
import { formatApiErrorMessage } from "../../lib/error-message";
import { getEnvConfig, patchSystemConfig, getSystemConfig, getDefaultSystemConfig } from "./api";
import type { RuntimeConfig, RuntimeConfigPatch } from "./types";

type RuntimeConfigForm = {
  request_log_enabled: boolean;
  reverse_proxy_log_detail_enabled: boolean;
  reverse_proxy_log_req_headers_max_bytes: string;
  reverse_proxy_log_req_body_max_bytes: string;
  reverse_proxy_log_resp_headers_max_bytes: string;
  reverse_proxy_log_resp_body_max_bytes: string;
  max_consecutive_failures: string;
  max_latency_test_interval: string;
  max_authority_latency_test_interval: string;
  max_egress_test_interval: string;
  latency_test_url: string;
  latency_authorities_raw: string;
  p2c_latency_window: string;
  latency_decay_window: string;
  cache_flush_interval: string;
  cache_flush_dirty_threshold: string;
};

const EDITABLE_FIELDS: Array<keyof RuntimeConfig> = [
  "request_log_enabled",
  "reverse_proxy_log_detail_enabled",
  "reverse_proxy_log_req_headers_max_bytes",
  "reverse_proxy_log_req_body_max_bytes",
  "reverse_proxy_log_resp_headers_max_bytes",
  "reverse_proxy_log_resp_body_max_bytes",
  "max_consecutive_failures",
  "max_latency_test_interval",
  "max_authority_latency_test_interval",
  "max_egress_test_interval",
  "latency_test_url",
  "latency_authorities",
  "p2c_latency_window",
  "latency_decay_window",
  "cache_flush_interval",
  "cache_flush_dirty_threshold",
];

const FIELD_LABELS: Record<keyof RuntimeConfig, string> = {
  request_log_enabled: "启用请求日志",
  reverse_proxy_log_detail_enabled: "记录详细反代日志",
  reverse_proxy_log_req_headers_max_bytes: "请求头最大字节数",
  reverse_proxy_log_req_body_max_bytes: "请求体最大字节数",
  reverse_proxy_log_resp_headers_max_bytes: "响应头最大字节数",
  reverse_proxy_log_resp_body_max_bytes: "响应体最大字节数",
  max_consecutive_failures: "最大连续失败次数",
  max_latency_test_interval: "节点延迟最大测试间隔",
  max_authority_latency_test_interval: "权威域名最大测试间隔",
  max_egress_test_interval: "出口 IP 更新检查间隔",
  latency_test_url: "延迟测试目标 URL",
  latency_authorities: "延迟测试权威域名列表",
  p2c_latency_window: "P2C 延迟衰减窗口",
  latency_decay_window: "历史延迟衰减窗口",
  cache_flush_interval: "缓存异步刷盘间隔",
  cache_flush_dirty_threshold: "缓存刷盘脏阈值",
};

const ALLOCATION_POLICY_LABELS: Record<string, string> = {
  BALANCED: "均衡",
  PREFER_LOW_LATENCY: "优先低延迟",
  PREFER_IDLE_IP: "优先空闲出口 IP",
};

const MISS_ACTION_LABELS: Record<string, string> = {
  TREAT_AS_EMPTY: "按空账号处理",
  REJECT: "拒绝代理请求",
};

const EMPTY_ACCOUNT_BEHAVIOR_LABELS: Record<string, string> = {
  RANDOM: "随机路由",
  FIXED_HEADER: "提取指定请求头作为 Account",
  ACCOUNT_HEADER_RULE: "按照全局请求头规则提取 Account",
};

function configToForm(config: RuntimeConfig): RuntimeConfigForm {
  return {
    request_log_enabled: config.request_log_enabled,
    reverse_proxy_log_detail_enabled: config.reverse_proxy_log_detail_enabled,
    reverse_proxy_log_req_headers_max_bytes: String(config.reverse_proxy_log_req_headers_max_bytes),
    reverse_proxy_log_req_body_max_bytes: String(config.reverse_proxy_log_req_body_max_bytes),
    reverse_proxy_log_resp_headers_max_bytes: String(config.reverse_proxy_log_resp_headers_max_bytes),
    reverse_proxy_log_resp_body_max_bytes: String(config.reverse_proxy_log_resp_body_max_bytes),
    max_consecutive_failures: String(config.max_consecutive_failures),
    max_latency_test_interval: config.max_latency_test_interval,
    max_authority_latency_test_interval: config.max_authority_latency_test_interval,
    max_egress_test_interval: config.max_egress_test_interval,
    latency_test_url: config.latency_test_url,
    latency_authorities_raw: config.latency_authorities.join("\n"),
    p2c_latency_window: config.p2c_latency_window,
    latency_decay_window: config.latency_decay_window,
    cache_flush_interval: config.cache_flush_interval,
    cache_flush_dirty_threshold: String(config.cache_flush_dirty_threshold),
  };
}

function requiredFieldLabel(field: string): string {
  return i18next.t(field);
}

function parseNonNegativeInt(field: string, raw: string): number {
  const value = raw.trim();
  if (!value) {
    throw new Error(i18next.t("{{field}} 不能为空", { field: requiredFieldLabel(field) }));
  }
  const parsed = Number(value);
  if (!Number.isInteger(parsed) || parsed < 0) {
    throw new Error(i18next.t("{{field}} 必须是非负整数", { field: requiredFieldLabel(field) }));
  }
  return parsed;
}

function parseDurationField(field: string, raw: string): string {
  const value = raw.trim();
  if (!value) {
    throw new Error(i18next.t("{{field}} 不能为空", { field: requiredFieldLabel(field) }));
  }
  return value;
}

function parseAuthorities(raw: string): string[] {
  const items = raw
    .split(/[\n,]/)
    .map((item) => item.trim())
    .filter(Boolean);

  return Array.from(new Set(items));
}

function parseForm(form: RuntimeConfigForm): RuntimeConfig {
  const latencyURL = form.latency_test_url.trim();
  if (!latencyURL) {
    throw new Error("延迟测试目标 URL 不能为空");
  }
  if (!latencyURL.startsWith("http://") && !latencyURL.startsWith("https://")) {
    throw new Error("延迟测试目标 URL 必须是 http/https 地址");
  }

  return {
    request_log_enabled: form.request_log_enabled,
    reverse_proxy_log_detail_enabled: form.reverse_proxy_log_detail_enabled,
    reverse_proxy_log_req_headers_max_bytes: parseNonNegativeInt(
      "请求头最大字节数",
      form.reverse_proxy_log_req_headers_max_bytes,
    ),
    reverse_proxy_log_req_body_max_bytes: parseNonNegativeInt("请求体最大字节数", form.reverse_proxy_log_req_body_max_bytes),
    reverse_proxy_log_resp_headers_max_bytes: parseNonNegativeInt(
      "响应头最大字节数",
      form.reverse_proxy_log_resp_headers_max_bytes,
    ),
    reverse_proxy_log_resp_body_max_bytes: parseNonNegativeInt(
      "响应体最大字节数",
      form.reverse_proxy_log_resp_body_max_bytes,
    ),
    max_consecutive_failures: parseNonNegativeInt("最大连续失败次数", form.max_consecutive_failures),
    max_latency_test_interval: parseDurationField("节点延迟最大测试间隔", form.max_latency_test_interval),
    max_authority_latency_test_interval: parseDurationField(
      "权威域名最大测试间隔",
      form.max_authority_latency_test_interval,
    ),
    max_egress_test_interval: parseDurationField("出口 IP 更新检查间隔", form.max_egress_test_interval),
    latency_test_url: latencyURL,
    latency_authorities: parseAuthorities(form.latency_authorities_raw),
    p2c_latency_window: parseDurationField("P2C 延迟衰减窗口", form.p2c_latency_window),
    latency_decay_window: parseDurationField("历史延迟衰减窗口", form.latency_decay_window),
    cache_flush_interval: parseDurationField("缓存异步刷盘间隔", form.cache_flush_interval),
    cache_flush_dirty_threshold: parseNonNegativeInt("缓存刷盘脏阈值", form.cache_flush_dirty_threshold),
  };
}

function displayAllocationPolicy(value: string): string {
  return ALLOCATION_POLICY_LABELS[value] ?? value;
}

function displayMissAction(value: string): string {
  return MISS_ACTION_LABELS[value] ?? value;
}

function displayEmptyAccountBehavior(value: string): string {
  return EMPTY_ACCOUNT_BEHAVIOR_LABELS[value] ?? value;
}

function arrayEquals(a: string[], b: string[]): boolean {
  if (a.length !== b.length) {
    return false;
  }
  for (let i = 0; i < a.length; i += 1) {
    if (a[i] !== b[i]) {
      return false;
    }
  }
  return true;
}

function buildPatch(current: RuntimeConfig, next: RuntimeConfig): RuntimeConfigPatch {
  const patch: RuntimeConfigPatch = {};
  const patchMutable = patch as Record<string, unknown>;

  for (const field of EDITABLE_FIELDS) {
    const currentValue = current[field];
    const nextValue = next[field];

    if (Array.isArray(currentValue) && Array.isArray(nextValue)) {
      if (!arrayEquals(currentValue, nextValue)) {
        patchMutable[field] = nextValue;
      }
      continue;
    }

    if (currentValue !== nextValue) {
      patchMutable[field] = nextValue;
    }
  }

  return patch;
}

export function SystemConfigPage() {
  const { t } = useI18n();
  const [draftForm, setDraftForm] = useState<RuntimeConfigForm | null>(null);
  const [customPatchText, setCustomPatchText] = useState<string | null>(null);
  const { toasts, showToast, dismissToast } = useToast();
  const queryClient = useQueryClient();

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

  const defaultConfigQuery = useQuery({
    queryKey: ["system-config-default"],
    queryFn: getDefaultSystemConfig,
    staleTime: 30_000,
  });

  const envConfigQuery = useQuery({
    queryKey: ["system-config-env"],
    queryFn: getEnvConfig,
    staleTime: Infinity, // Env config does not change at runtime
  });

  const baseline = configQuery.data ?? null;
  const defaultBaseline = defaultConfigQuery.data ?? null;
  const envBaseline = envConfigQuery.data ?? null;

  const form = useMemo(() => {
    if (!baseline) {
      return null;
    }
    return draftForm ?? configToForm(baseline);
  }, [baseline, draftForm]);

  const parsedResult = useMemo(() => {
    if (!form) {
      return { config: null as RuntimeConfig | null, error: "" };
    }

    try {
      return { config: parseForm(form), error: "" };
    } catch (error) {
      return { config: null, error: formatApiErrorMessage(error, t) };
    }
  }, [form, t]);

  const patchPreview = useMemo<RuntimeConfigPatch>(() => {
    if (!baseline || !parsedResult.config) {
      return {};
    }
    return buildPatch(baseline, parsedResult.config);
  }, [baseline, parsedResult.config]);

  const changedKeys = useMemo(() => Object.keys(patchPreview) as Array<keyof RuntimeConfig>, [patchPreview]);
  const hasUnsavedChanges = changedKeys.length > 0;

  const saveMutation = useMutation({
    mutationFn: async () => {
      if (!baseline || !form) {
        throw new Error("配置尚未加载完成");
      }
      let patchToSend: RuntimeConfigPatch;
      if (customPatchText !== null) {
        try {
          patchToSend = JSON.parse(customPatchText);
        } catch {
          throw new Error("手动编辑的 JSON 格式有误,请检查");
        }
      } else {
        const parsed = parseForm(form);
        patchToSend = buildPatch(baseline, parsed);
      }

      const changedCount = Object.keys(patchToSend).length;
      if (!changedCount) {
        throw new Error("没有可提交的变更");
      }
      const updated = await patchSystemConfig(patchToSend);
      return { updated, changedCount };
    },
    onSuccess: ({ updated, changedCount }) => {
      queryClient.setQueryData(["system-config"], updated);
      setDraftForm(null);
      setCustomPatchText(null);
      showToast("success", t("配置已更新({{count}} 项变更)", { count: changedCount }));
    },
    onError: (error) => {
      showToast("error", formatApiErrorMessage(error, t));
    },
  });

  const setFormField = <K extends keyof RuntimeConfigForm>(key: K, value: RuntimeConfigForm[K]) => {
    setDraftForm((prev) => {
      if (!baseline) {
        return prev;
      }
      const source = prev ?? configToForm(baseline);
      return { ...source, [key]: value };
    });
  };

  const handleRestoreDefault = (key: keyof RuntimeConfigForm) => {
    if (!defaultBaseline || !baseline) {
      showToast("error", "默认配置尚未加载");
      return;
    }

    const defaultForm = configToForm(defaultBaseline);
    const value = defaultForm[key];

    setDraftForm((prev) => {
      const source = prev ?? configToForm(baseline);
      return { ...source, [key]: value };
    });
  };

  const renderRestoreButton = (fieldKey: keyof RuntimeConfigForm) => {
    const displayVal = defaultBaseline ? (() => {
      const val = configToForm(defaultBaseline)[fieldKey];
      if (typeof val === "boolean") return val ? t("开启") : t("关闭");
      if (val === "") return t("空");
      return String(val);
    })() : "";

    return (
      <button
        type="button"
        title={displayVal ? t("恢复为默认值: {{value}}", { value: displayVal }) : t("恢复为默认值")}
        onClick={() => handleRestoreDefault(fieldKey)}
        style={{
          background: "transparent",
          border: "none",
          cursor: "pointer",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          color: "var(--text-muted, #888)",
          padding: "4px",
          marginLeft: "4px",
          opacity: 0.6,
          transition: "opacity 0.2s"
        }}
        onMouseEnter={(e) => e.currentTarget.style.opacity = "1"}
        onMouseLeave={(e) => e.currentTarget.style.opacity = "0.6"}
      >
        <RotateCcw size={14} />
      </button>
    );
  };

  const resetDraft = () => {
    setDraftForm(null);
    setCustomPatchText(null);
  };

  const reloadFromServer = async () => {
    if (hasUnsavedChanges) {
      const confirmed = window.confirm(t("当前有未保存变更,确认丢弃并重新加载运行时配置?"));
      if (!confirmed) {
        return;
      }
    }

    setDraftForm(null);
    setCustomPatchText(null);
    const result = await configQuery.refetch();
    if (result.data) {
      showToast("success", t("已加载最新运行时配置"));
    }
  };

  const handlePatchEdit = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setCustomPatchText(e.target.value);
  };

  const defaultPatchText = useMemo(() => {
    return JSON.stringify(patchPreview, null, 2);
  }, [patchPreview]);

  const displayedPatchText = customPatchText ?? defaultPatchText;

  const isSaveDisabled = saveMutation.isPending || (customPatchText === null && (Boolean(parsedResult.error) || !hasUnsavedChanges));

  return (
    <section className="syscfg-page">
      <header className="module-header">
        <div>
          <h2>{t("系统配置")}</h2>
          <p className="module-description">{t("按需调整系统参数,保存后立即生效。")}</p>
        </div>
      </header>

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

      {!form ? (
        <Card className="syscfg-form-card platform-directory-card">
          {(configQuery.isLoading || envConfigQuery.isLoading) ? <p className="muted">{t("正在加载配置...")}</p> : null}
          {configQuery.isError ? (
            <div className="callout callout-error">
              <AlertTriangle size={14} />
              <span>{formatApiErrorMessage(configQuery.error, t)}</span>
            </div>
          ) : null}
          {envConfigQuery.isError ? (
            <div className="callout callout-error">
              <AlertTriangle size={14} />
              <span>{t("静态配置加载失败")}: {formatApiErrorMessage(envConfigQuery.error, t)}</span>
            </div>
          ) : null}
        </Card>
      ) : (
        <div className="syscfg-layout">
          <div className="syscfg-main" style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
            <Card className="syscfg-form-card platform-directory-card">
              <div className="detail-header">
                <div>
                  <h3>{t("运行时配置")}</h3>
                  <p>{t("按分类查看和修改设置,可随时撤销未保存更改。")}</p>
                </div>
                <Button variant="secondary" size="sm" onClick={() => void reloadFromServer()} disabled={configQuery.isFetching}>
                  <RefreshCw size={16} className={configQuery.isFetching ? "spin" : undefined} />
                  {t("刷新")}
                </Button>
              </div>

              <section className="syscfg-section">
                <h4>{t("基础与健康检查")}</h4>
                <div className="form-grid">
                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-max-fail" style={{ margin: 0 }}>
                        {t("最大连续失败次数")}
                      </label>
                      {renderRestoreButton("max_consecutive_failures")}
                    </div>
                    <Input
                      id="sys-max-fail"
                      type="number"
                      min={0}
                      value={form.max_consecutive_failures}
                      onChange={(event) => setFormField("max_consecutive_failures", event.target.value)}
                    />
                  </div>
                </div>
              </section>

              <section className="syscfg-section">
                <h4>{t("请求日志")}</h4>
                <div className="syscfg-checkbox-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: "var(--surface-sunken, rgba(0,0,0,0.02))", padding: "12px 16px", borderRadius: "8px", border: "1px solid var(--border)" }}>
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <span className="field-label" style={{ margin: 0, fontWeight: 500 }}>{t("启用请求日志")}</span>
                      {renderRestoreButton("request_log_enabled")}
                    </div>
                    <Switch
                      checked={form.request_log_enabled}
                      onChange={(event) => setFormField("request_log_enabled", event.target.checked)}
                    />
                  </div>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: "var(--surface-sunken, rgba(0,0,0,0.02))", padding: "12px 16px", borderRadius: "8px", border: "1px solid var(--border)" }}>
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <span className="field-label" style={{ margin: 0, fontWeight: 500 }}>{t("记录详细反代日志")}</span>
                      {renderRestoreButton("reverse_proxy_log_detail_enabled")}
                    </div>
                    <Switch
                      checked={form.reverse_proxy_log_detail_enabled}
                      onChange={(event) => setFormField("reverse_proxy_log_detail_enabled", event.target.checked)}
                    />
                  </div>
                </div>

                <div className="form-grid" style={{ marginTop: "16px" }}>
                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-req-h-max" style={{ margin: 0 }}>
                        {t("请求头最大字节数")}
                      </label>
                      {renderRestoreButton("reverse_proxy_log_req_headers_max_bytes")}
                    </div>
                    <Input
                      id="sys-req-h-max"
                      type="number"
                      min={0}
                      value={form.reverse_proxy_log_req_headers_max_bytes}
                      onChange={(event) => setFormField("reverse_proxy_log_req_headers_max_bytes", event.target.value)}
                    />
                  </div>

                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-req-b-max" style={{ margin: 0 }}>
                        {t("请求体最大字节数")}
                      </label>
                      {renderRestoreButton("reverse_proxy_log_req_body_max_bytes")}
                    </div>
                    <Input
                      id="sys-req-b-max"
                      type="number"
                      min={0}
                      value={form.reverse_proxy_log_req_body_max_bytes}
                      onChange={(event) => setFormField("reverse_proxy_log_req_body_max_bytes", event.target.value)}
                    />
                  </div>

                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-resp-h-max" style={{ margin: 0 }}>
                        {t("响应头最大字节数")}
                      </label>
                      {renderRestoreButton("reverse_proxy_log_resp_headers_max_bytes")}
                    </div>
                    <Input
                      id="sys-resp-h-max"
                      type="number"
                      min={0}
                      value={form.reverse_proxy_log_resp_headers_max_bytes}
                      onChange={(event) => setFormField("reverse_proxy_log_resp_headers_max_bytes", event.target.value)}
                    />
                  </div>

                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-resp-b-max" style={{ margin: 0 }}>
                        {t("响应体最大字节数")}
                      </label>
                      {renderRestoreButton("reverse_proxy_log_resp_body_max_bytes")}
                    </div>
                    <Input
                      id="sys-resp-b-max"
                      type="number"
                      min={0}
                      value={form.reverse_proxy_log_resp_body_max_bytes}
                      onChange={(event) => setFormField("reverse_proxy_log_resp_body_max_bytes", event.target.value)}
                    />
                  </div>
                </div>
              </section>

              <section className="syscfg-section">
                <h4>{t("探测与路由")}</h4>
                <div className="form-grid">
                  <div className="field-group field-span-2">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-latency-url" style={{ margin: 0 }}>
                        {t("延迟测试目标 URL")}
                      </label>
                      {renderRestoreButton("latency_test_url")}
                    </div>
                    <Input
                      id="sys-latency-url"
                      value={form.latency_test_url}
                      onChange={(event) => setFormField("latency_test_url", event.target.value)}
                    />
                  </div>

                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-max-latency-int" style={{ margin: 0 }}>
                        {t("节点延迟最大测试间隔")}
                      </label>
                      {renderRestoreButton("max_latency_test_interval")}
                    </div>
                    <Input
                      id="sys-max-latency-int"
                      value={form.max_latency_test_interval}
                      onChange={(event) => setFormField("max_latency_test_interval", event.target.value)}
                    />
                  </div>

                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-max-auth-latency-int" style={{ margin: 0 }}>
                        {t("权威域名最大测试间隔")}
                      </label>
                      {renderRestoreButton("max_authority_latency_test_interval")}
                    </div>
                    <Input
                      id="sys-max-auth-latency-int"
                      value={form.max_authority_latency_test_interval}
                      onChange={(event) => setFormField("max_authority_latency_test_interval", event.target.value)}
                    />
                  </div>

                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-max-egress-int" style={{ margin: 0 }}>
                        {t("出口 IP 更新检查间隔")}
                      </label>
                      {renderRestoreButton("max_egress_test_interval")}
                    </div>
                    <Input
                      id="sys-max-egress-int"
                      value={form.max_egress_test_interval}
                      onChange={(event) => setFormField("max_egress_test_interval", event.target.value)}
                    />
                  </div>

                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-p2c-window" style={{ margin: 0 }}>
                        {t("P2C 延迟衰减窗口")}
                      </label>
                      {renderRestoreButton("p2c_latency_window")}
                    </div>
                    <Input
                      id="sys-p2c-window"
                      value={form.p2c_latency_window}
                      onChange={(event) => setFormField("p2c_latency_window", event.target.value)}
                    />
                  </div>

                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-decay-window" style={{ margin: 0 }}>
                        {t("历史延迟衰减窗口")}
                      </label>
                      {renderRestoreButton("latency_decay_window")}
                    </div>
                    <Input
                      id="sys-decay-window"
                      value={form.latency_decay_window}
                      onChange={(event) => setFormField("latency_decay_window", event.target.value)}
                    />
                  </div>

                  <div className="field-group field-span-2">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-latency-authorities" style={{ margin: 0 }}>
                        {t("延迟测试权威域名列表")}
                      </label>
                      {renderRestoreButton("latency_authorities_raw")}
                    </div>
                    <Textarea
                      id="sys-latency-authorities"
                      rows={4}
                      placeholder={"gstatic.com\ngoogle.com\ncloudflare.com"}
                      value={form.latency_authorities_raw}
                      onChange={(event) => setFormField("latency_authorities_raw", event.target.value)}
                    />
                  </div>
                </div>
              </section>

              <section className="syscfg-section">
                <h4>{t("持久化策略")}</h4>
                <div className="form-grid">
                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-cache-flush-int" style={{ margin: 0 }}>
                        {t("缓存异步刷盘间隔")}
                      </label>
                      {renderRestoreButton("cache_flush_interval")}
                    </div>
                    <Input
                      id="sys-cache-flush-int"
                      value={form.cache_flush_interval}
                      onChange={(event) => setFormField("cache_flush_interval", event.target.value)}
                    />
                  </div>

                  <div className="field-group">
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <label className="field-label" htmlFor="sys-cache-threshold" style={{ margin: 0 }}>
                        {t("缓存刷盘脏阈值")}
                      </label>
                      {renderRestoreButton("cache_flush_dirty_threshold")}
                    </div>
                    <Input
                      id="sys-cache-threshold"
                      type="number"
                      min={0}
                      value={form.cache_flush_dirty_threshold}
                      onChange={(event) => setFormField("cache_flush_dirty_threshold", event.target.value)}
                    />
                  </div>

                </div>
              </section>
            </Card>

            {envBaseline && (
              <Card className="syscfg-form-card platform-directory-card syscfg-static-card">
                <div className="detail-header">
                  <div>
                    <h3>{t("静态配置")}</h3>
                    <p>{t("来自环境变量和启动参数的只读配置。")}</p>
                  </div>
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={async () => {
                      const result = await envConfigQuery.refetch();
                      if (result.data) showToast("success", t("已加载最新静态配置"));
                    }}
                    disabled={envConfigQuery.isFetching}
                  >
                    <RefreshCw size={16} className={envConfigQuery.isFetching ? "spin" : undefined} />
                    {t("刷新")}
                  </Button>
                </div>

                <section className="syscfg-section">
                  <h4>{t("目录与端口")}</h4>
                  <div className="form-grid">
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("数据缓存目录")}</label>
                      <Input readOnly disabled value={envBaseline.cache_dir} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("状态存储目录")}</label>
                      <Input readOnly disabled value={envBaseline.state_dir} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("日志保留目录")}</label>
                      <Input readOnly disabled value={envBaseline.log_dir} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("统一监听地址")}</label>
                      <Input readOnly disabled value={envBaseline.listen_address} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("统一服务端口")}</label>
                      <Input readOnly disabled value={String(envBaseline.resin_port)} />
                    </div>
                  </div>
                </section>

                <section className="syscfg-section">
                  <h4>{t("全局限额与性能调优")}</h4>
                  <div className="form-grid">
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("控制面最大请求体")}</label>
                      <Input readOnly disabled value={String(envBaseline.api_max_body_bytes)} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("最大延迟表条目数")}</label>
                      <Input readOnly disabled value={String(envBaseline.max_latency_table_entries)} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("节点拨测并发数")}</label>
                      <Input readOnly disabled value={String(envBaseline.probe_concurrency)} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("拨测超时时间")}</label>
                      <Input readOnly disabled value={envBaseline.probe_timeout} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("资源获取超时时间")}</label>
                      <Input readOnly disabled value={envBaseline.resource_fetch_timeout} />
                    </div>
                    <div className="field-group field-span-2">
                      <label className="field-label" style={{ margin: 0 }}>{t("节点 DNS 上游")}</label>
                      <Textarea
                        readOnly
                        disabled
                        rows={3}
                        value={envBaseline.node_dns_upstreams?.join("\n") || t("无")}
                      />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("GeoIP 更新计划")}</label>
                      <Input readOnly disabled value={envBaseline.geoip_update_schedule} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("代理传输最大空闲连接")}</label>
                      <Input readOnly disabled value={String(envBaseline.proxy_transport_max_idle_conns)} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("单主机最大空闲连接")}</label>
                      <Input readOnly disabled value={String(envBaseline.proxy_transport_max_idle_conns_per_host)} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("空闲连接超时时间")}</label>
                      <Input readOnly disabled value={envBaseline.proxy_transport_idle_conn_timeout} />
                    </div>
                    <div className="field-group field-span-2">
                      <label className="field-label" style={{ margin: 0 }}>{t("代理直连目标")}</label>
                      <Textarea
                        readOnly
                        disabled
                        rows={3}
                        value={envBaseline.proxy_bypass_rules?.join("\n") || t("无")}
                      />
                    </div>
                  </div>
                </section>

                <section className="syscfg-section">
                  <h4>{t("默认平台回退规则")}</h4>
                  <div className="form-grid">
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("默认粘性会话 TTL")}</label>
                      <Input readOnly disabled value={envBaseline.default_platform_sticky_ttl} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("默认节点分配策略")}</label>
                      <Input readOnly disabled value={t(displayAllocationPolicy(envBaseline.default_platform_allocation_policy))} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("默认反代不匹配行为")}</label>
                      <Input readOnly disabled value={t(displayMissAction(envBaseline.default_platform_reverse_proxy_miss_action))} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("默认反代空账号行为")}</label>
                      <Input
                        readOnly
                        disabled
                        value={t(displayEmptyAccountBehavior(envBaseline.default_platform_reverse_proxy_empty_account_behavior))}
                      />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("默认反代固定账号 Header 列表")}</label>
                      <Textarea
                        readOnly
                        disabled
                        rows={3}
                        value={envBaseline.default_platform_reverse_proxy_fixed_account_header || t("无")}
                      />
                    </div>
                    <div className="field-group field-span-2">
                      <label className="field-label" style={{ margin: 0 }}>{t("默认正则黑名单")}</label>
                      <Textarea readOnly disabled rows={3} value={envBaseline.default_platform_regex_filters?.join("\n") || t("无")} />
                    </div>
                    <div className="field-group field-span-2">
                      <label className="field-label" style={{ margin: 0 }}>{t("默认地区黑名单")}</label>
                      <Textarea readOnly disabled rows={2} value={envBaseline.default_platform_region_filters?.join(",") || t("无")} />
                    </div>
                  </div>
                </section>

                <section className="syscfg-section">
                  <h4>{t("请求日志落库")}</h4>
                  <div className="form-grid">
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("队列大小")}</label>
                      <Input readOnly disabled value={String(envBaseline.request_log_queue_size)} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("落盘批大小")}</label>
                      <Input readOnly disabled value={String(envBaseline.request_log_queue_flush_batch_size)} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("落盘间隔")}</label>
                      <Input readOnly disabled value={envBaseline.request_log_queue_flush_interval} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("数据库保留阈值")}</label>
                      <Input readOnly disabled value={envBaseline.request_log_db_max_mb + " MB"} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("数据库旧分片保留数")}</label>
                      <Input readOnly disabled value={String(envBaseline.request_log_db_retain_count)} />
                    </div>
                  </div>
                </section>

                <section className="syscfg-section">
                  <h4>{t("可观测性指标")}</h4>
                  <div className="form-grid">
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("吞吐量抽样间隔")}</label>
                      <Input readOnly disabled value={envBaseline.metric_throughput_interval_seconds + "s"} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("吞吐量保留时间")}</label>
                      <Input readOnly disabled value={envBaseline.metric_throughput_retention_seconds + "s"} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("连接数抽样间隔")}</label>
                      <Input readOnly disabled value={envBaseline.metric_connections_interval_seconds + "s"} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("连接数保留时间")}</label>
                      <Input readOnly disabled value={envBaseline.metric_connections_retention_seconds + "s"} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("租期与连接指标分桶数")}</label>
                      <Input readOnly disabled value={envBaseline.metric_bucket_seconds + "s"} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("租期抽样间隔")}</label>
                      <Input readOnly disabled value={envBaseline.metric_leases_interval_seconds + "s"} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("租期保留时间")}</label>
                      <Input readOnly disabled value={envBaseline.metric_leases_retention_seconds + "s"} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("延迟统计桶宽")}</label>
                      <Input readOnly disabled value={envBaseline.metric_latency_bin_width_ms + "ms"} />
                    </div>
                    <div className="field-group">
                      <label className="field-label" style={{ margin: 0 }}>{t("延迟统计截断值")}</label>
                      <Input readOnly disabled value={envBaseline.metric_latency_bin_overflow_ms + "ms"} />
                    </div>
                  </div>
                </section>

                <section className="syscfg-section">
                  <h4>{t("服务鉴权状态")}</h4>
                  <div className="syscfg-checkbox-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: "var(--surface-sunken, rgba(0,0,0,0.02))", padding: "12px 16px", borderRadius: "8px", border: "1px solid var(--border)", opacity: 0.7 }}>
                      <span className="field-label" style={{ margin: 0, fontWeight: 500 }}>{t("已配置管理端令牌")}</span>
                      <Switch checked={envBaseline.admin_token_set} disabled />
                    </div>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: "var(--surface-sunken, rgba(0,0,0,0.02))", padding: "12px 16px", borderRadius: "8px", border: "1px solid var(--border)", opacity: 0.7 }}>
                      <span className="field-label" style={{ margin: 0, fontWeight: 500 }}>{t("已配置代理令牌")}</span>
                      <Switch checked={envBaseline.proxy_token_set} disabled />
                    </div>
                  </div>
                </section>
              </Card>
            )}
          </div>

          <div className="syscfg-side">
            <Card className="syscfg-summary-card platform-directory-card">
              <div className="detail-header">
                <div>
                  <h3>{t("变更摘要")}</h3>
                  <p>{hasUnsavedChanges ? t("{{count}} 项待提交", { count: changedKeys.length }) : t("当前无未保存改动")}</p>
                </div>
              </div>

              {parsedResult.error && customPatchText === null ? (
                <div className="callout callout-error">
                  <AlertTriangle size={14} />
                  <span>{parsedResult.error}</span>
                </div>
              ) : null}

              {changedKeys.length ? (
                <div className="syscfg-change-list">
                  {changedKeys.map((field) => (
                    <Badge key={field} variant="neutral">
                      {t(FIELD_LABELS[field])}
                    </Badge>
                  ))}
                </div>
              ) : (
                <div className="empty-box">
                  <Sparkles size={16} />
                  <p>{t("修改后会在这里显示变更项")}</p>
                </div>
              )}

              <div style={{ marginTop: "16px" }}>
                <p style={{ fontSize: "12px", color: "var(--text-muted)", marginBottom: "8px" }}>
                  {t("保存内容预览")} {customPatchText !== null && <span style={{ color: "var(--primary)" }}>{t("(已手动修改)")}</span>}
                </p>
                <Textarea
                  value={displayedPatchText}
                  onChange={handlePatchEdit}
                  rows={10}
                  style={{ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace', fontSize: "12px", width: "100%", resize: "vertical", backgroundColor: "var(--surface-sunken)", border: "1px solid var(--border)", borderRadius: "var(--radius)" }}
                  spellCheck={false}
                />
              </div>

              <div className="detail-actions" style={{ justifyContent: "flex-end", marginTop: "16px" }}>
                <Button
                  onClick={() => void saveMutation.mutateAsync()}
                  disabled={isSaveDisabled}
                >
                  <Save size={14} />
                  {saveMutation.isPending ? t("保存中...") : t("保存配置")}
                </Button>
                <Button variant="ghost" onClick={resetDraft} disabled={(customPatchText === null && !hasUnsavedChanges) || saveMutation.isPending}>
                  <RotateCcw size={14} />
                  {t("重置草稿")}
                </Button>
              </div>
            </Card>
          </div>
        </div>
      )}
    </section>
  );
}