omni-dev 0.39.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, and Datadog.
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
//! The cross-window worktree registry engine.
//!
//! Maintains the live, authoritative set of repos/worktrees open across *every*
//! VS Code window, fed by a first-party companion extension that reports from
//! each window over the daemon's control socket. The resident daemon is the
//! rendezvous point the per-window extension sandbox cannot replace: each window
//! can see only its own `workspace.workspaceFolders`, so a single process
//! aggregating those registrations is the only cross-window source of truth.
//! See ADR-0040.
//!
//! This is the standalone engine, analogous to [`crate::browser`] and
//! [`crate::snowflake`]; the daemon adapter lives in
//! [`crate::daemon::services::worktrees`].
//!
//! Like the Snowflake engine this is cheap and in-memory — no async setup, no
//! secret persisted. The registry lives behind a [`std::sync::Mutex`] that is
//! **never held across an `.await`** (the Snowflake rule); every op is pure CPU
//! under the lock, so liveness reaping happens inline on each read rather than
//! from a background task.

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use chrono::{DateTime, Duration as ChronoDuration, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::watch;

/// How long a window may go silent before it ages out of the registry. Three
/// missed ~10s heartbeats; a window that crashed without firing `unregister`
/// disappears on the next read. The resident process is what makes this
/// liveness correct — a flat shared file could not reap stale entries.
const DEFAULT_TTL: Duration = Duration::from_secs(30);

/// How long a per-repository PR-poll lease lasts before it auto-expires (#1376).
/// Enabling polling for a repo is deliberately **temporary** — 15 minutes — so an
/// idle repo stops costing GitHub budget without the user remembering to disable
/// it; re-enabling refreshes the lease.
const DEFAULT_POLL_LEASE: Duration = Duration::from_secs(15 * 60);

/// Ceiling on live registry entries, so a misbehaving companion flooding
/// `register` with distinct keys cannot grow daemon memory faster than the TTL
/// reaps it (#1140). Far above any real window count; when a new key would
/// exceed it, the longest-silent entry is evicted instead of rejecting the
/// request — an evicted live window self-heals via the `heartbeat` →
/// `{known: false}` → re-register path, so `register` stays infallible for the
/// companion.
const MAX_WINDOWS: usize = 256;

/// A `register` request from a companion extension.
///
/// The companion owns its `key` (a per-`activate()` UUID) so the registry never
/// has to reason about whether `vscode.env.sessionId` is unique per window;
/// everything else is best-effort metadata.
#[derive(Debug, Clone, Deserialize)]
pub struct RegisterRequest {
    /// Stable per-window identity, generated by the companion on activation.
    pub key: String,
    /// Absolute paths of the window's workspace folders.
    #[serde(default)]
    pub folders: Vec<PathBuf>,
    /// Repository root or name, when the window has one.
    #[serde(default)]
    pub repo: Option<String>,
    /// The window title, for display.
    #[serde(default)]
    pub title: Option<String>,
    /// The reporting extension-host process id.
    #[serde(default)]
    pub pid: Option<u32>,
}

/// One open window's live registration. Serialized verbatim into `list` /
/// `status` payloads; consumers compute age from `last_seen` (RFC 3339).
#[derive(Debug, Clone, Serialize)]
pub struct WindowEntry {
    /// The companion-owned per-window key.
    pub key: String,
    /// Absolute workspace-folder paths.
    pub folders: Vec<PathBuf>,
    /// Repository root or name, if reported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repo: Option<String>,
    /// Window title, if reported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Reporting extension-host pid, if reported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    /// When the registry last heard from this window (register or heartbeat).
    pub last_seen: DateTime<Utc>,
}

/// The cross-window worktree registry: the in-memory, TTL-reaped set of open
/// windows. Hosted by
/// [`WorktreesService`](crate::daemon::services::worktrees::WorktreesService).
pub struct WorktreesRegistry {
    /// Open windows keyed by their companion-owned `key`.
    windows: Mutex<HashMap<String, WindowEntry>>,
    /// How long an entry survives without a heartbeat.
    ttl: Duration,
    /// A monotonically-bumped version counter, incremented whenever the visible
    /// set of windows changes (a `register`, a removing `unregister`, or a
    /// mutation-driven reap that drops a stale entry). A push-subscription
    /// consumer holds a [`watch::Receiver`] from
    /// [`subscribe_changes`](Self::subscribe_changes) and wakes on each bump to
    /// re-snapshot (#1267). The counter's *value* is immaterial —
    /// only that it changed — so a burst coalesces into one wake and the
    /// subscriber diffs the resulting snapshot to suppress duplicate frames.
    ///
    /// `watch` needs no runtime and never blocks, so it fits this engine's
    /// no-async-setup posture; every [`bump`](Self::bump) happens *after* the map
    /// guard is dropped, so the `std::Mutex`-never-across-`.await` rule is intact
    /// (and the watch's own internal lock is never nested under the map lock).
    changes: watch::Sender<u64>,
    /// Window keys with a pending "close yourself" directive, set by the
    /// `close` op (#1277) when a cross-window close must reach a window the
    /// daemon can only *reply* to, never call. Each key is surfaced — and
    /// cleared — on that window's next `heartbeat` (the `known:false →
    /// re-register` precedent, riding the same reply). In-memory only, like the
    /// window map: a daemon restart drops any pending directive (the close op
    /// aborts and the user retries — an accepted failure mode). Behind its own
    /// `Mutex`, taken independently of the window map's, so neither nests.
    close_pending: Mutex<HashSet<String>>,
    /// Window keys with a pending "reload yourself" directive, set by the
    /// `reload` op (#1417). The second directive of the
    /// [`close_pending`](Self::close_pending) shape, and for the same reason: a
    /// window can only be reached on the `heartbeat` it initiates, so a
    /// cross-window reload rides that reply and is taken-and-cleared to fire
    /// exactly once. Unlike a close, nothing waits for it — a reload has no
    /// completion the daemon can observe (the window re-registers under the same
    /// key), so the op reports what it *signalled*, never what reloaded.
    /// In-memory only: a daemon restart drops any pending directive, and the
    /// user simply reloads again. Behind its **own** `Mutex`, taken
    /// independently of the window map's and of `close_pending`'s, so none nest.
    reload_pending: Mutex<HashSet<String>>,
    /// Worktree paths the daemon is **currently rebasing** (#1415) — the
    /// transient half of the tree view's rebase cue.
    ///
    /// Two orthogonal facts drive that cue and neither substitutes for the other.
    /// The *durable* one is the worktree's own `repo.state()`, read fresh off disk
    /// into each snapshot: it survives a daemon restart and keeps showing a
    /// left-in-place conflict until the user resolves it. This is the *transient*
    /// one: a rebase that is running right now has not yet written a
    /// `.git/rebase-merge` state the snapshot can see for most of its life, and a
    /// clean rebase never leaves one at all — so without this a multi-second
    /// rebase would render as nothing happening.
    ///
    /// Unlike the two directives above this is **consumer-visible state**, not a
    /// message to one window: it rides the `tree` snapshot, so marking and
    /// clearing it bumps the change-notify (a directive never does).
    ///
    /// Keyed by **canonicalized worktree path**, not window key: a rebase targets
    /// worktrees, and a worktree need not have a window open on it. Behind its own
    /// `Mutex`, taken independently of the window map's, `close_pending`'s and
    /// `reload_pending`'s, so none of the four ever nest. In-memory only — a
    /// daemon restart clears it, which is correct: nothing is rebasing any more,
    /// and the durable `operation` field still shows any conflict left behind.
    rebasing: Mutex<HashSet<PathBuf>>,
    /// The daemon-backed **show/hide-closed** toggle (#1301): whether the
    /// companion's tree view shows worktrees with no open window. A single
    /// cross-window value carried in every `tree`/`subscribe` snapshot so all
    /// windows read (and live-sync) the same state — `context.globalState` could
    /// not, being read-once with no cross-window change event. Defaults to `true`
    /// (show all, the original behavior). A lock-free [`AtomicBool`] rather than a
    /// `Mutex`, so it is never a `.await`-holding-a-lock hazard; a flip
    /// [`bump`](Self::bump)s the change-notify so subscribers re-push. In-memory
    /// like the window map: a daemon restart resets it to the default, which the
    /// next snapshot propagates to every window.
    show_closed: AtomicBool,
    /// The **per-repository PR-poll** enable set (#1376): the GitHub repos
    /// (`"owner/name"`) whose PR badges the daemon polls. Polling defaults
    /// **off** — a repo not in this set issues zero `gh` — so the user enables
    /// only the handful of repos they are actively working on, rather than the
    /// daemon polling all 29 open repos and exhausting the GitHub budget. A
    /// cross-window value like [`show_closed`](Self::show_closed): the daemon
    /// stamps each repo's state onto the `tree` snapshot (`polling_enabled`) and
    /// a [`set_polling`](Self::set_polling) flip [`bump`](Self::bump)s the
    /// change-notify so every window recolors and drops/keeps badges in sync.
    ///
    /// Unlike `show_closed` this survives a daemon restart: the adapter seeds it
    /// from a `0600` file on startup ([`seed_polling`](Self::seed_polling)) and
    /// persists it on each change — otherwise a restart would silently re-disable
    /// every repo. Behind its **own** `Mutex`, taken independently of the window
    /// map's (neither nests) and never held across an `.await`.
    ///
    /// Each enable is a **time-boxed lease**, not a permanent flag (#1376): the
    /// value is the wall-clock instant the lease **expires** ([`poll_ttl`] after
    /// it was enabled), so an idle repo auto-disables and stops costing `gh`
    /// without the user remembering to turn it back off. Expired entries are
    /// reaped on read — the window-TTL precedent — so the icon greys, badges
    /// drop, and the poller stops within one snapshot tick of expiry.
    ///
    /// [`poll_ttl`]: Self::poll_ttl
    polling_enabled: Mutex<HashMap<String, DateTime<Utc>>>,
    /// How long a repo's PR-poll lease lasts before it auto-expires (#1376).
    /// [`DEFAULT_POLL_LEASE`] in production; tests inject a short value via the
    /// `#[cfg(test)]` `with_poll_ttl` constructor (not linked — it does not exist
    /// in a non-test doc build).
    poll_ttl: Duration,
}

impl WorktreesRegistry {
    /// Creates the registry with the default liveness TTL. Cheap — no I/O.
    #[must_use]
    pub fn new() -> Self {
        Self {
            windows: Mutex::new(HashMap::new()),
            ttl: DEFAULT_TTL,
            changes: watch::channel(0).0,
            close_pending: Mutex::new(HashSet::new()),
            reload_pending: Mutex::new(HashSet::new()),
            rebasing: Mutex::new(HashSet::new()),
            show_closed: AtomicBool::new(true),
            polling_enabled: Mutex::new(HashMap::new()),
            poll_ttl: DEFAULT_POLL_LEASE,
        }
    }

    /// Creates a registry with a custom PR-poll lease duration, for tests that
    /// exercise auto-expiry without waiting the full 15 minutes.
    #[cfg(test)]
    #[must_use]
    pub fn with_poll_ttl(poll_ttl: Duration) -> Self {
        Self {
            poll_ttl,
            ..Self::new()
        }
    }

    /// A change-notification receiver for the push subscription: it observes a
    /// new value each time the visible window set changes (see [`changes`] and
    /// [`bump`]). Created with the current version already marked seen, so the
    /// first [`watch::Receiver::changed`] resolves on the *next* change — the
    /// subscriber sends its own initial snapshot up front and then waits for
    /// deltas (#1267).
    ///
    /// [`changes`]: Self::changes
    /// [`bump`]: Self::bump
    #[must_use]
    pub fn subscribe_changes(&self) -> watch::Receiver<u64> {
        self.changes.subscribe()
    }

    /// Signals subscribers that the visible state changed. Non-blocking and
    /// runtime-free; called only *after* the map guard is released so the two
    /// locks never nest. A send never fails here (the sender is owned by the
    /// registry, which outlives every receiver, and `send_modify` bumps even
    /// with no receivers).
    ///
    /// Visible outside the registry so the daemon's PR badge poller can signal a
    /// changed CI verdict (#1337) — the tree snapshot carries more than the window
    /// set. Callers must bump **only on a real change**: an unconditional bump
    /// defeats the server's snapshot diff and re-pushes to every window on every
    /// tick.
    pub(crate) fn bump(&self) {
        self.changes.send_modify(|v| *v = v.wrapping_add(1));
    }

    /// The current change-notify generation — the counter [`bump`](Self::bump)
    /// increments on every visible-set change. Read (never subscribed) so a
    /// coalescing consumer — the service's shared tree-snapshot cache (#1303) —
    /// can tell whether the registry has changed since it last computed and
    /// rebuild only then. The value itself is immaterial; only whether it
    /// differs between two reads matters, so `wrapping_add` overflow is benign.
    #[must_use]
    pub fn change_generation(&self) -> u64 {
        *self.changes.borrow()
    }

    /// Locks the registry, recovering from a poisoned mutex (a panic in a prior
    /// critical section must not wedge the whole registry).
    fn lock(&self) -> MutexGuard<'_, HashMap<String, WindowEntry>> {
        self.windows.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Records (upserts) a window registration. Reaps stale entries first, then
    /// — only when a genuinely new key would grow the map past [`MAX_WINDOWS`] —
    /// evicts the longest-silent entry. Infallible: an upsert never evicts, and
    /// callers validate the `key` before reaching here.
    pub fn register(&self, req: RegisterRequest) {
        let now = Utc::now();
        {
            let mut windows = self.lock();
            reap(&mut windows, self.ttl, now);
            // Upserts never evict; only a genuinely new key can grow the map, and
            // never past MAX_WINDOWS.
            if !windows.contains_key(&req.key) && windows.len() >= MAX_WINDOWS {
                evict_oldest(&mut windows);
            }
            windows.insert(
                req.key.clone(),
                WindowEntry {
                    key: req.key,
                    folders: req.folders,
                    repo: req.repo,
                    title: req.title,
                    pid: req.pid,
                    last_seen: now,
                },
            );
        }
        // Always bump: a register is infrequent (once per companion `activate()`,
        // not per heartbeat) and may add or alter a window's folders/repo. A
        // no-op re-register with identical data is harmless — the subscriber
        // diffs the snapshot and suppresses the duplicate frame.
        self.bump();
    }

    /// Refreshes a window's liveness. Returns whether the key was known: a
    /// `false` tells a window that started before the daemon — or survived a
    /// daemon restart — to re-`register`, since the registry is in-memory and
    /// has no record of it.
    pub fn heartbeat(&self, key: &str) -> bool {
        let now = Utc::now();
        let (known, reaped) = {
            let mut windows = self.lock();
            let reaped = reap(&mut windows, self.ttl, now);
            let known = match windows.get_mut(key) {
                Some(entry) => {
                    entry.last_seen = now;
                    true
                }
                None => false,
            };
            (known, reaped)
        };
        // A heartbeat is frequent (~every 10 s per window); a pure liveness
        // refresh does not change the visible set, so bump *only* when this
        // heartbeat's inline reap actually aged a stale sibling out.
        if reaped > 0 {
            self.bump();
        }
        known
    }

    /// Drops a window's registration. Returns whether an entry was present.
    pub fn unregister(&self, key: &str) -> bool {
        let now = Utc::now();
        let (removed, reaped) = {
            let mut windows = self.lock();
            let removed = windows.remove(key).is_some();
            let reaped = reap(&mut windows, self.ttl, now);
            (removed, reaped)
        };
        // The window is gone; any directive for it is fulfilled or moot.
        // (Keys are per-`activate()` UUIDs, never reused, so a stale directive
        // would only ever leak a little memory — but clearing keeps it tidy.)
        // Both takes are outside the map's critical section, so no lock nests.
        self.take_close_pending(key);
        self.take_reload_pending(key);
        if removed || reaped > 0 {
            self.bump();
        }
        removed
    }

    /// Records a pending "close yourself" directive for `key`, to be surfaced on
    /// that window's next `heartbeat`. Set by the `close` op when signalling a
    /// window it can only reply to. Idempotent; infallible.
    pub fn mark_close_pending(&self, key: &str) {
        self.close_pending
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(key.to_string());
    }

    /// Takes (returns and clears) `key`'s pending close directive. Called on
    /// each `heartbeat` so the directive fires exactly once; a `false` means no
    /// close is pending.
    pub fn take_close_pending(&self, key: &str) -> bool {
        self.close_pending
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(key)
    }

    /// Records a pending "reload yourself" directive for `key`, to be surfaced
    /// on that window's next `heartbeat` (#1417). Set by the `reload` op for
    /// every target window, which — unlike a close — includes no waiting: the
    /// caller learns only that the directive was marked. Idempotent; infallible.
    pub fn mark_reload_pending(&self, key: &str) {
        self.reload_pending
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(key.to_string());
    }

    /// Takes (returns and clears) `key`'s pending reload directive. Called on
    /// each `heartbeat` so the directive fires exactly once; a `false` means no
    /// reload is pending.
    pub fn take_reload_pending(&self, key: &str) -> bool {
        self.reload_pending
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(key)
    }

    /// Marks `paths` as being rebased right now (#1415), returning whether the
    /// set actually changed.
    ///
    /// A real change [`bump`](Self::bump)s the change-notify so every subscribed
    /// window re-pushes a snapshot carrying the spinner — the same cross-window
    /// sync `set_show_closed` / `set_polling` rely on. Bumping **only** on a real
    /// change is load-bearing rather than an optimization: an unconditional bump
    /// defeats the server's snapshot diff and re-pushes to every window on every
    /// tick.
    ///
    /// Callers pass **already-canonicalized** paths, so these match the tree
    /// snapshot's own keys. Canonicalizing is disk I/O, which belongs in the
    /// adapter (where `canonical()` lives), not in this engine — the same split
    /// that keeps the git enrichment out of here.
    pub fn mark_rebasing(&self, paths: &[PathBuf]) -> bool {
        self.mutate_rebasing(paths, true)
    }

    /// Clears the rebasing mark on `paths`, returning whether the set changed.
    /// Called on **every** exit from a phase-2 execute, so a panicking or failing
    /// rebase can never leave a permanent spinner on a row.
    pub fn clear_rebasing(&self, paths: &[PathBuf]) -> bool {
        self.mutate_rebasing(paths, false)
    }

    /// The shared body of [`mark_rebasing`](Self::mark_rebasing) /
    /// [`clear_rebasing`](Self::clear_rebasing): mutate under the set's own lock,
    /// drop the guard, then bump if anything moved (never bump while holding a
    /// lock, per the engine's `std::Mutex`-never-across-`.await` discipline).
    fn mutate_rebasing(&self, paths: &[PathBuf], insert: bool) -> bool {
        let changed = {
            let mut set = self.rebasing.lock().unwrap_or_else(PoisonError::into_inner);
            paths.iter().fold(false, |changed, path| {
                let moved = if insert {
                    set.insert(path.clone())
                } else {
                    set.remove(path)
                };
                changed || moved
            })
        };
        if changed {
            self.bump();
        }
        changed
    }

    /// The worktree paths currently being rebased, canonicalized. Read into each
    /// `tree`/`subscribe` snapshot; cheap (a set clone of at most a batch's worth
    /// of paths) and never held across an `.await`.
    #[must_use]
    pub fn rebasing_paths(&self) -> HashSet<PathBuf> {
        self.rebasing
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// The current show/hide-closed toggle: whether the tree view shows
    /// worktrees with no open window (#1301). Read into every `tree`/`subscribe`
    /// snapshot so every window renders the same, live-synced state.
    #[must_use]
    pub fn show_closed(&self) -> bool {
        self.show_closed.load(Ordering::Relaxed)
    }

    /// Sets the show/hide-closed toggle, returning whether the value actually
    /// changed. A real change [`bump`](Self::bump)s the change-notify so every
    /// subscriber re-pushes a snapshot carrying the new value — the reliable
    /// cross-window sync `context.globalState` could not provide. A no-op set
    /// (same value) neither bumps nor wakes anyone.
    pub fn set_show_closed(&self, show_closed: bool) -> bool {
        let changed = self.show_closed.swap(show_closed, Ordering::Relaxed) != show_closed;
        if changed {
            self.bump();
        }
        changed
    }

    /// Locks the per-repo PR-poll lease map (`"owner/name"` → lease-expiry
    /// instant), recovering from a poisoned mutex (a panic in a prior critical
    /// section must not wedge polling for the whole daemon).
    fn polling_lock(&self) -> MutexGuard<'_, HashMap<String, DateTime<Utc>>> {
        self.polling_enabled
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    /// Whether PR polling is currently leased for the GitHub repo `owner/name`
    /// (#1376) — the entry exists **and** its lease has not expired. Defaults
    /// **false** (a never-toggled repo does not poll), so only repos the user has
    /// explicitly enabled, within the last [`poll_ttl`](Self::poll_ttl), poll.
    #[must_use]
    pub fn is_polling_enabled(&self, owner: &str, name: &str) -> bool {
        let now = Utc::now();
        self.polling_lock()
            .get(&polling_key(owner, name))
            .is_some_and(|expiry| *expiry > now)
    }

    /// The repos with a **live** (unexpired) lease, as a set of `"owner/name"`
    /// keys — what stamps `polling_enabled` onto the `tree` snapshot. Reaps
    /// expired leases first (the window-TTL reap-on-read precedent), so an idle
    /// repo drops out on the next snapshot build without a background timer.
    /// Cloned out so the lock is never held across the (blocking-thread) tree
    /// build that reads it.
    #[must_use]
    pub fn enabled_polling_repos(&self) -> HashSet<String> {
        let now = Utc::now();
        let mut map = self.polling_lock();
        map.retain(|_, expiry| *expiry > now);
        map.keys().cloned().collect()
    }

    /// The live leases as `(repo, expiry)` pairs sorted by repo, for
    /// deterministic persistence to the `0600` prefs file (#1376) — the expiry is
    /// stored so a daemon restart within the lease window keeps the *remaining*
    /// time rather than resetting the clock. Reaps expired leases first, so a
    /// stale entry is never written back.
    #[must_use]
    pub fn polling_snapshot(&self) -> Vec<(String, DateTime<Utc>)> {
        let now = Utc::now();
        let mut map = self.polling_lock();
        map.retain(|_, expiry| *expiry > now);
        let mut entries: Vec<(String, DateTime<Utc>)> =
            map.iter().map(|(k, v)| (k.clone(), *v)).collect();
        entries.sort_by(|a, b| a.0.cmp(&b.0));
        entries
    }

    /// Enables (leases for [`poll_ttl`](Self::poll_ttl)) or disables PR polling
    /// for `owner/name`, returning whether the stored map changed — which the
    /// adapter uses to decide whether to persist. Enabling an already-leased repo
    /// **refreshes** the lease (a new expiry), which is a change worth persisting.
    ///
    /// [`bump`](Self::bump)s the change-notify only when the repo's **effective**
    /// enabled state flips (off→on or on→off), so every subscribed window
    /// re-pushes a snapshot that recolours the icon and drops/keeps badges — the
    /// [`set_show_closed`](Self::set_show_closed) precedent. A lease *refresh*
    /// (already on, still on) changes the expiry but not the visible state, so it
    /// persists without waking anyone.
    pub fn set_polling(&self, owner: &str, name: &str, enabled: bool) -> bool {
        let key = polling_key(owner, name);
        let now = Utc::now();
        let (changed, flipped) = {
            let mut map = self.polling_lock();
            let was_enabled = map.get(&key).is_some_and(|expiry| *expiry > now);
            if enabled {
                let expiry = now
                    + ChronoDuration::from_std(self.poll_ttl).unwrap_or_else(|_| {
                        ChronoDuration::seconds(DEFAULT_POLL_LEASE.as_secs() as i64)
                    });
                let changed = map.insert(key, expiry) != Some(expiry);
                (changed, !was_enabled)
            } else {
                let removed = map.remove(&key).is_some();
                (removed, was_enabled)
            }
        };
        if flipped {
            self.bump();
        }
        changed
    }

    /// Replaces the lease map wholesale from the persisted `0600` prefs file
    /// (#1376), dropping any lease that already expired while the daemon was down.
    /// Does **not** [`bump`](Self::bump): it runs before any window subscribes, so
    /// there is no one to notify, and each window's first snapshot already
    /// reflects the seeded leases.
    pub fn seed_polling(&self, leases: impl IntoIterator<Item = (String, DateTime<Utc>)>) {
        let now = Utc::now();
        *self.polling_lock() = leases
            .into_iter()
            .filter(|(_, expiry)| *expiry > now)
            .collect();
    }

    /// Test-only: forces `owner/name`'s lease to `expiry`, so a test can simulate
    /// an elapsed lease deterministically without sleeping for [`poll_ttl`].
    #[cfg(test)]
    pub fn set_polling_expiry(&self, owner: &str, name: &str, expiry: DateTime<Utc>) {
        self.polling_lock().insert(polling_key(owner, name), expiry);
    }

    /// Reaps stale entries, then returns the live set sorted for deterministic
    /// output. Holds the lock only for pure-CPU work.
    ///
    /// Like the other reads ([`open_folders`](Self::open_folders),
    /// [`first_folder`](Self::first_folder)) this reaps but never
    /// [`bump`](Self::bump)s: the only observer of a read-path reap is the push
    /// subscription's own re-snapshot (or `status`/`menu`), and the
    /// subscription's periodic tick already re-samples read-only staleness — so
    /// bumping here would only make the subscription wake itself (#1267).
    pub fn list(&self) -> Vec<WindowEntry> {
        let now = Utc::now();
        let mut windows = self.lock();
        reap(&mut windows, self.ttl, now);
        sorted_entries(&windows)
    }

    /// The first workspace folder of a still-live window, if it has one. Used by
    /// the tray "focus" action to resolve a key to a folder to open. Does not
    /// reap — a menu action races the reaper either way, and the caller handles
    /// a `None` (the window may have closed).
    pub fn first_folder(&self, key: &str) -> Option<PathBuf> {
        let windows = self.lock();
        windows.get(key).and_then(|e| e.folders.first().cloned())
    }

    /// Snapshots the distinct workspace folders across all live windows — the
    /// seed set the adapter resolves to repositories (each folder → its git
    /// common dir → repo root) to enumerate every worktree per repo (#1265).
    ///
    /// Reaps stale entries first, then returns the folders sorted and
    /// deduplicated. Like [`list`](Self::list) it is pure CPU under the lock:
    /// the git resolution the "distinct repos" derivation needs is disk I/O and
    /// stays in the adapter, off the registry lock, honouring the
    /// `Mutex`-never-across-`.await` invariant.
    pub fn open_folders(&self) -> Vec<PathBuf> {
        let now = Utc::now();
        let mut windows = self.lock();
        reap(&mut windows, self.ttl, now);
        let mut folders: Vec<PathBuf> = windows
            .values()
            .flat_map(|e| e.folders.iter().cloned())
            .collect();
        folders.sort();
        folders.dedup();
        folders
    }
}

impl Default for WorktreesRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Removes entries last seen longer than `ttl` ago, returning how many were
/// dropped. Pure CPU; the caller holds the registry lock but never `.await`s
/// while holding it. The count lets a *mutation* path
/// ([`register`](WorktreesRegistry::register) et al.) decide whether to
/// [`bump`](WorktreesRegistry::bump) the change-notify; read paths ignore it (see
/// [`list`](WorktreesRegistry::list)).
fn reap(windows: &mut HashMap<String, WindowEntry>, ttl: Duration, now: DateTime<Utc>) -> usize {
    let max_age = ttl.as_secs() as i64;
    let before = windows.len();
    windows.retain(|_, e| (now - e.last_seen).num_seconds() <= max_age);
    before - windows.len()
}

/// Removes the entry with the oldest `last_seen` (ties broken by lowest key
/// for determinism). Called when a `register` of a new key would grow the
/// registry past [`MAX_WINDOWS`]. Pure CPU under the registry lock, like
/// [`reap`].
fn evict_oldest(windows: &mut HashMap<String, WindowEntry>) {
    let oldest = windows
        .values()
        .min_by(|a, b| {
            a.last_seen
                .cmp(&b.last_seen)
                .then_with(|| a.key.cmp(&b.key))
        })
        .map(|e| e.key.clone());
    if let Some(key) = oldest {
        windows.remove(&key);
    }
}

/// The canonical key for a GitHub repo in the per-repo PR-poll set: `owner/name`
/// (#1376). One place so the registry's set, the snapshot stamp, and the poller
/// filter all agree on the exact string.
fn polling_key(owner: &str, name: &str) -> String {
    format!("{owner}/{name}")
}

/// Snapshots the registry into a stably-ordered vector (by repo, then key) so
/// `list`/`status`/`menu` output is deterministic despite `HashMap` ordering.
fn sorted_entries(windows: &HashMap<String, WindowEntry>) -> Vec<WindowEntry> {
    let mut entries: Vec<WindowEntry> = windows.values().cloned().collect();
    entries.sort_by(|a, b| a.repo.cmp(&b.repo).then_with(|| a.key.cmp(&b.key)));
    entries
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    fn register_request(key: &str, repo: Option<&str>, folder: &str) -> RegisterRequest {
        RegisterRequest {
            key: key.to_string(),
            folders: vec![PathBuf::from(folder)],
            repo: repo.map(str::to_string),
            title: Some(format!("{key}-title")),
            pid: Some(1234),
        }
    }

    #[test]
    fn list_is_empty_initially() {
        let reg = WorktreesRegistry::new();
        assert!(reg.list().is_empty());
    }

    #[test]
    fn register_then_list_round_trips() {
        let reg = WorktreesRegistry::new();
        reg.register(register_request("w1", Some("repo-a"), "/tmp/a"));
        let windows = reg.list();
        assert_eq!(windows.len(), 1);
        assert_eq!(windows[0].key, "w1");
        assert_eq!(windows[0].repo.as_deref(), Some("repo-a"));
    }

    #[test]
    fn register_is_idempotent_upsert() {
        let reg = WorktreesRegistry::new();
        reg.register(register_request("w1", Some("repo-a"), "/tmp/a"));
        // Re-registering the same key updates rather than duplicates.
        reg.register(register_request("w1", Some("repo-b"), "/tmp/b"));
        let windows = reg.list();
        assert_eq!(windows.len(), 1);
        assert_eq!(windows[0].repo.as_deref(), Some("repo-b"));
    }

    #[test]
    fn heartbeat_reports_known_and_unknown() {
        let reg = WorktreesRegistry::new();
        // Unknown before registration: the window must re-register.
        assert!(!reg.heartbeat("w1"));
        reg.register(register_request("w1", None, "/tmp/a"));
        assert!(reg.heartbeat("w1"));
    }

    #[test]
    fn unregister_removes() {
        let reg = WorktreesRegistry::new();
        reg.register(register_request("w1", None, "/tmp/a"));
        assert!(reg.unregister("w1"));
        // Removing again is a no-op.
        assert!(!reg.unregister("w1"));
    }

    #[test]
    fn first_folder_returns_first_folder_or_none() {
        let reg = WorktreesRegistry::new();
        // No such key.
        assert!(reg.first_folder("missing").is_none());
        reg.register(register_request("w1", None, "/tmp/a"));
        assert_eq!(reg.first_folder("w1"), Some(PathBuf::from("/tmp/a")));
        // A folderless window resolves to None rather than a folder.
        reg.register(RegisterRequest {
            key: "w2".to_string(),
            folders: vec![],
            repo: None,
            title: None,
            pid: None,
        });
        assert!(reg.first_folder("w2").is_none());
    }

    #[test]
    fn open_folders_dedups_and_sorts_across_windows() {
        let reg = WorktreesRegistry::new();
        assert!(reg.open_folders().is_empty());
        // Two windows sharing a folder, plus a multi-folder window: the shared
        // path collapses and the result is sorted.
        reg.register(register_request("w1", Some("repo-a"), "/tmp/shared"));
        reg.register(RegisterRequest {
            key: "w2".to_string(),
            folders: vec![PathBuf::from("/tmp/shared"), PathBuf::from("/tmp/b")],
            repo: Some("repo-a".to_string()),
            title: None,
            pid: None,
        });
        reg.register(register_request("w3", Some("repo-b"), "/tmp/a"));
        assert_eq!(
            reg.open_folders(),
            vec![
                PathBuf::from("/tmp/a"),
                PathBuf::from("/tmp/b"),
                PathBuf::from("/tmp/shared"),
            ]
        );
    }

    #[test]
    fn open_folders_reaps_stale_windows() {
        let reg = WorktreesRegistry::new();
        {
            let mut windows = reg.lock();
            windows.insert(
                "fresh".to_string(),
                WindowEntry {
                    key: "fresh".to_string(),
                    folders: vec![PathBuf::from("/tmp/fresh")],
                    repo: None,
                    title: None,
                    pid: None,
                    last_seen: Utc::now(),
                },
            );
            windows.insert(
                "stale".to_string(),
                WindowEntry {
                    key: "stale".to_string(),
                    folders: vec![PathBuf::from("/tmp/stale")],
                    repo: None,
                    title: None,
                    pid: None,
                    last_seen: Utc::now() - chrono::Duration::seconds(120),
                },
            );
        }
        // The stale window's folder is reaped out of the snapshot.
        assert_eq!(reg.open_folders(), vec![PathBuf::from("/tmp/fresh")]);
    }

    #[test]
    fn reap_evicts_only_stale_entries() {
        let now = Utc::now();
        let mut windows = HashMap::new();
        windows.insert(
            "fresh".to_string(),
            WindowEntry {
                key: "fresh".to_string(),
                folders: vec![],
                repo: None,
                title: None,
                pid: None,
                last_seen: now - chrono::Duration::seconds(5),
            },
        );
        windows.insert(
            "stale".to_string(),
            WindowEntry {
                key: "stale".to_string(),
                folders: vec![],
                repo: None,
                title: None,
                pid: None,
                last_seen: now - chrono::Duration::seconds(120),
            },
        );
        reap(&mut windows, DEFAULT_TTL, now);
        assert!(windows.contains_key("fresh"));
        assert!(!windows.contains_key("stale"));
    }

    /// A minimal entry for cap/eviction tests; only `key` and `last_seen`
    /// participate in eviction order.
    fn entry_at(key: &str, last_seen: DateTime<Utc>) -> WindowEntry {
        WindowEntry {
            key: key.to_string(),
            folders: vec![],
            repo: None,
            title: None,
            pid: None,
            last_seen,
        }
    }

    #[test]
    fn evict_oldest_removes_oldest_with_key_tiebreak() {
        let now = Utc::now();
        let mut windows = HashMap::new();
        windows.insert("young".to_string(), entry_at("young", now));
        windows.insert(
            "old-b".to_string(),
            entry_at("old-b", now - chrono::Duration::seconds(10)),
        );
        windows.insert(
            "old-a".to_string(),
            entry_at("old-a", now - chrono::Duration::seconds(10)),
        );
        // Oldest `last_seen` is shared by two entries; the lowest key loses.
        evict_oldest(&mut windows);
        assert!(!windows.contains_key("old-a"));
        assert!(windows.contains_key("old-b"));
        assert!(windows.contains_key("young"));
        // Empty map is a no-op rather than a panic.
        let mut empty: HashMap<String, WindowEntry> = HashMap::new();
        evict_oldest(&mut empty);
        assert!(empty.is_empty());
    }

    #[test]
    fn register_at_cap_evicts_only_the_oldest() {
        let reg = WorktreesRegistry::new();
        // Seed a full registry directly (registering 256 times would work too,
        // but sub-second timestamps may tie; explicit timestamps make the
        // highest-numbered key unambiguously the oldest).
        {
            let mut windows = reg.lock();
            let base = Utc::now();
            for i in 0..MAX_WINDOWS {
                let key = format!("w{i:03}");
                windows.insert(
                    key.clone(),
                    entry_at(&key, base - chrono::Duration::milliseconds(i as i64)),
                );
            }
        }
        // A new key at the cap displaces exactly the longest-silent entry.
        reg.register(register_request("fresh", None, "/tmp/f"));
        let windows = reg.lock();
        assert_eq!(windows.len(), MAX_WINDOWS);
        assert!(windows.contains_key("fresh"));
        assert!(!windows.contains_key(&format!("w{:03}", MAX_WINDOWS - 1)));
        assert!(windows.contains_key("w000"));
    }

    #[test]
    fn register_upsert_at_cap_does_not_evict() {
        let reg = WorktreesRegistry::new();
        {
            let mut windows = reg.lock();
            let base = Utc::now();
            for i in 0..MAX_WINDOWS {
                let key = format!("w{i:03}");
                windows.insert(
                    key.clone(),
                    entry_at(&key, base - chrono::Duration::milliseconds(i as i64)),
                );
            }
        }
        // Re-registering an existing key is an upsert: nothing is displaced,
        // not even the oldest entry.
        let oldest = format!("w{:03}", MAX_WINDOWS - 1);
        reg.register(register_request(&oldest, Some("r"), "/tmp/a"));
        let windows = reg.lock();
        assert_eq!(windows.len(), MAX_WINDOWS);
        assert!(windows.contains_key(&oldest));
        assert!(windows.contains_key("w000"));
    }

    #[test]
    fn sorted_entries_orders_by_repo_then_key() {
        let now = Utc::now();
        let mut windows = HashMap::new();
        for (key, repo) in [("z", "repo-a"), ("a", "repo-b"), ("m", "repo-a")] {
            windows.insert(
                key.to_string(),
                WindowEntry {
                    key: key.to_string(),
                    folders: vec![],
                    repo: Some(repo.to_string()),
                    title: None,
                    pid: None,
                    last_seen: now,
                },
            );
        }
        let entries = sorted_entries(&windows);
        let ordered: Vec<(&str, &str)> = entries
            .iter()
            .map(|e| (e.key.as_str(), e.repo.as_deref().unwrap()))
            .collect();
        assert_eq!(
            ordered,
            vec![("m", "repo-a"), ("z", "repo-a"), ("a", "repo-b")]
        );
    }

    #[test]
    fn default_constructs_an_empty_registry() {
        let reg = WorktreesRegistry::default();
        assert!(reg.lock().is_empty());
    }

    // --- Change-notify for the push subscription (#1267) --------------------

    #[test]
    fn subscribe_changes_starts_seen_and_register_bumps() {
        let reg = WorktreesRegistry::new();
        let mut rx = reg.subscribe_changes();
        // A fresh receiver has the current version already marked seen.
        assert!(!rx.has_changed().unwrap());
        // A register changes the visible set → the receiver observes a new value.
        reg.register(register_request("w1", None, "/tmp/a"));
        assert!(rx.has_changed().unwrap(), "register should bump");
        // Marking it seen clears the pending change.
        rx.borrow_and_update();
        assert!(!rx.has_changed().unwrap());
    }

    #[test]
    fn unregister_bumps_only_when_it_removes() {
        let reg = WorktreesRegistry::new();
        reg.register(register_request("w1", None, "/tmp/a"));
        // Subscribe *after* the register so its bump is already seen.
        let rx = reg.subscribe_changes();
        // Removing a missing key changes nothing (and reaps nothing) → no bump.
        assert!(!reg.unregister("ghost"));
        assert!(
            !rx.has_changed().unwrap(),
            "a no-op unregister must not bump"
        );
        // Removing a present key bumps.
        assert!(reg.unregister("w1"));
        assert!(
            rx.has_changed().unwrap(),
            "a removing unregister should bump"
        );
    }

    #[test]
    fn change_generation_advances_only_on_a_visible_change() {
        let reg = WorktreesRegistry::new();
        let g0 = reg.change_generation();
        // A no-op (heartbeat of an unknown key) leaves the generation untouched.
        assert!(!reg.heartbeat("ghost"));
        assert_eq!(
            reg.change_generation(),
            g0,
            "a no-op must not advance the generation"
        );
        // A register changes the visible set → the generation advances, so a
        // cache keyed on it rebuilds.
        reg.register(register_request("w1", None, "/tmp/a"));
        assert_ne!(
            reg.change_generation(),
            g0,
            "a register should advance the generation"
        );
    }

    #[test]
    fn heartbeat_bumps_only_when_it_reaps() {
        let reg = WorktreesRegistry::new();
        reg.register(register_request("w1", None, "/tmp/a"));
        let rx = reg.subscribe_changes();
        // A plain heartbeat refreshes liveness but changes no visible state.
        assert!(reg.heartbeat("w1"));
        assert!(!rx.has_changed().unwrap(), "a pure heartbeat must not bump");
        // Seed a stale sibling directly; a heartbeat that reaps it *does* bump.
        {
            let mut windows = reg.lock();
            windows.insert(
                "stale".to_string(),
                entry_at("stale", Utc::now() - chrono::Duration::seconds(120)),
            );
        }
        assert!(reg.heartbeat("w1"));
        assert!(
            rx.has_changed().unwrap(),
            "a heartbeat that reaps a stale sibling should bump"
        );
    }

    // --- Close-pending directive (#1277) -----------------------------------

    #[test]
    fn close_pending_is_taken_once_then_cleared() {
        let reg = WorktreesRegistry::new();
        // No directive by default.
        assert!(!reg.take_close_pending("w1"));
        // Marked → the first take observes it, the next does not (fires once).
        reg.mark_close_pending("w1");
        assert!(reg.take_close_pending("w1"));
        assert!(!reg.take_close_pending("w1"));
    }

    #[test]
    fn unregister_clears_a_pending_close_directive() {
        let reg = WorktreesRegistry::new();
        reg.register(register_request("w1", None, "/tmp/a"));
        reg.mark_close_pending("w1");
        // Unregistering the window drops any pending directive with it.
        assert!(reg.unregister("w1"));
        assert!(!reg.take_close_pending("w1"));
    }

    // --- Reload-pending directive (#1417) ----------------------------------

    #[test]
    fn reload_pending_is_taken_once_then_cleared() {
        let reg = WorktreesRegistry::new();
        // No directive by default.
        assert!(!reg.take_reload_pending("w1"));
        // Marked → the first take observes it, the next does not (fires once).
        reg.mark_reload_pending("w1");
        assert!(reg.take_reload_pending("w1"));
        assert!(!reg.take_reload_pending("w1"));
    }

    #[test]
    fn unregister_clears_a_pending_reload_directive() {
        let reg = WorktreesRegistry::new();
        reg.register(register_request("w1", None, "/tmp/a"));
        reg.mark_reload_pending("w1");
        // Unregistering the window drops any pending directive with it.
        assert!(reg.unregister("w1"));
        assert!(!reg.take_reload_pending("w1"));
    }

    #[test]
    fn close_and_reload_directives_are_independent() {
        let reg = WorktreesRegistry::new();
        // Separate sets: marking one must not set or consume the other, so the
        // heartbeat can surface both fields and the companion pick a winner.
        reg.mark_reload_pending("w1");
        assert!(!reg.take_close_pending("w1"));
        reg.mark_close_pending("w1");
        assert!(reg.take_close_pending("w1"));
        assert!(reg.take_reload_pending("w1"));
        // Each key is tracked on its own.
        reg.mark_reload_pending("w1");
        assert!(!reg.take_reload_pending("w2"));
        assert!(reg.take_reload_pending("w1"));
    }

    #[test]
    fn marking_a_reload_does_not_bump() {
        let reg = WorktreesRegistry::new();
        reg.register(register_request("w1", None, "/tmp/a"));
        let rx = reg.subscribe_changes();
        // A directive is not consumer-visible state — it never reaches a tree
        // snapshot — so marking one must not push a redundant frame to every
        // subscriber. Same rule as the close directive.
        reg.mark_reload_pending("w1");
        assert!(!rx.has_changed().unwrap(), "marking a reload must not bump");
        assert!(reg.take_reload_pending("w1"));
        assert!(!rx.has_changed().unwrap(), "taking a reload must not bump");
    }

    // --- Rebasing set (#1415) ----------------------------------------------

    #[test]
    fn rebasing_marks_and_clears_the_named_paths() {
        let reg = WorktreesRegistry::new();
        let a = PathBuf::from("/tmp/a");
        let b = PathBuf::from("/tmp/b");
        assert!(
            reg.rebasing_paths().is_empty(),
            "nothing rebases by default"
        );

        assert!(reg.mark_rebasing(&[a.clone(), b.clone()]));
        assert_eq!(reg.rebasing_paths(), [a.clone(), b.clone()].into());

        // Clearing one leaves the other — a batch reports per worktree.
        assert!(reg.clear_rebasing(std::slice::from_ref(&a)));
        assert_eq!(reg.rebasing_paths(), [b.clone()].into());
        assert!(reg.clear_rebasing(&[b]));
        assert!(reg.rebasing_paths().is_empty());
    }

    #[test]
    fn rebasing_bumps_only_on_a_real_change() {
        // Load-bearing: an unconditional bump would defeat the server's snapshot
        // diff and re-push a `tree` frame to every window on every tick.
        let reg = WorktreesRegistry::new();
        let path = PathBuf::from("/tmp/a");

        let mut rx = reg.subscribe_changes();
        assert!(reg.mark_rebasing(std::slice::from_ref(&path)));
        assert!(rx.has_changed().unwrap(), "the first mark bumps");
        let _ = rx.borrow_and_update();

        assert!(
            !reg.mark_rebasing(std::slice::from_ref(&path)),
            "re-marking an already-rebasing path is not a change"
        );
        assert!(!rx.has_changed().unwrap(), "a no-op mark must not bump");

        assert!(
            !reg.clear_rebasing(&[PathBuf::from("/tmp/never-marked")]),
            "clearing an unmarked path is not a change"
        );
        assert!(!rx.has_changed().unwrap(), "a no-op clear must not bump");

        assert!(reg.clear_rebasing(&[path]));
        assert!(rx.has_changed().unwrap(), "a real clear bumps");
    }

    // --- Show/hide-closed toggle (#1301) -----------------------------------

    #[test]
    fn show_closed_defaults_to_true() {
        let reg = WorktreesRegistry::new();
        assert!(reg.show_closed(), "default is show all");
    }

    #[test]
    fn set_show_closed_reports_change_and_is_idempotent() {
        let reg = WorktreesRegistry::new();
        // Flipping to a new value reports a change and is observable.
        assert!(reg.set_show_closed(false));
        assert!(!reg.show_closed());
        // Setting the same value again is a no-op (no change reported).
        assert!(!reg.set_show_closed(false));
        // Flipping back reports a change again.
        assert!(reg.set_show_closed(true));
        assert!(reg.show_closed());
    }

    #[test]
    fn set_show_closed_bumps_only_on_change() {
        let reg = WorktreesRegistry::new();
        let rx = reg.subscribe_changes();
        // A no-op set (already the default) does not wake subscribers.
        assert!(!reg.set_show_closed(true));
        assert!(
            !rx.has_changed().unwrap(),
            "a no-op toggle must not bump the change-notify"
        );
        // A real flip bumps so subscribers re-push a snapshot with the new value.
        assert!(reg.set_show_closed(false));
        assert!(
            rx.has_changed().unwrap(),
            "flipping the toggle should bump the change-notify"
        );
    }

    #[test]
    fn polling_defaults_off_for_an_untoggled_repo() {
        let reg = WorktreesRegistry::new();
        // #1376: the whole point — a repo the user has never enabled is not polled.
        assert!(!reg.is_polling_enabled("rust-works", "omni-dev"));
        assert!(reg.enabled_polling_repos().is_empty());
        assert!(reg.polling_snapshot().is_empty());
    }

    #[test]
    fn set_polling_leases_and_disables() {
        let reg = WorktreesRegistry::new();
        // Enabling a fresh repo reports a change and leases it live.
        assert!(reg.set_polling("rust-works", "omni-dev", true));
        assert!(reg.is_polling_enabled("rust-works", "omni-dev"));
        // Re-enabling refreshes the lease — the map changes (new expiry).
        assert!(reg.set_polling("rust-works", "omni-dev", true));
        assert!(reg.is_polling_enabled("rust-works", "omni-dev"));
        // Disabling reports a change and clears it.
        assert!(reg.set_polling("rust-works", "omni-dev", false));
        assert!(!reg.is_polling_enabled("rust-works", "omni-dev"));
        // Disabling an already-disabled repo is a no-op.
        assert!(!reg.set_polling("rust-works", "omni-dev", false));
    }

    #[test]
    fn polling_lease_auto_expires() {
        // The 15-minute lease (#1376): an enabled repo drops out once its lease
        // elapses, reaped on the next read — no background timer.
        let reg = WorktreesRegistry::new();
        reg.set_polling("rust-works", "omni-dev", true);
        assert!(reg.is_polling_enabled("rust-works", "omni-dev"));
        // Force the lease into the past (as if 15 min elapsed).
        reg.set_polling_expiry(
            "rust-works",
            "omni-dev",
            Utc::now() - ChronoDuration::seconds(1),
        );
        assert!(
            !reg.is_polling_enabled("rust-works", "omni-dev"),
            "an expired lease reads as disabled"
        );
        // The read paths reap it, so it is gone from the snapshot entirely.
        assert!(reg.enabled_polling_repos().is_empty());
        assert!(reg.polling_snapshot().is_empty());
        // A tiny real TTL expires on its own after a short sleep.
        let short = WorktreesRegistry::with_poll_ttl(Duration::from_millis(30));
        short.set_polling("o", "n", true);
        assert!(short.is_polling_enabled("o", "n"));
        std::thread::sleep(Duration::from_millis(60));
        assert!(!short.is_polling_enabled("o", "n"));
    }

    #[test]
    fn set_polling_bumps_only_on_an_effective_flip() {
        let reg = WorktreesRegistry::new();
        let rx = reg.subscribe_changes();
        // A no-op (disabling an already-off repo) does not wake subscribers.
        assert!(!reg.set_polling("o", "n", false));
        assert!(
            !rx.has_changed().unwrap(),
            "a no-op poll toggle must not bump the change-notify"
        );
        // A real enable flips off→on and bumps so every window recolors.
        assert!(reg.set_polling("o", "n", true));
        assert!(
            rx.has_changed().unwrap(),
            "enabling a repo should bump the change-notify"
        );
    }

    #[test]
    fn refreshing_a_live_lease_does_not_bump() {
        // A lease refresh (already on, still on) persists a new expiry but does
        // not change the visible state, so it must not wake every window.
        let reg = WorktreesRegistry::new();
        reg.set_polling("o", "n", true);
        let rx = reg.subscribe_changes();
        assert!(
            reg.set_polling("o", "n", true),
            "re-enabling refreshes the lease (map changed → persist)"
        );
        assert!(
            !rx.has_changed().unwrap(),
            "refreshing a live lease must not bump — the visible state is unchanged"
        );
    }

    #[test]
    fn seed_polling_loads_leases_and_drops_expired() {
        let reg = WorktreesRegistry::new();
        reg.set_polling("a", "z", true);
        let future = Utc::now() + ChronoDuration::minutes(10);
        let past = Utc::now() - ChronoDuration::minutes(1);
        // Seeding (the startup load) replaces wholesale, dropping the prior entry
        // and any already-expired lease from the file.
        reg.seed_polling([
            ("rust-works/omni-dev".to_string(), future),
            ("acme/widgets".to_string(), future),
            ("stale/repo".to_string(), past),
        ]);
        assert!(!reg.is_polling_enabled("a", "z"));
        assert!(reg.is_polling_enabled("rust-works", "omni-dev"));
        assert!(
            !reg.is_polling_enabled("stale", "repo"),
            "expired lease dropped"
        );
        // The persisted form is deterministic (sorted) and carries the expiries.
        let snap = reg.polling_snapshot();
        assert_eq!(
            snap.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(),
            vec![
                "acme/widgets".to_string(),
                "rust-works/omni-dev".to_string()
            ]
        );
        assert!(snap.iter().all(|(_, expiry)| *expiry == future));
    }
}