mgui-core 0.6.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
//! 响应式系统 —— 原 mgui-reactive crate,已合入 mgui-core
//!
//! 设计文档 § 7 + § 22:
//! - `Signal<T>` 细粒度可观察值
//! - 依赖追踪:thread_local 记录"当前正在 build 的 Element",
//!   `Signal::get()` 时把当前 element 注册为该 signal 的订阅者
//! - `Signal::set()` 时把订阅者标记为 dirty
//! - 主循环把 dirty 集合取出,rebuild 这些 element
//!
//! 阶段 4-A7 追加:
//! - `Memo<T>` 惰性派生值:依赖自动收集,上游变化 → stale → 下次 get 重算
//! - `Effect` 自动追踪副作用:创建即运行一次收集依赖,依赖 signal 变化时重跑
//! - `batch(f)` 批量更新:batch 内的 set 合并通知,退出时 dirty/effect 一次 flush
//! - `untracked(f)` 无追踪读取:块内 `Signal::get()` 不建立订阅
//!
//! 范围限定:
//! - 假定单线程 UI(不跨线程)
//! - Effect 重跑不清除旧依赖(增量式)
//! - Memo 循环依赖:重算中再次 get 自身 → panic

use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct SubscriberId(pub u64);

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct SignalId(pub u64);

/// 全局响应式状态(thread_local,只在 UI 线程访问)
#[derive(Default)]
struct ReactiveState {
    /// 订阅者栈(栈式 — Memo::get 嵌套在 element build 内)
    /// 每项 = (订阅者, 本次运行 generation)。Effect/Memo 每次重跑 generation 自增,
    /// 旧的依赖在下一次通知/重跑时被剔除(修复条件分支依赖残留)。
    subscriber_stack: Vec<(SubscriberId, u64)>,
    /// 被标记为 dirty 的订阅者
    dirty: HashSet<SubscriberId>,
    /// 下一个 SubscriberId
    next_subscriber_id: u64,
    /// 下一个 SignalId
    next_signal_id: u64,
    /// subscriber 失效代数:deactivate/remount 后自增,通知时按代数剔除陈旧订阅。
    /// 只记录被失效过的 id(正常订阅者缺省为 0)。
    subscriber_epoch: HashMap<SubscriberId, u64>,
    /// 下一个失效代数
    next_subscriber_epoch: u64,
    /// Effect/Memo 当前依赖 generation(每次重跑自增)。element subscriber 缺省 0。
    subscriber_generation: HashMap<SubscriberId, u64>,
    /// 下一个依赖 generation
    next_subscriber_generation: u64,
    /// element subscriber 所属窗口/树的 reactive scope。
    /// drain 时只消费本 scope 的 dirty,避免多窗口互相吞掉更新。
    subscriber_scope: HashMap<SubscriberId, u64>,
    /// 0.5 M2B:`peek()` 在 subscriber 上下文里登记宿主级 rebuild 依赖。
    /// 与 `Signal::subscribers`(get 订阅)分开:peek 不参与值派生链,只负责让
    /// 用 peek 生成 props 的那棵子树/element 在下一帧重建一次。
    peek_deps: HashMap<SignalId, HashSet<(SubscriberId, u64, u64)>>,
    /// subscriber → 它 peek 过的 Signal,供 rebuild 前按 subscriber O(自身依赖数) 清理。
    /// 没有这张反查表时清旧依赖要遍历所有 Signal,会让大列表每帧 build 线性放大。
    peek_deps_by_subscriber: HashMap<SubscriberId, HashSet<SignalId>>,
    /// batch 深度(>0 = 正在 batch)
    batch_depth: usize,
    /// batch 期间暂存的 dirty(退出时一次性并入 dirty)
    pending_dirty: HashSet<SubscriberId>,
    /// memo 注册表:SubscriberId → memo core
    memo_registry: HashMap<SubscriberId, Rc<MemoCore>>,
    /// effect 注册表:SubscriberId → effect core
    effect_registry: HashMap<SubscriberId, Rc<EffectCore>>,
    /// batch 期间暂存的待重跑 effect
    pending_effects: Vec<Rc<EffectCore>>,
}

thread_local! {
    static REACTIVE: RefCell<ReactiveState> = RefCell::new(ReactiveState::default());
    /// untracked 深度(>0 = 当前读取不建立依赖)
    static TRACKING_PAUSED: Cell<usize> = const { Cell::new(0) };
}

/// 进入"订阅者"上下文
pub fn enter_subscriber(sub_id: SubscriberId) {
    let generation = subscriber_generation(sub_id);
    enter_subscriber_generation(sub_id, generation);
}

fn enter_subscriber_generation(sub_id: SubscriberId, generation: u64) {
    REACTIVE.with(|s| s.borrow_mut().subscriber_stack.push((sub_id, generation)));
}

/// 退出"订阅者"上下文(回到外层订阅者,若有)
pub fn exit_subscriber() {
    REACTIVE.with(|s| {
        s.borrow_mut().subscriber_stack.pop();
    });
}

/// RAII 订阅者作用域:compute/effect 内部 panic 时也能弹栈,
/// 否则后续所有 `Signal::get` 都会挂到已失败的订阅者上。
struct SubscriberScope;

impl SubscriberScope {
    fn enter(id: SubscriberId) -> Self {
        enter_subscriber(id);
        Self
    }

    /// Effect/Memo 每次重跑使用新的 generation:旧依赖在下一次通知时被剔除。
    fn enter_generation(id: SubscriberId, generation: u64) -> Self {
        enter_subscriber_generation(id, generation);
        Self
    }
}

impl Drop for SubscriberScope {
    fn drop(&mut self) {
        exit_subscriber();
    }
}

/// 在指定订阅者上下文中执行 `f`。
///
/// Element 树在 `State::build` / `Widget::children` 期间用它把 `Signal::get`
/// 的依赖归属到当前 element;panic 时由 RAII 保证弹栈。
pub fn with_subscriber<T>(id: SubscriberId, f: impl FnOnce() -> T) -> T {
    let _scope = SubscriberScope::enter(id);
    f()
}

/// 当前订阅者代数(未失效 = 0)
fn subscriber_epoch(id: SubscriberId) -> u64 {
    REACTIVE.with(|s| s.borrow().subscriber_epoch.get(&id).copied().unwrap_or(0))
}

/// 当前 Effect/Memo 依赖 generation(element 缺省 0)
fn subscriber_generation(id: SubscriberId) -> u64 {
    REACTIVE.with(|s| s.borrow().subscriber_generation.get(&id).copied().unwrap_or(0))
}

