Skip to main content

omni_dev/
worktrees.rs

1//! The cross-window worktree registry engine.
2//!
3//! Maintains the live, authoritative set of repos/worktrees open across *every*
4//! VS Code window, fed by a first-party companion extension that reports from
5//! each window over the daemon's control socket. The resident daemon is the
6//! rendezvous point the per-window extension sandbox cannot replace: each window
7//! can see only its own `workspace.workspaceFolders`, so a single process
8//! aggregating those registrations is the only cross-window source of truth.
9//! See ADR-0040.
10//!
11//! This is the standalone engine, analogous to [`crate::browser`] and
12//! [`crate::snowflake`]; the daemon adapter lives in
13//! [`crate::daemon::services::worktrees`].
14//!
15//! Like the Snowflake engine this is cheap and in-memory — no async setup, no
16//! secret persisted. The registry lives behind a [`std::sync::Mutex`] that is
17//! **never held across an `.await`** (the Snowflake rule); every op is pure CPU
18//! under the lock, so liveness reaping happens inline on each read rather than
19//! from a background task.
20
21use std::collections::{HashMap, HashSet};
22use std::path::PathBuf;
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::sync::{Mutex, MutexGuard, PoisonError};
25use std::time::Duration;
26
27use chrono::{DateTime, Duration as ChronoDuration, Utc};
28use serde::{Deserialize, Serialize};
29use tokio::sync::watch;
30
31/// How long a window may go silent before it ages out of the registry. Three
32/// missed ~10s heartbeats; a window that crashed without firing `unregister`
33/// disappears on the next read. The resident process is what makes this
34/// liveness correct — a flat shared file could not reap stale entries.
35const DEFAULT_TTL: Duration = Duration::from_secs(30);
36
37/// How long a per-repository PR-poll lease lasts before it auto-expires (#1376).
38/// Enabling polling for a repo is deliberately **temporary** — 15 minutes — so an
39/// idle repo stops costing GitHub budget without the user remembering to disable
40/// it; re-enabling refreshes the lease.
41const DEFAULT_POLL_LEASE: Duration = Duration::from_secs(15 * 60);
42
43/// Ceiling on live registry entries, so a misbehaving companion flooding
44/// `register` with distinct keys cannot grow daemon memory faster than the TTL
45/// reaps it (#1140). Far above any real window count; when a new key would
46/// exceed it, the longest-silent entry is evicted instead of rejecting the
47/// request — an evicted live window self-heals via the `heartbeat` →
48/// `{known: false}` → re-register path, so `register` stays infallible for the
49/// companion.
50const MAX_WINDOWS: usize = 256;
51
52/// A `register` request from a companion extension.
53///
54/// The companion owns its `key` (a per-`activate()` UUID) so the registry never
55/// has to reason about whether `vscode.env.sessionId` is unique per window;
56/// everything else is best-effort metadata.
57#[derive(Debug, Clone, Deserialize)]
58pub struct RegisterRequest {
59    /// Stable per-window identity, generated by the companion on activation.
60    pub key: String,
61    /// Absolute paths of the window's workspace folders.
62    #[serde(default)]
63    pub folders: Vec<PathBuf>,
64    /// Repository root or name, when the window has one.
65    #[serde(default)]
66    pub repo: Option<String>,
67    /// The window title, for display.
68    #[serde(default)]
69    pub title: Option<String>,
70    /// The reporting extension-host process id.
71    #[serde(default)]
72    pub pid: Option<u32>,
73}
74
75/// One open window's live registration. Serialized verbatim into `list` /
76/// `status` payloads; consumers compute age from `last_seen` (RFC 3339).
77#[derive(Debug, Clone, Serialize)]
78pub struct WindowEntry {
79    /// The companion-owned per-window key.
80    pub key: String,
81    /// Absolute workspace-folder paths.
82    pub folders: Vec<PathBuf>,
83    /// Repository root or name, if reported.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub repo: Option<String>,
86    /// Window title, if reported.
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub title: Option<String>,
89    /// Reporting extension-host pid, if reported.
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub pid: Option<u32>,
92    /// When the registry last heard from this window (register or heartbeat).
93    pub last_seen: DateTime<Utc>,
94}
95
96/// The cross-window worktree registry: the in-memory, TTL-reaped set of open
97/// windows. Hosted by
98/// [`WorktreesService`](crate::daemon::services::worktrees::WorktreesService).
99pub struct WorktreesRegistry {
100    /// Open windows keyed by their companion-owned `key`.
101    windows: Mutex<HashMap<String, WindowEntry>>,
102    /// How long an entry survives without a heartbeat.
103    ttl: Duration,
104    /// A monotonically-bumped version counter, incremented whenever the visible
105    /// set of windows changes (a `register`, a removing `unregister`, or a
106    /// mutation-driven reap that drops a stale entry). A push-subscription
107    /// consumer holds a [`watch::Receiver`] from
108    /// [`subscribe_changes`](Self::subscribe_changes) and wakes on each bump to
109    /// re-snapshot (#1267). The counter's *value* is immaterial —
110    /// only that it changed — so a burst coalesces into one wake and the
111    /// subscriber diffs the resulting snapshot to suppress duplicate frames.
112    ///
113    /// `watch` needs no runtime and never blocks, so it fits this engine's
114    /// no-async-setup posture; every [`bump`](Self::bump) happens *after* the map
115    /// guard is dropped, so the `std::Mutex`-never-across-`.await` rule is intact
116    /// (and the watch's own internal lock is never nested under the map lock).
117    changes: watch::Sender<u64>,
118    /// Window keys with a pending "close yourself" directive, set by the
119    /// `close` op (#1277) when a cross-window close must reach a window the
120    /// daemon can only *reply* to, never call. Each key is surfaced — and
121    /// cleared — on that window's next `heartbeat` (the `known:false →
122    /// re-register` precedent, riding the same reply). In-memory only, like the
123    /// window map: a daemon restart drops any pending directive (the close op
124    /// aborts and the user retries — an accepted failure mode). Behind its own
125    /// `Mutex`, taken independently of the window map's, so neither nests.
126    close_pending: Mutex<HashSet<String>>,
127    /// Window keys with a pending "reload yourself" directive, set by the
128    /// `reload` op (#1417). The second directive of the
129    /// [`close_pending`](Self::close_pending) shape, and for the same reason: a
130    /// window can only be reached on the `heartbeat` it initiates, so a
131    /// cross-window reload rides that reply and is taken-and-cleared to fire
132    /// exactly once. Unlike a close, nothing waits for it — a reload has no
133    /// completion the daemon can observe (the window re-registers under the same
134    /// key), so the op reports what it *signalled*, never what reloaded.
135    /// In-memory only: a daemon restart drops any pending directive, and the
136    /// user simply reloads again. Behind its **own** `Mutex`, taken
137    /// independently of the window map's and of `close_pending`'s, so none nest.
138    reload_pending: Mutex<HashSet<String>>,
139    /// Worktree paths the daemon is **currently rebasing** (#1415) — the
140    /// transient half of the tree view's rebase cue.
141    ///
142    /// Two orthogonal facts drive that cue and neither substitutes for the other.
143    /// The *durable* one is the worktree's own `repo.state()`, read fresh off disk
144    /// into each snapshot: it survives a daemon restart and keeps showing a
145    /// left-in-place conflict until the user resolves it. This is the *transient*
146    /// one: a rebase that is running right now has not yet written a
147    /// `.git/rebase-merge` state the snapshot can see for most of its life, and a
148    /// clean rebase never leaves one at all — so without this a multi-second
149    /// rebase would render as nothing happening.
150    ///
151    /// Unlike the two directives above this is **consumer-visible state**, not a
152    /// message to one window: it rides the `tree` snapshot, so marking and
153    /// clearing it bumps the change-notify (a directive never does).
154    ///
155    /// Keyed by **canonicalized worktree path**, not window key: a rebase targets
156    /// worktrees, and a worktree need not have a window open on it. Behind its own
157    /// `Mutex`, taken independently of the window map's, `close_pending`'s and
158    /// `reload_pending`'s, so none of the four ever nest. In-memory only — a
159    /// daemon restart clears it, which is correct: nothing is rebasing any more,
160    /// and the durable `operation` field still shows any conflict left behind.
161    rebasing: Mutex<HashSet<PathBuf>>,
162    /// Worktree paths the daemon is **currently pushing** (#1443) — the twin of
163    /// [`rebasing`](Self::rebasing), with the same keying, locking and
164    /// bump-only-on-a-real-change contract.
165    ///
166    /// Unlike a rebase this cue has **no durable half**: a push writes no on-disk
167    /// state for a later snapshot to rediscover, so there is no `operation`
168    /// equivalent and this set is the whole of it. What makes a *completed* push
169    /// visible instead is `upstream_sha` moving on the snapshot — which is exactly
170    /// why that field is carried (#1344).
171    pushing: Mutex<HashSet<PathBuf>>,
172    /// The daemon-backed **show/hide-closed** toggle (#1301): whether the
173    /// companion's tree view shows worktrees with no open window. A single
174    /// cross-window value carried in every `tree`/`subscribe` snapshot so all
175    /// windows read (and live-sync) the same state — `context.globalState` could
176    /// not, being read-once with no cross-window change event. Defaults to `true`
177    /// (show all, the original behavior). A lock-free [`AtomicBool`] rather than a
178    /// `Mutex`, so it is never a `.await`-holding-a-lock hazard; a flip
179    /// [`bump`](Self::bump)s the change-notify so subscribers re-push. In-memory
180    /// like the window map: a daemon restart resets it to the default, which the
181    /// next snapshot propagates to every window.
182    show_closed: AtomicBool,
183    /// The **per-repository PR-poll** enable set (#1376): the GitHub repos
184    /// (`"owner/name"`) whose PR badges the daemon polls. Polling defaults
185    /// **off** — a repo not in this set issues zero `gh` — so the user enables
186    /// only the handful of repos they are actively working on, rather than the
187    /// daemon polling all 29 open repos and exhausting the GitHub budget. A
188    /// cross-window value like [`show_closed`](Self::show_closed): the daemon
189    /// stamps each repo's state onto the `tree` snapshot (`polling_enabled`) and
190    /// a [`set_polling`](Self::set_polling) flip [`bump`](Self::bump)s the
191    /// change-notify so every window recolors and drops/keeps badges in sync.
192    ///
193    /// Unlike `show_closed` this survives a daemon restart: the adapter seeds it
194    /// from a `0600` file on startup ([`seed_polling`](Self::seed_polling)) and
195    /// persists it on each change — otherwise a restart would silently re-disable
196    /// every repo. Behind its **own** `Mutex`, taken independently of the window
197    /// map's (neither nests) and never held across an `.await`.
198    ///
199    /// Each enable is a **time-boxed lease**, not a permanent flag (#1376): the
200    /// value is the wall-clock instant the lease **expires** ([`poll_ttl`] after
201    /// it was enabled), so an idle repo auto-disables and stops costing `gh`
202    /// without the user remembering to turn it back off. Expired entries are
203    /// reaped on read — the window-TTL precedent — so the icon greys, badges
204    /// drop, and the poller stops within one snapshot tick of expiry.
205    ///
206    /// [`poll_ttl`]: Self::poll_ttl
207    polling_enabled: Mutex<HashMap<String, DateTime<Utc>>>,
208    /// How long a repo's PR-poll lease lasts before it auto-expires (#1376).
209    /// [`DEFAULT_POLL_LEASE`] in production; tests inject a short value via the
210    /// `#[cfg(test)]` `with_poll_ttl` constructor (not linked — it does not exist
211    /// in a non-test doc build).
212    poll_ttl: Duration,
213}
214
215impl WorktreesRegistry {
216    /// Creates the registry with the default liveness TTL. Cheap — no I/O.
217    #[must_use]
218    pub fn new() -> Self {
219        Self {
220            windows: Mutex::new(HashMap::new()),
221            ttl: DEFAULT_TTL,
222            changes: watch::channel(0).0,
223            close_pending: Mutex::new(HashSet::new()),
224            reload_pending: Mutex::new(HashSet::new()),
225            rebasing: Mutex::new(HashSet::new()),
226            pushing: Mutex::new(HashSet::new()),
227            show_closed: AtomicBool::new(true),
228            polling_enabled: Mutex::new(HashMap::new()),
229            poll_ttl: DEFAULT_POLL_LEASE,
230        }
231    }
232
233    /// Creates a registry with a custom PR-poll lease duration, for tests that
234    /// exercise auto-expiry without waiting the full 15 minutes.
235    #[cfg(test)]
236    #[must_use]
237    pub fn with_poll_ttl(poll_ttl: Duration) -> Self {
238        Self {
239            poll_ttl,
240            ..Self::new()
241        }
242    }
243
244    /// A change-notification receiver for the push subscription: it observes a
245    /// new value each time the visible window set changes (see [`changes`] and
246    /// [`bump`]). Created with the current version already marked seen, so the
247    /// first [`watch::Receiver::changed`] resolves on the *next* change — the
248    /// subscriber sends its own initial snapshot up front and then waits for
249    /// deltas (#1267).
250    ///
251    /// [`changes`]: Self::changes
252    /// [`bump`]: Self::bump
253    #[must_use]
254    pub fn subscribe_changes(&self) -> watch::Receiver<u64> {
255        self.changes.subscribe()
256    }
257
258    /// Signals subscribers that the visible state changed. Non-blocking and
259    /// runtime-free; called only *after* the map guard is released so the two
260    /// locks never nest. A send never fails here (the sender is owned by the
261    /// registry, which outlives every receiver, and `send_modify` bumps even
262    /// with no receivers).
263    ///
264    /// Visible outside the registry so the daemon's PR badge poller can signal a
265    /// changed CI verdict (#1337) — the tree snapshot carries more than the window
266    /// set. Callers must bump **only on a real change**: an unconditional bump
267    /// defeats the server's snapshot diff and re-pushes to every window on every
268    /// tick.
269    pub(crate) fn bump(&self) {
270        self.changes.send_modify(|v| *v = v.wrapping_add(1));
271    }
272
273    /// The current change-notify generation — the counter [`bump`](Self::bump)
274    /// increments on every visible-set change. Read (never subscribed) so a
275    /// coalescing consumer — the service's shared tree-snapshot cache (#1303) —
276    /// can tell whether the registry has changed since it last computed and
277    /// rebuild only then. The value itself is immaterial; only whether it
278    /// differs between two reads matters, so `wrapping_add` overflow is benign.
279    #[must_use]
280    pub fn change_generation(&self) -> u64 {
281        *self.changes.borrow()
282    }
283
284    /// Locks the registry, recovering from a poisoned mutex (a panic in a prior
285    /// critical section must not wedge the whole registry).
286    fn lock(&self) -> MutexGuard<'_, HashMap<String, WindowEntry>> {
287        self.windows.lock().unwrap_or_else(PoisonError::into_inner)
288    }
289
290    /// Records (upserts) a window registration. Reaps stale entries first, then
291    /// — only when a genuinely new key would grow the map past [`MAX_WINDOWS`] —
292    /// evicts the longest-silent entry. Infallible: an upsert never evicts, and
293    /// callers validate the `key` before reaching here.
294    pub fn register(&self, req: RegisterRequest) {
295        let now = Utc::now();
296        {
297            let mut windows = self.lock();
298            reap(&mut windows, self.ttl, now);
299            // Upserts never evict; only a genuinely new key can grow the map, and
300            // never past MAX_WINDOWS.
301            if !windows.contains_key(&req.key) && windows.len() >= MAX_WINDOWS {
302                evict_oldest(&mut windows);
303            }
304            windows.insert(
305                req.key.clone(),
306                WindowEntry {
307                    key: req.key,
308                    folders: req.folders,
309                    repo: req.repo,
310                    title: req.title,
311                    pid: req.pid,
312                    last_seen: now,
313                },
314            );
315        }
316        // Always bump: a register is infrequent (once per companion `activate()`,
317        // not per heartbeat) and may add or alter a window's folders/repo. A
318        // no-op re-register with identical data is harmless — the subscriber
319        // diffs the snapshot and suppresses the duplicate frame.
320        self.bump();
321    }
322
323    /// Refreshes a window's liveness. Returns whether the key was known: a
324    /// `false` tells a window that started before the daemon — or survived a
325    /// daemon restart — to re-`register`, since the registry is in-memory and
326    /// has no record of it.
327    pub fn heartbeat(&self, key: &str) -> bool {
328        let now = Utc::now();
329        let (known, reaped) = {
330            let mut windows = self.lock();
331            let reaped = reap(&mut windows, self.ttl, now);
332            let known = match windows.get_mut(key) {
333                Some(entry) => {
334                    entry.last_seen = now;
335                    true
336                }
337                None => false,
338            };
339            (known, reaped)
340        };
341        // A heartbeat is frequent (~every 10 s per window); a pure liveness
342        // refresh does not change the visible set, so bump *only* when this
343        // heartbeat's inline reap actually aged a stale sibling out.
344        if reaped > 0 {
345            self.bump();
346        }
347        known
348    }
349
350    /// Drops a window's registration. Returns whether an entry was present.
351    pub fn unregister(&self, key: &str) -> bool {
352        let now = Utc::now();
353        let (removed, reaped) = {
354            let mut windows = self.lock();
355            let removed = windows.remove(key).is_some();
356            let reaped = reap(&mut windows, self.ttl, now);
357            (removed, reaped)
358        };
359        // The window is gone; any directive for it is fulfilled or moot.
360        // (Keys are per-`activate()` UUIDs, never reused, so a stale directive
361        // would only ever leak a little memory — but clearing keeps it tidy.)
362        // Both takes are outside the map's critical section, so no lock nests.
363        self.take_close_pending(key);
364        self.take_reload_pending(key);
365        if removed || reaped > 0 {
366            self.bump();
367        }
368        removed
369    }
370
371    /// Records a pending "close yourself" directive for `key`, to be surfaced on
372    /// that window's next `heartbeat`. Set by the `close` op when signalling a
373    /// window it can only reply to. Idempotent; infallible.
374    pub fn mark_close_pending(&self, key: &str) {
375        self.close_pending
376            .lock()
377            .unwrap_or_else(PoisonError::into_inner)
378            .insert(key.to_string());
379    }
380
381    /// Takes (returns and clears) `key`'s pending close directive. Called on
382    /// each `heartbeat` so the directive fires exactly once; a `false` means no
383    /// close is pending.
384    pub fn take_close_pending(&self, key: &str) -> bool {
385        self.close_pending
386            .lock()
387            .unwrap_or_else(PoisonError::into_inner)
388            .remove(key)
389    }
390
391    /// Records a pending "reload yourself" directive for `key`, to be surfaced
392    /// on that window's next `heartbeat` (#1417). Set by the `reload` op for
393    /// every target window, which — unlike a close — includes no waiting: the
394    /// caller learns only that the directive was marked. Idempotent; infallible.
395    pub fn mark_reload_pending(&self, key: &str) {
396        self.reload_pending
397            .lock()
398            .unwrap_or_else(PoisonError::into_inner)
399            .insert(key.to_string());
400    }
401
402    /// Takes (returns and clears) `key`'s pending reload directive. Called on
403    /// each `heartbeat` so the directive fires exactly once; a `false` means no
404    /// reload is pending.
405    pub fn take_reload_pending(&self, key: &str) -> bool {
406        self.reload_pending
407            .lock()
408            .unwrap_or_else(PoisonError::into_inner)
409            .remove(key)
410    }
411
412    /// Marks `paths` as being rebased right now (#1415), returning whether the
413    /// set actually changed.
414    ///
415    /// A real change [`bump`](Self::bump)s the change-notify so every subscribed
416    /// window re-pushes a snapshot carrying the spinner — the same cross-window
417    /// sync `set_show_closed` / `set_polling` rely on. Bumping **only** on a real
418    /// change is load-bearing rather than an optimization: an unconditional bump
419    /// defeats the server's snapshot diff and re-pushes to every window on every
420    /// tick.
421    ///
422    /// Callers pass **already-canonicalized** paths, so these match the tree
423    /// snapshot's own keys. Canonicalizing is disk I/O, which belongs in the
424    /// adapter (where `canonical()` lives), not in this engine — the same split
425    /// that keeps the git enrichment out of here.
426    pub fn mark_rebasing(&self, paths: &[PathBuf]) -> bool {
427        self.mutate_in_flight(&self.rebasing, paths, true)
428    }
429
430    /// Clears the rebasing mark on `paths`, returning whether the set changed.
431    /// Called on **every** exit from a phase-2 execute, so a panicking or failing
432    /// rebase can never leave a permanent spinner on a row.
433    pub fn clear_rebasing(&self, paths: &[PathBuf]) -> bool {
434        self.mutate_in_flight(&self.rebasing, paths, false)
435    }
436
437    /// Marks `paths` as being pushed right now (#1443), returning whether the set
438    /// actually changed. The [`mark_rebasing`](Self::mark_rebasing) twin, with the
439    /// same canonicalized-paths-in and bump-only-on-a-real-change contract.
440    pub fn mark_pushing(&self, paths: &[PathBuf]) -> bool {
441        self.mutate_in_flight(&self.pushing, paths, true)
442    }
443
444    /// Clears the pushing mark on `paths`, returning whether the set changed.
445    /// Called on **every** exit from a phase-2 execute — and it is the *only* thing
446    /// that clears this cue, since a push leaves no on-disk state a later snapshot
447    /// could correct a stale mark from.
448    pub fn clear_pushing(&self, paths: &[PathBuf]) -> bool {
449        self.mutate_in_flight(&self.pushing, paths, false)
450    }
451
452    /// The shared body of the in-flight-set mutators: mutate under that set's own
453    /// lock, drop the guard, then bump if anything moved (never bump while holding
454    /// a lock, per the engine's `std::Mutex`-never-across-`.await` discipline).
455    ///
456    /// Bumping **only** on a real change is load-bearing rather than an
457    /// optimization: an unconditional bump defeats the server's snapshot diff and
458    /// re-pushes to every window on every tick.
459    fn mutate_in_flight(
460        &self,
461        set: &Mutex<HashSet<PathBuf>>,
462        paths: &[PathBuf],
463        insert: bool,
464    ) -> bool {
465        let changed = {
466            let mut set = set.lock().unwrap_or_else(PoisonError::into_inner);
467            paths.iter().fold(false, |changed, path| {
468                let moved = if insert {
469                    set.insert(path.clone())
470                } else {
471                    set.remove(path)
472                };
473                changed || moved
474            })
475        };
476        if changed {
477            self.bump();
478        }
479        changed
480    }
481
482    /// The worktree paths currently being rebased, canonicalized. Read into each
483    /// `tree`/`subscribe` snapshot; cheap (a set clone of at most a batch's worth
484    /// of paths) and never held across an `.await`.
485    #[must_use]
486    pub fn rebasing_paths(&self) -> HashSet<PathBuf> {
487        Self::snapshot_paths(&self.rebasing)
488    }
489
490    /// The worktree paths currently being pushed, canonicalized (#1443). The
491    /// [`rebasing_paths`](Self::rebasing_paths) twin, read into the same snapshot.
492    #[must_use]
493    pub fn pushing_paths(&self) -> HashSet<PathBuf> {
494        Self::snapshot_paths(&self.pushing)
495    }
496
497    /// A clone of one in-flight set, for folding into a tree snapshot.
498    fn snapshot_paths(set: &Mutex<HashSet<PathBuf>>) -> HashSet<PathBuf> {
499        set.lock().unwrap_or_else(PoisonError::into_inner).clone()
500    }
501
502    /// The current show/hide-closed toggle: whether the tree view shows
503    /// worktrees with no open window (#1301). Read into every `tree`/`subscribe`
504    /// snapshot so every window renders the same, live-synced state.
505    #[must_use]
506    pub fn show_closed(&self) -> bool {
507        self.show_closed.load(Ordering::Relaxed)
508    }
509
510    /// Sets the show/hide-closed toggle, returning whether the value actually
511    /// changed. A real change [`bump`](Self::bump)s the change-notify so every
512    /// subscriber re-pushes a snapshot carrying the new value — the reliable
513    /// cross-window sync `context.globalState` could not provide. A no-op set
514    /// (same value) neither bumps nor wakes anyone.
515    pub fn set_show_closed(&self, show_closed: bool) -> bool {
516        let changed = self.show_closed.swap(show_closed, Ordering::Relaxed) != show_closed;
517        if changed {
518            self.bump();
519        }
520        changed
521    }
522
523    /// Locks the per-repo PR-poll lease map (`"owner/name"` → lease-expiry
524    /// instant), recovering from a poisoned mutex (a panic in a prior critical
525    /// section must not wedge polling for the whole daemon).
526    fn polling_lock(&self) -> MutexGuard<'_, HashMap<String, DateTime<Utc>>> {
527        self.polling_enabled
528            .lock()
529            .unwrap_or_else(PoisonError::into_inner)
530    }
531
532    /// Whether PR polling is currently leased for the GitHub repo `owner/name`
533    /// (#1376) — the entry exists **and** its lease has not expired. Defaults
534    /// **false** (a never-toggled repo does not poll), so only repos the user has
535    /// explicitly enabled, within the last [`poll_ttl`](Self::poll_ttl), poll.
536    #[must_use]
537    pub fn is_polling_enabled(&self, owner: &str, name: &str) -> bool {
538        let now = Utc::now();
539        self.polling_lock()
540            .get(&polling_key(owner, name))
541            .is_some_and(|expiry| *expiry > now)
542    }
543
544    /// The repos with a **live** (unexpired) lease, as a set of `"owner/name"`
545    /// keys — what stamps `polling_enabled` onto the `tree` snapshot. Reaps
546    /// expired leases first (the window-TTL reap-on-read precedent), so an idle
547    /// repo drops out on the next snapshot build without a background timer.
548    /// Cloned out so the lock is never held across the (blocking-thread) tree
549    /// build that reads it.
550    #[must_use]
551    pub fn enabled_polling_repos(&self) -> HashSet<String> {
552        let now = Utc::now();
553        let mut map = self.polling_lock();
554        map.retain(|_, expiry| *expiry > now);
555        map.keys().cloned().collect()
556    }
557
558    /// The live leases as `(repo, expiry)` pairs sorted by repo, for
559    /// deterministic persistence to the `0600` prefs file (#1376) — the expiry is
560    /// stored so a daemon restart within the lease window keeps the *remaining*
561    /// time rather than resetting the clock. Reaps expired leases first, so a
562    /// stale entry is never written back.
563    #[must_use]
564    pub fn polling_snapshot(&self) -> Vec<(String, DateTime<Utc>)> {
565        let now = Utc::now();
566        let mut map = self.polling_lock();
567        map.retain(|_, expiry| *expiry > now);
568        let mut entries: Vec<(String, DateTime<Utc>)> =
569            map.iter().map(|(k, v)| (k.clone(), *v)).collect();
570        entries.sort_by(|a, b| a.0.cmp(&b.0));
571        entries
572    }
573
574    /// Enables (leases for [`poll_ttl`](Self::poll_ttl)) or disables PR polling
575    /// for `owner/name`, returning whether the stored map changed — which the
576    /// adapter uses to decide whether to persist. Enabling an already-leased repo
577    /// **refreshes** the lease (a new expiry), which is a change worth persisting.
578    ///
579    /// [`bump`](Self::bump)s the change-notify only when the repo's **effective**
580    /// enabled state flips (off→on or on→off), so every subscribed window
581    /// re-pushes a snapshot that recolours the icon and drops/keeps badges — the
582    /// [`set_show_closed`](Self::set_show_closed) precedent. A lease *refresh*
583    /// (already on, still on) changes the expiry but not the visible state, so it
584    /// persists without waking anyone.
585    pub fn set_polling(&self, owner: &str, name: &str, enabled: bool) -> bool {
586        let key = polling_key(owner, name);
587        let now = Utc::now();
588        let (changed, flipped) = {
589            let mut map = self.polling_lock();
590            let was_enabled = map.get(&key).is_some_and(|expiry| *expiry > now);
591            if enabled {
592                let expiry = now
593                    + ChronoDuration::from_std(self.poll_ttl).unwrap_or_else(|_| {
594                        ChronoDuration::seconds(DEFAULT_POLL_LEASE.as_secs() as i64)
595                    });
596                let changed = map.insert(key, expiry) != Some(expiry);
597                (changed, !was_enabled)
598            } else {
599                let removed = map.remove(&key).is_some();
600                (removed, was_enabled)
601            }
602        };
603        if flipped {
604            self.bump();
605        }
606        changed
607    }
608
609    /// Replaces the lease map wholesale from the persisted `0600` prefs file
610    /// (#1376), dropping any lease that already expired while the daemon was down.
611    /// Does **not** [`bump`](Self::bump): it runs before any window subscribes, so
612    /// there is no one to notify, and each window's first snapshot already
613    /// reflects the seeded leases.
614    pub fn seed_polling(&self, leases: impl IntoIterator<Item = (String, DateTime<Utc>)>) {
615        let now = Utc::now();
616        *self.polling_lock() = leases
617            .into_iter()
618            .filter(|(_, expiry)| *expiry > now)
619            .collect();
620    }
621
622    /// Test-only: forces `owner/name`'s lease to `expiry`, so a test can simulate
623    /// an elapsed lease deterministically without sleeping for [`poll_ttl`].
624    #[cfg(test)]
625    pub fn set_polling_expiry(&self, owner: &str, name: &str, expiry: DateTime<Utc>) {
626        self.polling_lock().insert(polling_key(owner, name), expiry);
627    }
628
629    /// Reaps stale entries, then returns the live set sorted for deterministic
630    /// output. Holds the lock only for pure-CPU work.
631    ///
632    /// Like the other reads ([`open_folders`](Self::open_folders),
633    /// [`first_folder`](Self::first_folder)) this reaps but never
634    /// [`bump`](Self::bump)s: the only observer of a read-path reap is the push
635    /// subscription's own re-snapshot (or `status`/`menu`), and the
636    /// subscription's periodic tick already re-samples read-only staleness — so
637    /// bumping here would only make the subscription wake itself (#1267).
638    pub fn list(&self) -> Vec<WindowEntry> {
639        let now = Utc::now();
640        let mut windows = self.lock();
641        reap(&mut windows, self.ttl, now);
642        sorted_entries(&windows)
643    }
644
645    /// The first workspace folder of a still-live window, if it has one. Used by
646    /// the tray "focus" action to resolve a key to a folder to open. Does not
647    /// reap — a menu action races the reaper either way, and the caller handles
648    /// a `None` (the window may have closed).
649    pub fn first_folder(&self, key: &str) -> Option<PathBuf> {
650        let windows = self.lock();
651        windows.get(key).and_then(|e| e.folders.first().cloned())
652    }
653
654    /// Snapshots the distinct workspace folders across all live windows — the
655    /// seed set the adapter resolves to repositories (each folder → its git
656    /// common dir → repo root) to enumerate every worktree per repo (#1265).
657    ///
658    /// Reaps stale entries first, then returns the folders sorted and
659    /// deduplicated. Like [`list`](Self::list) it is pure CPU under the lock:
660    /// the git resolution the "distinct repos" derivation needs is disk I/O and
661    /// stays in the adapter, off the registry lock, honouring the
662    /// `Mutex`-never-across-`.await` invariant.
663    pub fn open_folders(&self) -> Vec<PathBuf> {
664        let now = Utc::now();
665        let mut windows = self.lock();
666        reap(&mut windows, self.ttl, now);
667        let mut folders: Vec<PathBuf> = windows
668            .values()
669            .flat_map(|e| e.folders.iter().cloned())
670            .collect();
671        folders.sort();
672        folders.dedup();
673        folders
674    }
675}
676
677impl Default for WorktreesRegistry {
678    fn default() -> Self {
679        Self::new()
680    }
681}
682
683/// Removes entries last seen longer than `ttl` ago, returning how many were
684/// dropped. Pure CPU; the caller holds the registry lock but never `.await`s
685/// while holding it. The count lets a *mutation* path
686/// ([`register`](WorktreesRegistry::register) et al.) decide whether to
687/// [`bump`](WorktreesRegistry::bump) the change-notify; read paths ignore it (see
688/// [`list`](WorktreesRegistry::list)).
689fn reap(windows: &mut HashMap<String, WindowEntry>, ttl: Duration, now: DateTime<Utc>) -> usize {
690    let max_age = ttl.as_secs() as i64;
691    let before = windows.len();
692    windows.retain(|_, e| (now - e.last_seen).num_seconds() <= max_age);
693    before - windows.len()
694}
695
696/// Removes the entry with the oldest `last_seen` (ties broken by lowest key
697/// for determinism). Called when a `register` of a new key would grow the
698/// registry past [`MAX_WINDOWS`]. Pure CPU under the registry lock, like
699/// [`reap`].
700fn evict_oldest(windows: &mut HashMap<String, WindowEntry>) {
701    let oldest = windows
702        .values()
703        .min_by(|a, b| {
704            a.last_seen
705                .cmp(&b.last_seen)
706                .then_with(|| a.key.cmp(&b.key))
707        })
708        .map(|e| e.key.clone());
709    if let Some(key) = oldest {
710        windows.remove(&key);
711    }
712}
713
714/// The canonical key for a GitHub repo in the per-repo PR-poll set: `owner/name`
715/// (#1376). One place so the registry's set, the snapshot stamp, and the poller
716/// filter all agree on the exact string.
717fn polling_key(owner: &str, name: &str) -> String {
718    format!("{owner}/{name}")
719}
720
721/// Snapshots the registry into a stably-ordered vector (by repo, then key) so
722/// `list`/`status`/`menu` output is deterministic despite `HashMap` ordering.
723fn sorted_entries(windows: &HashMap<String, WindowEntry>) -> Vec<WindowEntry> {
724    let mut entries: Vec<WindowEntry> = windows.values().cloned().collect();
725    entries.sort_by(|a, b| a.repo.cmp(&b.repo).then_with(|| a.key.cmp(&b.key)));
726    entries
727}
728
729#[cfg(test)]
730#[allow(clippy::unwrap_used, clippy::expect_used)]
731mod tests {
732    use super::*;
733
734    fn register_request(key: &str, repo: Option<&str>, folder: &str) -> RegisterRequest {
735        RegisterRequest {
736            key: key.to_string(),
737            folders: vec![PathBuf::from(folder)],
738            repo: repo.map(str::to_string),
739            title: Some(format!("{key}-title")),
740            pid: Some(1234),
741        }
742    }
743
744    #[test]
745    fn list_is_empty_initially() {
746        let reg = WorktreesRegistry::new();
747        assert!(reg.list().is_empty());
748    }
749
750    #[test]
751    fn register_then_list_round_trips() {
752        let reg = WorktreesRegistry::new();
753        reg.register(register_request("w1", Some("repo-a"), "/tmp/a"));
754        let windows = reg.list();
755        assert_eq!(windows.len(), 1);
756        assert_eq!(windows[0].key, "w1");
757        assert_eq!(windows[0].repo.as_deref(), Some("repo-a"));
758    }
759
760    #[test]
761    fn register_is_idempotent_upsert() {
762        let reg = WorktreesRegistry::new();
763        reg.register(register_request("w1", Some("repo-a"), "/tmp/a"));
764        // Re-registering the same key updates rather than duplicates.
765        reg.register(register_request("w1", Some("repo-b"), "/tmp/b"));
766        let windows = reg.list();
767        assert_eq!(windows.len(), 1);
768        assert_eq!(windows[0].repo.as_deref(), Some("repo-b"));
769    }
770
771    #[test]
772    fn heartbeat_reports_known_and_unknown() {
773        let reg = WorktreesRegistry::new();
774        // Unknown before registration: the window must re-register.
775        assert!(!reg.heartbeat("w1"));
776        reg.register(register_request("w1", None, "/tmp/a"));
777        assert!(reg.heartbeat("w1"));
778    }
779
780    #[test]
781    fn unregister_removes() {
782        let reg = WorktreesRegistry::new();
783        reg.register(register_request("w1", None, "/tmp/a"));
784        assert!(reg.unregister("w1"));
785        // Removing again is a no-op.
786        assert!(!reg.unregister("w1"));
787    }
788
789    #[test]
790    fn first_folder_returns_first_folder_or_none() {
791        let reg = WorktreesRegistry::new();
792        // No such key.
793        assert!(reg.first_folder("missing").is_none());
794        reg.register(register_request("w1", None, "/tmp/a"));
795        assert_eq!(reg.first_folder("w1"), Some(PathBuf::from("/tmp/a")));
796        // A folderless window resolves to None rather than a folder.
797        reg.register(RegisterRequest {
798            key: "w2".to_string(),
799            folders: vec![],
800            repo: None,
801            title: None,
802            pid: None,
803        });
804        assert!(reg.first_folder("w2").is_none());
805    }
806
807    #[test]
808    fn open_folders_dedups_and_sorts_across_windows() {
809        let reg = WorktreesRegistry::new();
810        assert!(reg.open_folders().is_empty());
811        // Two windows sharing a folder, plus a multi-folder window: the shared
812        // path collapses and the result is sorted.
813        reg.register(register_request("w1", Some("repo-a"), "/tmp/shared"));
814        reg.register(RegisterRequest {
815            key: "w2".to_string(),
816            folders: vec![PathBuf::from("/tmp/shared"), PathBuf::from("/tmp/b")],
817            repo: Some("repo-a".to_string()),
818            title: None,
819            pid: None,
820        });
821        reg.register(register_request("w3", Some("repo-b"), "/tmp/a"));
822        assert_eq!(
823            reg.open_folders(),
824            vec![
825                PathBuf::from("/tmp/a"),
826                PathBuf::from("/tmp/b"),
827                PathBuf::from("/tmp/shared"),
828            ]
829        );
830    }
831
832    #[test]
833    fn open_folders_reaps_stale_windows() {
834        let reg = WorktreesRegistry::new();
835        {
836            let mut windows = reg.lock();
837            windows.insert(
838                "fresh".to_string(),
839                WindowEntry {
840                    key: "fresh".to_string(),
841                    folders: vec![PathBuf::from("/tmp/fresh")],
842                    repo: None,
843                    title: None,
844                    pid: None,
845                    last_seen: Utc::now(),
846                },
847            );
848            windows.insert(
849                "stale".to_string(),
850                WindowEntry {
851                    key: "stale".to_string(),
852                    folders: vec![PathBuf::from("/tmp/stale")],
853                    repo: None,
854                    title: None,
855                    pid: None,
856                    last_seen: Utc::now() - chrono::Duration::seconds(120),
857                },
858            );
859        }
860        // The stale window's folder is reaped out of the snapshot.
861        assert_eq!(reg.open_folders(), vec![PathBuf::from("/tmp/fresh")]);
862    }
863
864    #[test]
865    fn reap_evicts_only_stale_entries() {
866        let now = Utc::now();
867        let mut windows = HashMap::new();
868        windows.insert(
869            "fresh".to_string(),
870            WindowEntry {
871                key: "fresh".to_string(),
872                folders: vec![],
873                repo: None,
874                title: None,
875                pid: None,
876                last_seen: now - chrono::Duration::seconds(5),
877            },
878        );
879        windows.insert(
880            "stale".to_string(),
881            WindowEntry {
882                key: "stale".to_string(),
883                folders: vec![],
884                repo: None,
885                title: None,
886                pid: None,
887                last_seen: now - chrono::Duration::seconds(120),
888            },
889        );
890        reap(&mut windows, DEFAULT_TTL, now);
891        assert!(windows.contains_key("fresh"));
892        assert!(!windows.contains_key("stale"));
893    }
894
895    /// A minimal entry for cap/eviction tests; only `key` and `last_seen`
896    /// participate in eviction order.
897    fn entry_at(key: &str, last_seen: DateTime<Utc>) -> WindowEntry {
898        WindowEntry {
899            key: key.to_string(),
900            folders: vec![],
901            repo: None,
902            title: None,
903            pid: None,
904            last_seen,
905        }
906    }
907
908    #[test]
909    fn evict_oldest_removes_oldest_with_key_tiebreak() {
910        let now = Utc::now();
911        let mut windows = HashMap::new();
912        windows.insert("young".to_string(), entry_at("young", now));
913        windows.insert(
914            "old-b".to_string(),
915            entry_at("old-b", now - chrono::Duration::seconds(10)),
916        );
917        windows.insert(
918            "old-a".to_string(),
919            entry_at("old-a", now - chrono::Duration::seconds(10)),
920        );
921        // Oldest `last_seen` is shared by two entries; the lowest key loses.
922        evict_oldest(&mut windows);
923        assert!(!windows.contains_key("old-a"));
924        assert!(windows.contains_key("old-b"));
925        assert!(windows.contains_key("young"));
926        // Empty map is a no-op rather than a panic.
927        let mut empty: HashMap<String, WindowEntry> = HashMap::new();
928        evict_oldest(&mut empty);
929        assert!(empty.is_empty());
930    }
931
932    #[test]
933    fn register_at_cap_evicts_only_the_oldest() {
934        let reg = WorktreesRegistry::new();
935        // Seed a full registry directly (registering 256 times would work too,
936        // but sub-second timestamps may tie; explicit timestamps make the
937        // highest-numbered key unambiguously the oldest).
938        {
939            let mut windows = reg.lock();
940            let base = Utc::now();
941            for i in 0..MAX_WINDOWS {
942                let key = format!("w{i:03}");
943                windows.insert(
944                    key.clone(),
945                    entry_at(&key, base - chrono::Duration::milliseconds(i as i64)),
946                );
947            }
948        }
949        // A new key at the cap displaces exactly the longest-silent entry.
950        reg.register(register_request("fresh", None, "/tmp/f"));
951        let windows = reg.lock();
952        assert_eq!(windows.len(), MAX_WINDOWS);
953        assert!(windows.contains_key("fresh"));
954        assert!(!windows.contains_key(&format!("w{:03}", MAX_WINDOWS - 1)));
955        assert!(windows.contains_key("w000"));
956    }
957
958    #[test]
959    fn register_upsert_at_cap_does_not_evict() {
960        let reg = WorktreesRegistry::new();
961        {
962            let mut windows = reg.lock();
963            let base = Utc::now();
964            for i in 0..MAX_WINDOWS {
965                let key = format!("w{i:03}");
966                windows.insert(
967                    key.clone(),
968                    entry_at(&key, base - chrono::Duration::milliseconds(i as i64)),
969                );
970            }
971        }
972        // Re-registering an existing key is an upsert: nothing is displaced,
973        // not even the oldest entry.
974        let oldest = format!("w{:03}", MAX_WINDOWS - 1);
975        reg.register(register_request(&oldest, Some("r"), "/tmp/a"));
976        let windows = reg.lock();
977        assert_eq!(windows.len(), MAX_WINDOWS);
978        assert!(windows.contains_key(&oldest));
979        assert!(windows.contains_key("w000"));
980    }
981
982    #[test]
983    fn sorted_entries_orders_by_repo_then_key() {
984        let now = Utc::now();
985        let mut windows = HashMap::new();
986        for (key, repo) in [("z", "repo-a"), ("a", "repo-b"), ("m", "repo-a")] {
987            windows.insert(
988                key.to_string(),
989                WindowEntry {
990                    key: key.to_string(),
991                    folders: vec![],
992                    repo: Some(repo.to_string()),
993                    title: None,
994                    pid: None,
995                    last_seen: now,
996                },
997            );
998        }
999        let entries = sorted_entries(&windows);
1000        let ordered: Vec<(&str, &str)> = entries
1001            .iter()
1002            .map(|e| (e.key.as_str(), e.repo.as_deref().unwrap()))
1003            .collect();
1004        assert_eq!(
1005            ordered,
1006            vec![("m", "repo-a"), ("z", "repo-a"), ("a", "repo-b")]
1007        );
1008    }
1009
1010    #[test]
1011    fn default_constructs_an_empty_registry() {
1012        let reg = WorktreesRegistry::default();
1013        assert!(reg.lock().is_empty());
1014    }
1015
1016    // --- Change-notify for the push subscription (#1267) --------------------
1017
1018    #[test]
1019    fn subscribe_changes_starts_seen_and_register_bumps() {
1020        let reg = WorktreesRegistry::new();
1021        let mut rx = reg.subscribe_changes();
1022        // A fresh receiver has the current version already marked seen.
1023        assert!(!rx.has_changed().unwrap());
1024        // A register changes the visible set → the receiver observes a new value.
1025        reg.register(register_request("w1", None, "/tmp/a"));
1026        assert!(rx.has_changed().unwrap(), "register should bump");
1027        // Marking it seen clears the pending change.
1028        rx.borrow_and_update();
1029        assert!(!rx.has_changed().unwrap());
1030    }
1031
1032    #[test]
1033    fn unregister_bumps_only_when_it_removes() {
1034        let reg = WorktreesRegistry::new();
1035        reg.register(register_request("w1", None, "/tmp/a"));
1036        // Subscribe *after* the register so its bump is already seen.
1037        let rx = reg.subscribe_changes();
1038        // Removing a missing key changes nothing (and reaps nothing) → no bump.
1039        assert!(!reg.unregister("ghost"));
1040        assert!(
1041            !rx.has_changed().unwrap(),
1042            "a no-op unregister must not bump"
1043        );
1044        // Removing a present key bumps.
1045        assert!(reg.unregister("w1"));
1046        assert!(
1047            rx.has_changed().unwrap(),
1048            "a removing unregister should bump"
1049        );
1050    }
1051
1052    #[test]
1053    fn change_generation_advances_only_on_a_visible_change() {
1054        let reg = WorktreesRegistry::new();
1055        let g0 = reg.change_generation();
1056        // A no-op (heartbeat of an unknown key) leaves the generation untouched.
1057        assert!(!reg.heartbeat("ghost"));
1058        assert_eq!(
1059            reg.change_generation(),
1060            g0,
1061            "a no-op must not advance the generation"
1062        );
1063        // A register changes the visible set → the generation advances, so a
1064        // cache keyed on it rebuilds.
1065        reg.register(register_request("w1", None, "/tmp/a"));
1066        assert_ne!(
1067            reg.change_generation(),
1068            g0,
1069            "a register should advance the generation"
1070        );
1071    }
1072
1073    #[test]
1074    fn heartbeat_bumps_only_when_it_reaps() {
1075        let reg = WorktreesRegistry::new();
1076        reg.register(register_request("w1", None, "/tmp/a"));
1077        let rx = reg.subscribe_changes();
1078        // A plain heartbeat refreshes liveness but changes no visible state.
1079        assert!(reg.heartbeat("w1"));
1080        assert!(!rx.has_changed().unwrap(), "a pure heartbeat must not bump");
1081        // Seed a stale sibling directly; a heartbeat that reaps it *does* bump.
1082        {
1083            let mut windows = reg.lock();
1084            windows.insert(
1085                "stale".to_string(),
1086                entry_at("stale", Utc::now() - chrono::Duration::seconds(120)),
1087            );
1088        }
1089        assert!(reg.heartbeat("w1"));
1090        assert!(
1091            rx.has_changed().unwrap(),
1092            "a heartbeat that reaps a stale sibling should bump"
1093        );
1094    }
1095
1096    // --- Close-pending directive (#1277) -----------------------------------
1097
1098    #[test]
1099    fn close_pending_is_taken_once_then_cleared() {
1100        let reg = WorktreesRegistry::new();
1101        // No directive by default.
1102        assert!(!reg.take_close_pending("w1"));
1103        // Marked → the first take observes it, the next does not (fires once).
1104        reg.mark_close_pending("w1");
1105        assert!(reg.take_close_pending("w1"));
1106        assert!(!reg.take_close_pending("w1"));
1107    }
1108
1109    #[test]
1110    fn unregister_clears_a_pending_close_directive() {
1111        let reg = WorktreesRegistry::new();
1112        reg.register(register_request("w1", None, "/tmp/a"));
1113        reg.mark_close_pending("w1");
1114        // Unregistering the window drops any pending directive with it.
1115        assert!(reg.unregister("w1"));
1116        assert!(!reg.take_close_pending("w1"));
1117    }
1118
1119    // --- Reload-pending directive (#1417) ----------------------------------
1120
1121    #[test]
1122    fn reload_pending_is_taken_once_then_cleared() {
1123        let reg = WorktreesRegistry::new();
1124        // No directive by default.
1125        assert!(!reg.take_reload_pending("w1"));
1126        // Marked → the first take observes it, the next does not (fires once).
1127        reg.mark_reload_pending("w1");
1128        assert!(reg.take_reload_pending("w1"));
1129        assert!(!reg.take_reload_pending("w1"));
1130    }
1131
1132    #[test]
1133    fn unregister_clears_a_pending_reload_directive() {
1134        let reg = WorktreesRegistry::new();
1135        reg.register(register_request("w1", None, "/tmp/a"));
1136        reg.mark_reload_pending("w1");
1137        // Unregistering the window drops any pending directive with it.
1138        assert!(reg.unregister("w1"));
1139        assert!(!reg.take_reload_pending("w1"));
1140    }
1141
1142    #[test]
1143    fn close_and_reload_directives_are_independent() {
1144        let reg = WorktreesRegistry::new();
1145        // Separate sets: marking one must not set or consume the other, so the
1146        // heartbeat can surface both fields and the companion pick a winner.
1147        reg.mark_reload_pending("w1");
1148        assert!(!reg.take_close_pending("w1"));
1149        reg.mark_close_pending("w1");
1150        assert!(reg.take_close_pending("w1"));
1151        assert!(reg.take_reload_pending("w1"));
1152        // Each key is tracked on its own.
1153        reg.mark_reload_pending("w1");
1154        assert!(!reg.take_reload_pending("w2"));
1155        assert!(reg.take_reload_pending("w1"));
1156    }
1157
1158    #[test]
1159    fn marking_a_reload_does_not_bump() {
1160        let reg = WorktreesRegistry::new();
1161        reg.register(register_request("w1", None, "/tmp/a"));
1162        let rx = reg.subscribe_changes();
1163        // A directive is not consumer-visible state — it never reaches a tree
1164        // snapshot — so marking one must not push a redundant frame to every
1165        // subscriber. Same rule as the close directive.
1166        reg.mark_reload_pending("w1");
1167        assert!(!rx.has_changed().unwrap(), "marking a reload must not bump");
1168        assert!(reg.take_reload_pending("w1"));
1169        assert!(!rx.has_changed().unwrap(), "taking a reload must not bump");
1170    }
1171
1172    // --- Rebasing set (#1415) ----------------------------------------------
1173
1174    #[test]
1175    fn rebasing_marks_and_clears_the_named_paths() {
1176        let reg = WorktreesRegistry::new();
1177        let a = PathBuf::from("/tmp/a");
1178        let b = PathBuf::from("/tmp/b");
1179        assert!(
1180            reg.rebasing_paths().is_empty(),
1181            "nothing rebases by default"
1182        );
1183
1184        assert!(reg.mark_rebasing(&[a.clone(), b.clone()]));
1185        assert_eq!(reg.rebasing_paths(), [a.clone(), b.clone()].into());
1186
1187        // Clearing one leaves the other — a batch reports per worktree.
1188        assert!(reg.clear_rebasing(std::slice::from_ref(&a)));
1189        assert_eq!(reg.rebasing_paths(), [b.clone()].into());
1190        assert!(reg.clear_rebasing(&[b]));
1191        assert!(reg.rebasing_paths().is_empty());
1192    }
1193
1194    #[test]
1195    fn rebasing_bumps_only_on_a_real_change() {
1196        // Load-bearing: an unconditional bump would defeat the server's snapshot
1197        // diff and re-push a `tree` frame to every window on every tick.
1198        let reg = WorktreesRegistry::new();
1199        let path = PathBuf::from("/tmp/a");
1200
1201        let mut rx = reg.subscribe_changes();
1202        assert!(reg.mark_rebasing(std::slice::from_ref(&path)));
1203        assert!(rx.has_changed().unwrap(), "the first mark bumps");
1204        let _ = rx.borrow_and_update();
1205
1206        assert!(
1207            !reg.mark_rebasing(std::slice::from_ref(&path)),
1208            "re-marking an already-rebasing path is not a change"
1209        );
1210        assert!(!rx.has_changed().unwrap(), "a no-op mark must not bump");
1211
1212        assert!(
1213            !reg.clear_rebasing(&[PathBuf::from("/tmp/never-marked")]),
1214            "clearing an unmarked path is not a change"
1215        );
1216        assert!(!rx.has_changed().unwrap(), "a no-op clear must not bump");
1217
1218        assert!(reg.clear_rebasing(&[path]));
1219        assert!(rx.has_changed().unwrap(), "a real clear bumps");
1220    }
1221
1222    // --- Pushing set (#1443) -----------------------------------------------
1223
1224    #[test]
1225    fn pushing_marks_and_clears_the_named_paths() {
1226        let reg = WorktreesRegistry::new();
1227        let a = PathBuf::from("/tmp/a");
1228        let b = PathBuf::from("/tmp/b");
1229        assert!(reg.pushing_paths().is_empty(), "nothing pushes by default");
1230
1231        assert!(reg.mark_pushing(&[a.clone(), b.clone()]));
1232        assert_eq!(reg.pushing_paths(), [a.clone(), b.clone()].into());
1233
1234        assert!(reg.clear_pushing(std::slice::from_ref(&a)));
1235        assert_eq!(reg.pushing_paths(), [b.clone()].into());
1236        assert!(reg.clear_pushing(&[b]));
1237        assert!(reg.pushing_paths().is_empty());
1238    }
1239
1240    #[test]
1241    fn pushing_bumps_only_on_a_real_change() {
1242        let reg = WorktreesRegistry::new();
1243        let path = PathBuf::from("/tmp/a");
1244
1245        let mut rx = reg.subscribe_changes();
1246        assert!(reg.mark_pushing(std::slice::from_ref(&path)));
1247        assert!(rx.has_changed().unwrap(), "the first mark bumps");
1248        let _ = rx.borrow_and_update();
1249
1250        assert!(
1251            !reg.mark_pushing(std::slice::from_ref(&path)),
1252            "re-marking an already-pushing path is not a change"
1253        );
1254        assert!(!rx.has_changed().unwrap(), "a no-op mark must not bump");
1255
1256        assert!(reg.clear_pushing(&[path]));
1257        assert!(rx.has_changed().unwrap(), "a real clear bumps");
1258    }
1259
1260    #[test]
1261    fn pushing_and_rebasing_are_independent_sets() {
1262        // The two cues are orthogonal — the same worktree can be marked by one op
1263        // without the other's cue appearing, and clearing one must not clear the
1264        // other.
1265        let reg = WorktreesRegistry::new();
1266        let path = PathBuf::from("/tmp/a");
1267
1268        assert!(reg.mark_rebasing(std::slice::from_ref(&path)));
1269        assert!(
1270            reg.pushing_paths().is_empty(),
1271            "a rebase mark must not show as a push"
1272        );
1273
1274        assert!(reg.mark_pushing(std::slice::from_ref(&path)));
1275        assert!(reg.clear_rebasing(std::slice::from_ref(&path)));
1276        assert_eq!(
1277            reg.pushing_paths(),
1278            [path].into(),
1279            "clearing the rebase mark must leave the push mark alone"
1280        );
1281    }
1282
1283    // --- Show/hide-closed toggle (#1301) -----------------------------------
1284
1285    #[test]
1286    fn show_closed_defaults_to_true() {
1287        let reg = WorktreesRegistry::new();
1288        assert!(reg.show_closed(), "default is show all");
1289    }
1290
1291    #[test]
1292    fn set_show_closed_reports_change_and_is_idempotent() {
1293        let reg = WorktreesRegistry::new();
1294        // Flipping to a new value reports a change and is observable.
1295        assert!(reg.set_show_closed(false));
1296        assert!(!reg.show_closed());
1297        // Setting the same value again is a no-op (no change reported).
1298        assert!(!reg.set_show_closed(false));
1299        // Flipping back reports a change again.
1300        assert!(reg.set_show_closed(true));
1301        assert!(reg.show_closed());
1302    }
1303
1304    #[test]
1305    fn set_show_closed_bumps_only_on_change() {
1306        let reg = WorktreesRegistry::new();
1307        let rx = reg.subscribe_changes();
1308        // A no-op set (already the default) does not wake subscribers.
1309        assert!(!reg.set_show_closed(true));
1310        assert!(
1311            !rx.has_changed().unwrap(),
1312            "a no-op toggle must not bump the change-notify"
1313        );
1314        // A real flip bumps so subscribers re-push a snapshot with the new value.
1315        assert!(reg.set_show_closed(false));
1316        assert!(
1317            rx.has_changed().unwrap(),
1318            "flipping the toggle should bump the change-notify"
1319        );
1320    }
1321
1322    #[test]
1323    fn polling_defaults_off_for_an_untoggled_repo() {
1324        let reg = WorktreesRegistry::new();
1325        // #1376: the whole point — a repo the user has never enabled is not polled.
1326        assert!(!reg.is_polling_enabled("rust-works", "omni-dev"));
1327        assert!(reg.enabled_polling_repos().is_empty());
1328        assert!(reg.polling_snapshot().is_empty());
1329    }
1330
1331    #[test]
1332    fn set_polling_leases_and_disables() {
1333        let reg = WorktreesRegistry::new();
1334        // Enabling a fresh repo reports a change and leases it live.
1335        assert!(reg.set_polling("rust-works", "omni-dev", true));
1336        assert!(reg.is_polling_enabled("rust-works", "omni-dev"));
1337        // Re-enabling refreshes the lease — the map changes (new expiry).
1338        assert!(reg.set_polling("rust-works", "omni-dev", true));
1339        assert!(reg.is_polling_enabled("rust-works", "omni-dev"));
1340        // Disabling reports a change and clears it.
1341        assert!(reg.set_polling("rust-works", "omni-dev", false));
1342        assert!(!reg.is_polling_enabled("rust-works", "omni-dev"));
1343        // Disabling an already-disabled repo is a no-op.
1344        assert!(!reg.set_polling("rust-works", "omni-dev", false));
1345    }
1346
1347    #[test]
1348    fn polling_lease_auto_expires() {
1349        // The 15-minute lease (#1376): an enabled repo drops out once its lease
1350        // elapses, reaped on the next read — no background timer.
1351        let reg = WorktreesRegistry::new();
1352        reg.set_polling("rust-works", "omni-dev", true);
1353        assert!(reg.is_polling_enabled("rust-works", "omni-dev"));
1354        // Force the lease into the past (as if 15 min elapsed).
1355        reg.set_polling_expiry(
1356            "rust-works",
1357            "omni-dev",
1358            Utc::now() - ChronoDuration::seconds(1),
1359        );
1360        assert!(
1361            !reg.is_polling_enabled("rust-works", "omni-dev"),
1362            "an expired lease reads as disabled"
1363        );
1364        // The read paths reap it, so it is gone from the snapshot entirely.
1365        assert!(reg.enabled_polling_repos().is_empty());
1366        assert!(reg.polling_snapshot().is_empty());
1367        // A tiny real TTL expires on its own after a short sleep.
1368        let short = WorktreesRegistry::with_poll_ttl(Duration::from_millis(30));
1369        short.set_polling("o", "n", true);
1370        assert!(short.is_polling_enabled("o", "n"));
1371        std::thread::sleep(Duration::from_millis(60));
1372        assert!(!short.is_polling_enabled("o", "n"));
1373    }
1374
1375    #[test]
1376    fn set_polling_bumps_only_on_an_effective_flip() {
1377        let reg = WorktreesRegistry::new();
1378        let rx = reg.subscribe_changes();
1379        // A no-op (disabling an already-off repo) does not wake subscribers.
1380        assert!(!reg.set_polling("o", "n", false));
1381        assert!(
1382            !rx.has_changed().unwrap(),
1383            "a no-op poll toggle must not bump the change-notify"
1384        );
1385        // A real enable flips off→on and bumps so every window recolors.
1386        assert!(reg.set_polling("o", "n", true));
1387        assert!(
1388            rx.has_changed().unwrap(),
1389            "enabling a repo should bump the change-notify"
1390        );
1391    }
1392
1393    #[test]
1394    fn refreshing_a_live_lease_does_not_bump() {
1395        // A lease refresh (already on, still on) persists a new expiry but does
1396        // not change the visible state, so it must not wake every window.
1397        let reg = WorktreesRegistry::new();
1398        reg.set_polling("o", "n", true);
1399        let rx = reg.subscribe_changes();
1400        assert!(
1401            reg.set_polling("o", "n", true),
1402            "re-enabling refreshes the lease (map changed → persist)"
1403        );
1404        assert!(
1405            !rx.has_changed().unwrap(),
1406            "refreshing a live lease must not bump — the visible state is unchanged"
1407        );
1408    }
1409
1410    #[test]
1411    fn seed_polling_loads_leases_and_drops_expired() {
1412        let reg = WorktreesRegistry::new();
1413        reg.set_polling("a", "z", true);
1414        let future = Utc::now() + ChronoDuration::minutes(10);
1415        let past = Utc::now() - ChronoDuration::minutes(1);
1416        // Seeding (the startup load) replaces wholesale, dropping the prior entry
1417        // and any already-expired lease from the file.
1418        reg.seed_polling([
1419            ("rust-works/omni-dev".to_string(), future),
1420            ("acme/widgets".to_string(), future),
1421            ("stale/repo".to_string(), past),
1422        ]);
1423        assert!(!reg.is_polling_enabled("a", "z"));
1424        assert!(reg.is_polling_enabled("rust-works", "omni-dev"));
1425        assert!(
1426            !reg.is_polling_enabled("stale", "repo"),
1427            "expired lease dropped"
1428        );
1429        // The persisted form is deterministic (sorted) and carries the expiries.
1430        let snap = reg.polling_snapshot();
1431        assert_eq!(
1432            snap.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(),
1433            vec![
1434                "acme/widgets".to_string(),
1435                "rust-works/omni-dev".to_string()
1436            ]
1437        );
1438        assert!(snap.iter().all(|(_, expiry)| *expiry == future));
1439    }
1440}