/// 为 Effect/Memo 分配新的依赖 generation
fn bump_subscriber_generation(id: SubscriberId) -> u64 {
    REACTIVE.with(|s| {
        let mut s = s.borrow_mut();
        let next = s.next_subscriber_generation.wrapping_add(1);
        s.next_subscriber_generation = next;
        s.subscriber_generation.insert(id, next);
        next
    })
}

/// 当前栈顶订阅者的 generation(element 为 0)
fn current_generation() -> u64 {
    REACTIVE.with(|s| s.borrow().subscriber_stack.last().map(|(_, generation)| *generation).unwrap_or(0))
}

fn current_subscriber() -> Option<SubscriberId> {
    REACTIVE.with(|s| s.borrow().subscriber_stack.last().map(|(id, _)| *id))
}

/// `peek()` 在 subscriber 上下文内登记“宿主 rebuild 依赖”。
/// 返回 false 表示没有 subscriber,调用方需要退回全局 epoch 兜底。
fn register_peek_dependency(signal_id: SignalId) -> bool {
    let Some(id) = current_subscriber() else { return false };
    REACTIVE.with(|s| {
        let mut state = s.borrow_mut();
        let epoch = state.subscriber_epoch.get(&id).copied().unwrap_or(0);
        let generation = state.subscriber_generation.get(&id).copied().unwrap_or(0);
        state.peek_deps.entry(signal_id).or_default().insert((id, epoch, generation));
        state.peek_deps_by_subscriber.entry(id).or_default().insert(signal_id);
    });
    true
}

/// 调试期一次性提示:subscriber 外的 `peek()` 没有宿主可定位,只能走全局 epoch。
#[cfg(debug_assertions)]
fn note_unknown_peek(signal_id: SignalId) {
    thread_local! {
        static UNKNOWN_PEEK_WARNED: Cell<bool> = const { Cell::new(false) };
    }
    UNKNOWN_PEEK_WARNED.with(|warned| {
        if !warned.replace(true) {
            eprintln!(
                "mgui: Signal::peek() outside subscriber (signal={}), falling back to global rebuild epoch",
                signal_id.0
            );
        }
    });
}

#[cfg(not(debug_assertions))]
fn note_unknown_peek(_signal_id: SignalId) {}

/// DT-02/测试用:某个 Signal 上当前有效的 peek 依赖数量。
pub fn peek_dependency_count(signal_id: SignalId) -> usize {
    REACTIVE.with(|s| {
        let state = s.borrow();
        state.peek_deps.get(&signal_id).map_or(0, |deps| {
            deps.iter()
                .filter(|(id, epoch, generation)| {
                    *epoch == state.subscriber_epoch.get(id).copied().unwrap_or(0)
                        && *generation == state.subscriber_generation.get(id).copied().unwrap_or(0)
                })
                .count()
        })
    })
}

/// 重建 subscriber 前清空旧 peek 依赖,让条件分支自然解绑。
///
/// 只在 element 的 build 入口调用,不在 `create_render_object` 调用:
/// 同一次 rebuild 的 `children()` 与 RO 构造属于同一轮,必须能累积依赖。
fn remove_peek_dependencies(state: &mut ReactiveState, sub_id: SubscriberId) {
    let Some(signals) = state.peek_deps_by_subscriber.remove(&sub_id) else { return };
    for signal_id in signals {
        let remove_key = if let Some(deps) = state.peek_deps.get_mut(&signal_id) {
            deps.retain(|(id, _, _)| *id != sub_id);
            deps.is_empty()
        } else {
            false
        };
        if remove_key {
            state.peek_deps.remove(&signal_id);
        }
    }
}

pub(crate) fn clear_peek_dependencies(sub_id: SubscriberId) {
    REACTIVE.with(|s| remove_peek_dependencies(&mut s.borrow_mut(), sub_id));
}

/// 使订阅者失效:deactivate / remount 后调用。
///
/// 不直接遍历所有 Signal 删除订阅(框架无法枚举 Signal),而是在下一次
/// `Signal::set/update` 通知时按代数剔除陈旧项;这样既避免长会话内存增长,
/// 也避免池复用后的旧依赖误触发新 element。
pub(crate) fn invalidate_subscriber(id: SubscriberId) {
    REACTIVE.with(|s| {
        let mut state = s.borrow_mut();
        let next = state.next_subscriber_epoch.wrapping_add(1);
        state.next_subscriber_epoch = next;
        state.subscriber_epoch.insert(id, next);
        // 卸载/池化复活后同步移除 peek 反查,避免陈旧条目留在表里。
        remove_peek_dependencies(&mut state, id);
    });
}

/// 取走当前 dirty 集合(兼容/测试用;ElementTree 主循环请用 `take_dirty_for_scope`)
pub fn take_dirty() -> HashSet<SubscriberId> {
    REACTIVE.with(|s| std::mem::take(&mut s.borrow_mut().dirty))
}

/// 登记 element subscriber 所属的树/窗口 scope。
pub(crate) fn register_subscriber_scope(id: SubscriberId, scope: u64) {
    REACTIVE.with(|s| {
        s.borrow_mut().subscriber_scope.insert(id, scope);
    });
}

/// 释放 scope(元素卸载/整树 remount)。未登记的 subscriber 视为全局(scope 0)。
pub(crate) fn release_subscriber_scope(id: SubscriberId) {
    REACTIVE.with(|s| {
        let mut state = s.borrow_mut();
        state.subscriber_scope.remove(&id);
        // 已卸载 element 的 pending dirty 直接丢弃,避免被其他窗口消费后
        // 产生无意义的重建计数。
        state.dirty.remove(&id);
        state.pending_dirty.remove(&id);
    });
}

/// 只取走属于 `scope`(或全局 scope 0)的 dirty,其他树的 id 留在集合里。
///
/// 多窗口共用 UI 线程时,`Signal::set` 会把所有窗口的 subscriber 放进同一个
/// 全局 dirty set;若任一窗口 `take_dirty()` 全取,其他窗口的 element dirty
/// 就被吞掉。这里按 scope 分区。
pub(crate) fn take_dirty_for_scope(scope: u64) -> HashSet<SubscriberId> {
    REACTIVE.with(|s| {
        let mut state = s.borrow_mut();
        let dirty = std::mem::take(&mut state.dirty);
        let mut mine = HashSet::new();
        let mut keep = HashSet::new();
        for id in dirty {
            let owner = state.subscriber_scope.get(&id).copied().unwrap_or(0);
            if owner == 0 || owner == scope {
                mine.insert(id);
            } else {
                keep.insert(id);
            }
        }
        state.dirty = keep;
        mine
    })
}

/// DT-02:只读 peek 当前属于 `scope` 的 dirty subscriber(不 drain)。
pub fn peek_dirty_for_scope(scope: u64) -> HashSet<SubscriberId> {
    REACTIVE.with(|s| {
        let state = s.borrow();
        let mut mine = HashSet::new();
        for id in state.dirty.iter().copied() {
            let owner = state.subscriber_scope.get(&id).copied().unwrap_or(0);
            if owner == 0 || owner == scope {
                mine.insert(id);
            }
        }
        mine
    })
}

thread_local! {
    /// 自上次取走后有任意 Signal::set/update 发生(与订阅无关)。
    /// 宿主(如 showcase)以 peek 读 Signal 进 Widget,不建立订阅 —— 值变化后
    /// dirty 集合为空,需要这个标记让 drain 返回非零,宿主据此触发 rebuild。
    static ANY_SIGNAL_SET: Cell<bool> = const { Cell::new(false) };
    /// peek 信号变化的全局 epoch:每棵 ElementTree 各自记录已消费版本,
    /// 避免多窗口共用 bool 时"一个窗口消费后其他窗口漏掉全树重建"。
    static ANY_SIGNAL_EPOCH: Cell<u64> = const { Cell::new(0) };
    /// DT-02:Signal trace 开关镜像。关闭时入口只读它,不拿 SIG_TRACE 锁。
    static SIGNAL_TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
}

/// DT-02:Signal trace 线程局部实例(复用 DevtoolsTrace 基础设施,CAP=256)。
/// 与 Reactive 状态本身同线程口径;进程全局会让测试线程互相污染开关。
fn with_signal_trace<R>(f: impl FnOnce(&crate::devtools_trace::DevtoolsTrace<SignalTraceEntry>) -> R) -> R {
    use std::sync::Mutex;
    thread_local! {
        static SIG_TRACE: Mutex<crate::devtools_trace::DevtoolsTrace<SignalTraceEntry>> =
            Mutex::new(crate::devtools_trace::DevtoolsTrace::new(256));
    }
    SIG_TRACE.with(|t| {
        let guard = t.lock().unwrap_or_else(|e| e.into_inner());
        f(&guard)
    })
}

/// 自上次取走后有任意 Signal::set/update 发生(取出即复位)
pub fn take_any_signal_set() -> bool {
    ANY_SIGNAL_SET.with(|c| c.replace(false))
}

/// 当前 peek 信号变化 epoch(只增不减)
pub fn any_signal_epoch() -> u64 {
    ANY_SIGNAL_EPOCH.with(|c| c.get())
}

/// 标记"有 Signal 值已变化"(batch 内也置位:值已变,宿主下帧 rebuild 即可)
fn mark_any_signal_set() {
    ANY_SIGNAL_SET.with(|c| c.set(true));
    ANY_SIGNAL_EPOCH.with(|c| c.set(c.get().wrapping_add(1)));
}

// ============================================================
// DT-02:Signal trace API
// ============================================================

/// DT-02:一次 Signal.set/update 的追踪条目
#[derive(Clone, Debug)]
pub struct SignalTraceEntry {
    pub signal_id: SignalId,
    /// 这次变化直接影响到的 subscriber(get + 有效 peek 依赖,已去重)
    pub subscribers: Vec<SubscriberId>,
    /// 这次变化影响的 peek 依赖 subscriber 子集。
    pub peek_subscribers: Vec<SubscriberId>,
    /// 是否被任意 peek() 读过。
    pub peeked: bool,
    /// 是否在 subscriber 上下文之外被 peek(无法定位宿主,退回全局 epoch)。
    pub unknown_peek: bool,
    /// 自进程启动的毫秒数
    pub timestamp_ms: u64,
}

/// DT-02:开启/关闭 Signal trace 采集。默认关闭(零开销)。
pub fn set_signal_trace_enabled(on: bool) {
    SIGNAL_TRACE_ENABLED.with(|c| c.set(on));
    with_signal_trace(|t| t.set_enabled(on));
}

/// DT-02:是否正在采集 Signal trace。只读 thread-local 镜像,不拿锁。
pub fn signal_trace_enabled() -> bool {
    SIGNAL_TRACE_ENABLED.with(|c| c.get())
}

/// DT-02:追加一次 Signal 触发事件(trace 关闭时立即返回,零开销)。
fn push_signal_trace(
    signal_id: SignalId,
    subscribers: &[SubscriberId],
    peek_subscribers: &[SubscriberId],
    peeked: bool,
    unknown_peek: bool,
) {
    if !signal_trace_enabled() {
        return;
    }
    use crate::devtools_trace::now_ms;
    with_signal_trace(|t| {
        // 关闭时必须先返回,避免 to_vec / now_ms 仍然发生。
        if !t.enabled() {
            return;
        }
        t.push(SignalTraceEntry {
            signal_id,
            subscribers: subscribers.to_vec(),
            peek_subscribers: peek_subscribers.to_vec(),
            peeked,
            unknown_peek,
            timestamp_ms: now_ms(),
        })
    });
}

/// DT-02:取最近 N 条 Signal trace(不 drain,可重复调用)。关闭时返回空,不拿锁。
pub fn peek_signal_trace(max: usize) -> Vec<SignalTraceEntry> {
    if !signal_trace_enabled() {
        return Vec::new();
    }
    with_signal_trace(|t| {
        if !t.enabled() {
            return Vec::new();
        }
        t.peek(max)
    })
}

/// DT-02:清空 Signal trace(切换窗口会话时)。
pub fn clear_signal_trace() {
    with_signal_trace(|t| t.clear());
}

/// 标记某个 subscriber 为 dirty
pub fn mark_dirty(sub_id: SubscriberId) {
    REACTIVE.with(|s| {
        let mut s = s.borrow_mut();
        if s.batch_depth > 0 {
            s.pending_dirty.insert(sub_id);
        } else {
            s.dirty.insert(sub_id);
        }
    });
}

/// 宿主级订阅者:由窗口宿主显式创建并绑定到一棵树的 reactive scope。
///
/// 与 Element 内部 subscriber 的区别:它不对应任何 element,只用于在
/// `build_root` 里读取 `Signal` / `Memo` 建立依赖,让后续变化只脏到本窗口
/// 的 scope。宿主在 `on_about_to_wait` 用 `has_dirty()` 决定 rebuild,
/// 帧循环再按 scope 排空,避免跨窗口互相吞 dirty 或退回全局 epoch。
#[derive(Debug)]
pub struct HostSubscriber {
    id: SubscriberId,
    scope: u64,
}

impl HostSubscriber {
    /// 绑定到一个明确的 reactive scope(通常取 `ElementTree::reactive_scope()`)。
    pub fn new(scope: u64) -> Self {
        let id = new_subscriber_id();
        register_subscriber_scope(id, scope);
        Self { id, scope }
    }

    pub fn id(&self) -> SubscriberId {
        self.id
    }

    /// 在该订阅者上下文中读取信号;块内的 `Signal::get()` / `Memo::get()` 归它所有。
    pub fn with<T>(&self, f: impl FnOnce() -> T) -> T {
        with_subscriber(self.id, f)
    }

    /// 重新绑定依赖:换 generation,上一轮依赖在下一次通知时自然失效。
    ///
    /// 条件分支变化导致这次少读某个信号时必须调用,避免旧依赖永久残留。
    pub fn rebind<T>(&self, f: impl FnOnce() -> T) -> T {
        bump_subscriber_generation(self.id);
        self.with(f)
    }

    /// 只读检查:本订阅者是否因上游变化被标脏(不消费 dirty)。
    pub fn has_dirty(&self) -> bool {
        peek_dirty_for_scope(self.scope).contains(&self.id)
    }

    pub fn scope(&self) -> u64 {
        self.scope
    }
}

impl Drop for HostSubscriber {
    fn drop(&mut self) {
        invalidate_subscriber(self.id);
        release_subscriber_scope(self.id);
    }
}

/// 分配新的 SubscriberId
pub fn new_subscriber_id() -> SubscriberId {
    REACTIVE.with(|s| {
        let mut s = s.borrow_mut();
        let id = SubscriberId(s.next_subscriber_id);
        s.next_subscriber_id += 1;
        id
    })
}

/// 分配新的 SignalId
pub fn new_signal_id() -> SignalId {
    REACTIVE.with(|s| {
        let mut s = s.borrow_mut();
        let id = SignalId(s.next_signal_id);
        s.next_signal_id += 1;
        id
    })
}

/// 追踪是否启用(untracked 块内为 false)
fn tracking_enabled() -> bool {
    TRACKING_PAUSED.with(|c| c.get() == 0)
}

/// 在 `f` 内的 `Signal::get()` 不建立依赖订阅
pub fn untracked<T>(f: impl FnOnce() -> T) -> T {
    struct TrackingGuard;
    impl Drop for TrackingGuard {
        fn drop(&mut self) {
            TRACKING_PAUSED.with(|c| c.set(c.get().saturating_sub(1)));
        }
    }
    TRACKING_PAUSED.with(|c| c.set(c.get() + 1));
    let _guard = TrackingGuard;
    f()
}

/// 批量更新。batch 内的 `Signal::set` 不立即通知订阅者,
/// 退出时把累积的 dirty / effect 重跑一次性 flush。
pub fn batch<T>(f: impl FnOnce() -> T) -> T {
    struct BatchGuard {
        completed: bool,
    }
    impl Drop for BatchGuard {
        fn drop(&mut self) {
            let depth = REACTIVE.with(|s| {
                let mut s = s.borrow_mut();
                s.batch_depth = s.batch_depth.saturating_sub(1);
                s.batch_depth
            });
            if depth == 0 {
                REACTIVE.with(|s| {
                    let mut s = s.borrow_mut();
                    let pending = std::mem::take(&mut s.pending_dirty);
                    s.dirty.extend(pending);
                    if !self.completed {
                        // 块内 panic:不在这里跑 effect(可能二次 panic)
                        s.pending_effects.clear();
                    }
                });
            }
        }
    }

    REACTIVE.with(|s| s.borrow_mut().batch_depth += 1);
    let mut guard = BatchGuard { completed: false };
    let out = f();
    guard.completed = true;
    drop(guard);
    let effects = REACTIVE.with(|s| std::mem::take(&mut s.borrow_mut().pending_effects));
    for core in effects {
        run_effect_core(&core);
    }
    out
}

// ============================================================
// 通知链
// ============================================================

/// memo 核心(非泛型 — 注册表按 SubscriberId 索引)
struct MemoCore {
    /// true = 依赖已变化,下次 get 重算
    stale: Cell<bool>,
    /// 重算中(循环依赖检测)
    computing: Cell<bool>,
    /// 下游订阅者(带订阅代数与依赖 generation,失效后通知时剔除)
    subscribers: RefCell<HashSet<(SubscriberId, u64, u64)>>,
}

/// effect 核心
struct EffectCore {
    run: Box<dyn Fn()>,
    /// 重入防护
    running: Cell<bool>,
    pending: Cell<bool>,
}

/// Signal::set/update 的统一通知入口
fn notify_subscribers(subs: &[SubscriberId]) {
    let mut memo_cores = Vec::new();
    let mut effect_cores = Vec::new();
    REACTIVE.with(|s| {
        let mut s = s.borrow_mut();
        for sub in subs {
            if s.batch_depth > 0 {
                s.pending_dirty.insert(*sub);
            } else {
                s.dirty.insert(*sub);
            }
            if let Some(c) = s.memo_registry.get(sub).cloned() {
                memo_cores.push(c);
            }
            if let Some(c) = s.effect_registry.get(sub).cloned() {
                effect_cores.push(c);
            }
        }
    });
    for c in memo_cores {
        notify_memo_stale(&c);
    }
    for c in effect_cores {
        schedule_effect(c);
    }
}

/// memo 置 stale 并向下游传播(递归;stale 剪枝保证循环依赖终止)
fn notify_memo_stale(core: &Rc<MemoCore>) {
    if core.stale.get() {
        return;
    }
    core.stale.set(true);
    // 剔除已失效的 element 订阅(池复用/卸载后),避免脏集合和 Set 无限增长
    core.subscribers
        .borrow_mut()
        .retain(|(id, epoch, generation)| *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id));
    let downstream: Vec<SubscriberId> = core.subscribers.borrow().iter().map(|(id, _, _)| *id).collect();
    for d in downstream {
        mark_dirty(d);
        let next = REACTIVE.with(|s| s.borrow().memo_registry.get(&d).cloned());
        if let Some(c) = next {
            notify_memo_stale(&c);
        }
    }
}

/// effect 调度重跑(batch 感知)
fn schedule_effect(core: Rc<EffectCore>) {
    let in_batch = REACTIVE.with(|s| s.borrow().batch_depth > 0);
    if in_batch {
        REACTIVE.with(|s| {
            let mut s = s.borrow_mut();
            if !s.pending_effects.iter().any(|c| Rc::ptr_eq(c, &core)) {
                s.pending_effects.push(core);
            }
        });
    } else {
        run_effect_core(&core);
    }
}

/// 立即重跑 effect(重入防护)
fn run_effect_core(core: &Rc<EffectCore>) {
    if core.running.get() {
        core.pending.set(true);
        return;
    }
    let id = REACTIVE.with(|s| s.borrow().effect_registry.iter().find(|(_, c)| Rc::ptr_eq(c, core)).map(|(k, _)| *k));
    let Some(id) = id else { return };
    struct RunningGuard<'a>(&'a Cell<bool>);
    impl Drop for RunningGuard<'_> {
        fn drop(&mut self) {
            self.0.set(false);
        }
    }
    core.running.set(true);
    let _running = RunningGuard(&core.running);
    // 每次重跑使用新的依赖 generation:本轮没读到的旧 Signal 依赖会在
    // 下一次通知时被剔除(条件分支不再造成幽灵重跑)。
    let generation = bump_subscriber_generation(id);
    let _scope = SubscriberScope::enter_generation(id, generation);
    (core.run)();
    drop(_scope);
    drop(_running);
    if core.pending.replace(false) {
        run_effect_core(core);
    }
}

// ============================================================
// Signal
// ============================================================

struct SignalInner<T> {
    value: T,
    /// (订阅者, 订阅时的代数, 依赖 generation)。失效/旧 generation 在下一次 set 时剔除。
    subscribers: HashSet<(SubscriberId, u64, u64)>,
    /// 是否被任意 `peek()` 读过(trace/诊断口径)。
    peeked: bool,
    /// 是否在 subscriber 上下文之外被 peek。只有这类无法定位宿主的读取
    /// 才置位全局 ANY_SIGNAL_SET;subscriber 内的 peek 走细粒度 dirty。
    unknown_peek: bool,
}

/// 细粒度响应式值
pub struct Signal<T> {
    id: SignalId,
    inner: Rc<RefCell<SignalInner<T>>>,
}

impl<T: Clone + 'static> Signal<T> {
    pub fn new(initial: T) -> Self {
        Self {
            id: new_signal_id(),
            inner: Rc::new(RefCell::new(SignalInner {
                value: initial,
                subscribers: HashSet::new(),
                peeked: false,
                unknown_peek: false,
            })),
        }
    }

    pub fn id(&self) -> SignalId {
        self.id
    }

    /// 读取值,并把当前 subscriber 加入依赖集合
    pub fn get(&self) -> T {
        if tracking_enabled() {
            if let Some(sub) = current_subscriber() {
                let epoch = subscriber_epoch(sub);
                let generation = current_generation();
                self.inner.borrow_mut().subscribers.insert((sub, epoch, generation));
            }
        }
        self.inner.borrow().value.clone()
    }

    /// 借用值执行闭包(不 clone),同时按 `get` 语义登记订阅。
    ///
    /// 大值(Vec/字符串/Store 列表)只读计算时应优先用它,避免每次 build 复制。
    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        if tracking_enabled() {
            if let Some(sub) = current_subscriber() {
                let epoch = subscriber_epoch(sub);
                let generation = current_generation();
                self.inner.borrow_mut().subscribers.insert((sub, epoch, generation));
            }
        }
        f(&self.inner.borrow().value)
    }

    /// 读取值但不建立 `get` 那种响应式订阅。
    ///
    /// 在 subscriber(element build/RO 构造)上下文内:登记一条细粒度宿主依赖,
    /// 该 Signal 变化时只标脏这个 subscriber 对应的 element/tree。
    /// 在 subscriber 上下文之外:无法定位宿主,退回全局 epoch 触发全树 rebuild。
    pub fn peek(&self) -> T {
        let scoped = register_peek_dependency(self.id);
        if !scoped {
            note_unknown_peek(self.id);
        }
        let mut inner = self.inner.borrow_mut();
        inner.peeked = true;
        inner.unknown_peek |= !scoped;
        inner.value.clone()
    }

    /// `peek` 的零拷贝版本:借用值执行闭包,依赖语义与 `peek()` 完全一致。
    pub fn peek_with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        let scoped = register_peek_dependency(self.id);
        if !scoped {
            note_unknown_peek(self.id);
        }
        let mut inner = self.inner.borrow_mut();
        inner.peeked = true;
        inner.unknown_peek |= !scoped;
        f(&inner.value)
    }

    /// 读取值但不建立订阅、**也不标记宿主全树重建**。
    ///
    /// 仅用于 Debug/统计等纯展示路径;UI build 需要使用 `peek()`(宿主级读取)
    /// 或 `get()`(组件 build 内订阅)。
    pub fn peek_silent(&self) -> T {
        self.inner.borrow().value.clone()
    }

    /// `peek_silent` 的零拷贝版本(Debug/统计等纯展示路径)。
    pub fn peek_silent_with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        f(&self.inner.borrow().value)
    }

    fn collect_peek_subscribers(&self) -> Vec<SubscriberId> {
        REACTIVE.with(|s| {
            let valid: Vec<(SubscriberId, u64, u64)> = {
                let state = s.borrow();
                let Some(deps) = state.peek_deps.get(&self.id) else { return Vec::new() };
                deps.iter()
                    .copied()
                    .filter(|(id, epoch, generation)| {
                        *epoch == state.subscriber_epoch.get(id).copied().unwrap_or(0)
                            && *generation == state.subscriber_generation.get(id).copied().unwrap_or(0)
                    })
                    .collect()
            };
            {
                let valid_set: HashSet<_> = valid.iter().copied().collect();
                let valid_subs: HashSet<_> = valid.iter().map(|(id, _, _)| *id).collect();
                let mut state = s.borrow_mut();
                let mut stale_subs = Vec::new();
                let mut remove_key = false;
                if let Some(deps) = state.peek_deps.get_mut(&self.id) {
                    for (sub, _, _) in deps.iter() {
                        if !valid_subs.contains(sub) {
                            stale_subs.push(*sub);
                        }
                    }
                    deps.retain(|d| valid_set.contains(d));
                    remove_key = deps.is_empty();
                }
                for sub in stale_subs {
                    let mut empty = false;
                    if let Some(signals) = state.peek_deps_by_subscriber.get_mut(&sub) {
                        signals.remove(&self.id);
                        empty = signals.is_empty();
                    }
                    if empty {
                        state.peek_deps_by_subscriber.remove(&sub);
                    }
                }
                if remove_key {
                    state.peek_deps.remove(&self.id);
                }
            }
            valid.into_iter().map(|(id, _, _)| id).collect()
        })
    }

    /// 直接设值并触发 dirty
    pub fn set(&self, value: T) {
        let (subs, peeked, unknown_peek) = {
            let mut inner = self.inner.borrow_mut();
            inner.value = value;
            inner.subscribers.retain(|(id, epoch, generation)| {
                *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id)
            });
            (inner.subscribers.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(), inner.peeked, inner.unknown_peek)
        };
        let peek_subs = self.collect_peek_subscribers();
        let mut all = subs;
        all.extend(peek_subs.iter().copied());
        all.sort_unstable_by_key(|id| id.0);
        all.dedup();
        if unknown_peek {
            mark_any_signal_set();
        }
        push_signal_trace(self.id, &all, &peek_subs, peeked, unknown_peek);
        notify_subscribers(&all);
    }

    /// 仅当值真正变化时设值并通知;返回是否发生变化。
    ///
    /// 高频路径(hover/滚动/主题同值写回)用它跳过无意义的 dirty 传播。
    pub fn set_if_changed(&self, value: T) -> bool
    where
        T: PartialEq,
    {
        if self.inner.borrow().value == value {
            return false;
        }
        self.set(value);
        true
    }

    /// 仅当 `f` 产生的新值与原值不同时通知;返回是否发生变化。
    pub fn update_if_changed(&self, f: impl FnOnce(&mut T)) -> bool
    where
        T: PartialEq,
    {
        let mut next = self.inner.borrow().value.clone();
        f(&mut next);
        if self.inner.borrow().value == next {
            return false;
        }
        self.set(next);
        true
    }

    /// 修改值并触发 dirty
    pub fn update(&self, f: impl FnOnce(&mut T)) {
        let (subs, peeked, unknown_peek) = {
            let mut inner = self.inner.borrow_mut();
            f(&mut inner.value);
            inner.subscribers.retain(|(id, epoch, generation)| {
                *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id)
            });
            (inner.subscribers.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(), inner.peeked, inner.unknown_peek)
        };
        let peek_subs = self.collect_peek_subscribers();
        let mut all = subs;
        all.extend(peek_subs.iter().copied());
        all.sort_unstable_by_key(|id| id.0);
        all.dedup();
        if unknown_peek {
            mark_any_signal_set();
        }
        push_signal_trace(self.id, &all, &peek_subs, peeked, unknown_peek);
        notify_subscribers(&all);
    }

    /// 当前订阅者数量(测试用)
    pub fn subscriber_count(&self) -> usize {
        self.inner.borrow().subscribers.len()
    }
}

impl<T: 'static> Clone for Signal<T> {
    fn clone(&self) -> Self {
        Self { id: self.id, inner: self.inner.clone() }
    }
}

impl<T: 'static> std::fmt::Debug for Signal<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Signal").field("id", &self.id).field("value_type", &std::any::type_name::<T>()).finish()
    }
}

// ============================================================
// Memo
// ============================================================

/// 惰性派生值:依赖自动收集,上游变化 → stale → 下次 `get()` 重算。
pub struct Memo<T> {
    id: SubscriberId,
    core: Rc<MemoCore>,
    inner: Rc<RefCell<MemoInner<T>>>,
    /// 注册令牌:所有 clone 共享,最后一个 drop 时才从 registry 注销
    _registration: Rc<MemoRegistration>,
}

struct MemoInner<T> {
    compute: Box<dyn Fn() -> T>,
    cached: Option<T>,
}

/// Memo 在全局 registry 中的注册生命周期。
///
/// **不能**在 `Memo::drop` 里直接 remove:Clone 共享同一 id/core,
/// 任意一个 clone 析构都会注销整条依赖链,剩余 clone 永远收不到 stale。
struct MemoRegistration {
    id: SubscriberId,
}

impl Drop for MemoRegistration {
    fn drop(&mut self) {
        REACTIVE.with(|s| {
            s.borrow_mut().memo_registry.remove(&self.id);
        });
    }
}

impl<T: Clone + 'static> Memo<T> {
    pub fn new(compute: impl Fn() -> T + 'static) -> Self {
        let id = new_subscriber_id();
        let memo = Self {
            id,
            core: Rc::new(MemoCore {
                stale: Cell::new(false),
                computing: Cell::new(false),
                subscribers: RefCell::new(HashSet::new()),
            }),
            inner: Rc::new(RefCell::new(MemoInner { compute: Box::new(compute), cached: None })),
            _registration: Rc::new(MemoRegistration { id }),
        };
        REACTIVE.with(|s| {
            s.borrow_mut().memo_registry.insert(id, memo.core.clone());
        });
        memo.recompute();
        memo
    }

    fn recompute(&self) {
        if self.core.computing.get() {
            panic!("Memo: circular dependency detected");
        }
        struct ComputeGuard<'a> {
            core: &'a MemoCore,
            completed: bool,
        }
        impl Drop for ComputeGuard<'_> {
            fn drop(&mut self) {
                self.core.computing.set(false);
                if !self.completed {
                    // 计算 panic:保留 stale,下次 get 必须重算,
                    // 不能把旧 cached 当新值返回。
                    self.core.stale.set(true);
                }
            }
        }

        self.core.computing.set(true);
        self.core.stale.set(false);
        let mut guard = ComputeGuard { core: &self.core, completed: false };
        // 每次重算换 generation:上游 Signal/Memo 里上一轮的依赖会被标记为陈旧,
        // 下一次通知时剔除(条件分支依赖不再永久残留)。
        let generation = bump_subscriber_generation(self.id);
        let value = {
            let _scope = SubscriberScope::enter_generation(self.id, generation);
            (self.inner.borrow().compute)()
        };
        self.inner.borrow_mut().cached = Some(value);
        guard.completed = true;
    }

    pub fn get(&self) -> T {
        if tracking_enabled() {
            if let Some(sub) = current_subscriber() {
                if sub != self.id {
                    let epoch = subscriber_epoch(sub);
                    let generation = current_generation();
                    self.core.subscribers.borrow_mut().insert((sub, epoch, generation));
                }
            }
        }
        if self.core.stale.replace(false) || self.inner.borrow().cached.is_none() {
            self.recompute();
        }
        self.inner.borrow().cached.clone().expect("Memo: cached after recompute")
    }

    pub fn peek(&self) -> Option<T> {
        self.inner.borrow().cached.clone()
    }
}

impl<T: 'static> Clone for Memo<T> {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            core: self.core.clone(),
            inner: self.inner.clone(),
            _registration: self._registration.clone(),
        }
    }
}

impl<T: 'static> std::fmt::Debug for Memo<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Memo").field("id", &self.id).field("value_type", &std::any::type_name::<T>()).finish()
    }
}

// ============================================================
// Effect
// ============================================================

/// 自动追踪副作用:创建时立即运行一次,依赖的 signal 变化时重跑。
pub struct Effect {
    id: SubscriberId,
    core: Rc<EffectCore>,
}

impl Effect {
    pub fn new(run: impl Fn() + 'static) -> Self {
        let id = new_subscriber_id();
        let effect = Self {
            id,
            core: Rc::new(EffectCore { run: Box::new(run), running: Cell::new(false), pending: Cell::new(false) }),
        };
        REACTIVE.with(|s| {
            s.borrow_mut().effect_registry.insert(id, effect.core.clone());
        });
        // 走统一入口:分配 generation + 重入防护 + 依赖清理
        run_effect_core(&effect.core);
        effect
    }

    pub fn rerun(&self) {
        run_effect_core(&self.core);
    }
}

impl Drop for Effect {
    fn drop(&mut self) {
        REACTIVE.with(|s| {
            s.borrow_mut().effect_registry.remove(&self.id);
        });
    }
}

impl std::fmt::Debug for Effect {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Effect").field("id", &self.id).finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::panic::{self, AssertUnwindSafe};

    /// 捕获 panic 并临时静音默认 hook,避免测试输出被预期 panic 污染
    fn quietly<R>(f: impl FnOnce() -> R) -> std::thread::Result<R> {
        let prev = panic::take_hook();
        panic::set_hook(Box::new(|_| {}));
        let out = panic::catch_unwind(AssertUnwindSafe(f));
        panic::set_hook(prev);
        out
    }

    #[test]
    fn signal_trace_records_only_while_enabled() {
        clear_signal_trace();
        set_signal_trace_enabled(false);
        assert!(!signal_trace_enabled());

        let sig = Signal::new(0);
        let _ = sig.peek();
        sig.set(1);
        assert!(peek_signal_trace(0).is_empty(), "关闭时快照也应为空");

        set_signal_trace_enabled(true);
        sig.set(2);
        let snap = peek_signal_trace(0);
        assert_eq!(snap.len(), 1);
        assert_eq!(snap[0].signal_id, sig.id);
        assert!(snap[0].peeked, "peek 读过的 Signal 必须带宿主级标记");

        clear_signal_trace();
        set_signal_trace_enabled(false);
    }

    #[test]
    fn signal_trace_clear_works_while_disabled() {
        clear_signal_trace();
        set_signal_trace_enabled(true);
        let sig = Signal::new(0);
        sig.set(1);
        assert_eq!(peek_signal_trace(0).len(), 1);

        set_signal_trace_enabled(false);
        clear_signal_trace();
        set_signal_trace_enabled(true);
        assert!(peek_signal_trace(0).is_empty(), "关闭期间的显式 clear 必须生效");
        set_signal_trace_enabled(false);
    }

    #[test]
    fn dropping_memo_clone_keeps_shared_registration() {
        let sig = Signal::new(1);
        let s = sig.clone();
        let memo = Memo::new(move || s.get() * 2);
        assert_eq!(memo.get(), 2);

        let clone = memo.clone();
        drop(clone);

        sig.set(7);
        assert_eq!(memo.get(), 14, "clone 析构不应注销原 Memo 的依赖注册");
    }

    #[test]
    fn memo_panic_keeps_stale_and_recomputes() {
        let sig = Signal::new(1);
        let fail = Rc::new(Cell::new(false));
        let (s, f) = (sig.clone(), fail.clone());
        let memo = Memo::new(move || {
            let v = s.get();
            if f.get() {
                panic!("memo boom");
            }
            v * 2
        });
        assert_eq!(memo.get(), 2);

        fail.set(true);
        sig.set(5);
        assert!(quietly(|| memo.get()).is_err());

        fail.set(false);
        assert_eq!(memo.get(), 10, "panic 后必须保留 stale 并重新计算");
    }

    #[test]
    fn effect_panic_resets_running_guard() {
        let sig = Signal::new(0);
        let fail = Rc::new(Cell::new(false));
        let runs = Rc::new(Cell::new(0usize));
        let (s, f, r) = (sig.clone(), fail.clone(), runs.clone());
        let effect = Effect::new(move || {
            let _ = s.get();
            r.set(r.get() + 1);
            if f.get() {
                panic!("effect boom");
            }
        });
        assert_eq!(runs.get(), 1);

        fail.set(true);
        assert!(quietly(|| sig.set(1)).is_err());
        fail.set(false);

        sig.set(2);
        assert_eq!(runs.get(), 3, "panic 后 effect 应能继续响应依赖变化");
        drop(effect);
    }

    #[test]
    fn batch_panic_restores_depth() {
        let sig = Signal::new(0);
        assert!(quietly(|| batch(|| {
            sig.set(1);
            panic!("batch boom");
        }))
        .is_err());

        let runs = Rc::new(Cell::new(0usize));
        let (s, r) = (sig.clone(), runs.clone());
        let effect = Effect::new(move || {
            let _ = s.get();
            r.set(r.get() + 1);
        });
        assert_eq!(runs.get(), 1);

        sig.set(2);
        assert_eq!(runs.get(), 2, "batch panic 后 depth 必须归零,set 应立即通知");
        drop(effect);
    }

    #[test]
    fn untracked_panic_restores_tracking() {
        let sig = Signal::new(0);
        assert!(quietly(|| untracked(|| {
            let _ = sig.get();
            panic!("untracked boom");
        }))
        .is_err());

        let runs = Rc::new(Cell::new(0usize));
        let (s, r) = (sig.clone(), runs.clone());
        let effect = Effect::new(move || {
            let _ = s.get();
            r.set(r.get() + 1);
        });
        sig.set(1);
        assert_eq!(runs.get(), 2, "untracked panic 后必须恢复依赖追踪");
        drop(effect);
    }

    #[test]
    fn only_peeked_signals_mark_global_rebuild() {
        let _ = take_any_signal_set();
        let scoped = Signal::new(0);
        let id = new_subscriber_id();
        with_subscriber(id, || {
            let _ = scoped.get();
        });
        scoped.set(1);
        assert!(!take_any_signal_set(), "仅 build 内 get 的 Signal 不应触发全树 rebuild");

        let peeked = Signal::new(0);
        let _ = peeked.peek();
        peeked.set(1);
        assert!(take_any_signal_set(), "peek 过的 Signal 变化应触发全树 rebuild");
    }

    #[test]
    fn invalidated_subscriber_is_pruned_on_next_set() {
        let sig = Signal::new(0);
        let id = new_subscriber_id();
        with_subscriber(id, || {
            let _ = sig.get();
        });
        assert_eq!(sig.subscriber_count(), 1);
        invalidate_subscriber(id);
        sig.set(1);
        assert_eq!(sig.subscriber_count(), 0, "失效订阅应在下一次 set 时被剔除");
    }

    #[test]
    fn effect_rerun_drops_stale_dependencies() {
        let sig = Signal::new(0);
        let gate = Signal::new(true);
        let runs = Rc::new(Cell::new(0usize));
        let (s, g, r) = (sig.clone(), gate.clone(), runs.clone());
        let effect = Effect::new(move || {
            r.set(r.get() + 1);
            if g.get() {
                let _ = s.get();
            }
        });
        assert_eq!(runs.get(), 1);

        gate.set(false);
        assert_eq!(runs.get(), 2, "gate 变化应重跑");
        sig.set(1);
        assert_eq!(runs.get(), 2, "gate=false 后旧 Signal 依赖必须被剔除");
        drop(effect);
    }

    #[test]
    fn memo_recompute_drops_stale_dependencies() {
        let sig = Signal::new(0);
        let gate = Signal::new(true);
        let computes = Rc::new(Cell::new(0usize));
        let (s, g, c) = (sig.clone(), gate.clone(), computes.clone());
        let memo = Memo::new(move || {
            c.set(c.get() + 1);
            if g.get() {
                s.get()
            } else {
                0
            }
        });
        assert_eq!(memo.get(), 0);
        assert_eq!(computes.get(), 1);

        gate.set(false);
        assert_eq!(memo.get(), 0);
        assert_eq!(computes.get(), 2, "gate 变化后应重算");

        sig.set(1);
        assert_eq!(memo.get(), 0);
        assert_eq!(computes.get(), 2, "gate=false 后旧 Signal 依赖必须被剔除");
    }

    fn fresh_scope() -> SubscriberId {
        let _ = take_dirty();
        let _ = take_any_signal_set();
        let sub = new_subscriber_id();
        register_subscriber_scope(sub, 4242);
        sub
    }

    #[test]
    fn peek_inside_subscriber_marks_scoped_dirty_only() {
        let sub = fresh_scope();
        let sig = Signal::new(0);
        with_subscriber(sub, || {
            let _ = sig.peek();
        });
        assert_eq!(peek_dependency_count(sig.id()), 1);
        sig.set(1);
        assert!(take_dirty_for_scope(4242).contains(&sub), "peek 应在自己 scope 内标脏");
        assert!(!take_any_signal_set(), "scoped peek 不该 bump 全局 epoch");
        release_subscriber_scope(sub);
    }

    #[test]
    fn peek_dependency_is_unbound_when_branch_stops_reading() {
        let sub = fresh_scope();
        let branch = Signal::new(true);
        let payload = Signal::new(0);
        with_subscriber(sub, || {
            if branch.peek() {
                let _ = payload.peek();
            }
        });
        assert_eq!(peek_dependency_count(payload.id()), 1);

        // 模拟下一轮 element build:先清旧映射,再按新分支重新登记。
        clear_peek_dependencies(sub);
        branch.set(false);
        let _ = take_dirty_for_scope(4242);
        with_subscriber(sub, || {
            if branch.peek() {
                let _ = payload.peek();
            }
        });
        assert_eq!(peek_dependency_count(payload.id()), 0, "分支不再读取后应自动解绑");
        payload.set(1);
        assert!(!take_dirty_for_scope(4242).contains(&sub), "旧分支信号不得再标脏宿主");
        release_subscriber_scope(sub);
    }

    #[test]
    fn peek_outside_subscriber_keeps_global_fallback() {
        let sub = fresh_scope();
        let sig = Signal::new(0);
        let _ = sig.peek();
        sig.set(1);
        assert!(take_dirty_for_scope(4242).is_empty());
        assert!(take_any_signal_set(), "无 subscriber 时 peek 必须保留全局兜底");
        release_subscriber_scope(sub);
    }

    #[test]
    fn invalidated_peek_dependency_does_not_cause_ghost_rebuild() {
        let sub = fresh_scope();
        let sig = Signal::new(0);
        with_subscriber(sub, || {
            let _ = sig.peek();
        });
        invalidate_subscriber(sub);
        assert_eq!(peek_dependency_count(sig.id()), 0);
        sig.set(1);
        assert!(!take_dirty_for_scope(4242).contains(&sub));
        release_subscriber_scope(sub);
    }

    #[test]
    fn peek_silent_builds_no_dependency() {
        let sub = fresh_scope();
        let sig = Signal::new(0);
        with_subscriber(sub, || {
            let _ = sig.peek_silent();
        });
        assert_eq!(peek_dependency_count(sig.id()), 0);
        sig.set(1);
        assert!(take_dirty_for_scope(4242).is_empty());
        assert!(!take_any_signal_set());
        release_subscriber_scope(sub);
    }

    #[test]
    fn host_subscriber_isolates_dirty_by_scope() {
        let a = HostSubscriber::new(9101);
        let b = HostSubscriber::new(9102);
        let sig = Signal::new(0);
        a.with(|| {
            let _ = sig.get();
        });
        b.with(|| {
            let _ = sig.get();
        });
        sig.set(1);
        assert!(a.has_dirty() && b.has_dirty());
        assert!(take_dirty_for_scope(9101).contains(&a.id()));
        assert!(!a.has_dirty());
        assert!(b.has_dirty(), "另一窗口的 dirty 不能被本 scope 取走");
        assert!(take_dirty_for_scope(9102).contains(&b.id()));
    }

    #[test]
    fn host_subscriber_rebind_drops_stale_dependency() {
        let host = HostSubscriber::new(9103);
        let branch = Signal::new(true);
        let payload = Signal::new(0);
        host.with(|| {
            if branch.get() {
                let _ = payload.get();
            }
        });
        branch.set(false);
        let _ = take_dirty_for_scope(9103);
        host.rebind(|| {
            if branch.get() {
                let _ = payload.get();
            }
        });
        payload.set(1);
        assert!(!host.has_dirty(), "rebind 后旧分支依赖必须解绑");
    }

    #[test]
    fn signal_trace_reports_peek_subscribers_and_unknown_fallback() {
        clear_signal_trace();
        set_signal_trace_enabled(true);
        let sub = fresh_scope();
        let sig = Signal::new(0);
        with_subscriber(sub, || {
            let _ = sig.peek();
        });
        sig.set(1);
        let snap = peek_signal_trace(0);
        assert_eq!(snap.len(), 1);
        assert_eq!(snap[0].peek_subscribers, vec![sub]);
        assert!(!snap[0].unknown_peek);
        set_signal_trace_enabled(false);
        clear_signal_trace();
        release_subscriber_scope(sub);
    }
}