cargo-port 0.4.2

A TUI for inspecting and managing Rust projects
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
use std::collections::HashSet;
use std::path::Path;
use std::thread;
use std::time::Duration;
use std::time::Instant;

use tui_pane::PERF_LOG_TARGET;
use tui_pane::TrackedItem;

use super::constants::PR_CHECK_POLL_SECS;
use crate::ci;
use crate::ci::OwnerRepo;
use crate::http::HttpClient;
use crate::http::PullRequestFetch;
use crate::http::ServiceSignal;
use crate::project::AbsolutePath;
use crate::project::CheckoutInfo;
use crate::project::GitStatus;
use crate::project::LocalGitState;
use crate::project::ProjectPrData;
use crate::project::ProjectPrInfo;
use crate::project::ProjectPrUnavailable;
use crate::project::PullRequestGoneReason;
use crate::project::PullRequestInfo;
use crate::project::PullRequestState;
use crate::project::PullRequestUnavailableReason;
use crate::project::RepoInfo;
use crate::project::RootItem;
use crate::scan;
use crate::scan::BackgroundMsg;
use crate::scan::CachedRepoData;
use crate::scan::CiFetchResult;
use crate::scan::RepoCache;
use crate::tui::app::App;
use crate::tui::project_list::SyncResolution;
use crate::tui::state;

impl App {
    pub(super) fn spawn_repo_fetch_for_git_info(&mut self, path: &Path, repo_url: &str) {
        let Some(owner_repo) = ci::parse_owner_repo(repo_url) else {
            return;
        };
        // Dedup by `OwnerRepo`: a fetch for this repo is either already
        // running or queued. The `RepoFetchComplete` background message
        // removes the entry, so a later spawn after completion is not
        // blocked.
        if !self
            .net
            .github
            .repo_fetch_in_flight_mut()
            .insert(owner_repo.clone())
        {
            return;
        }
        let sender = self.background.background_sender();
        let client = self.net.http_client();
        let repo_cache = self.net.github.fetch_cache.clone();
        let path: AbsolutePath = AbsolutePath::from(path);
        let repo_url = repo_url.to_string();
        let ci_run_count = self.config.ci_run_count();
        thread::spawn(move || {
            let mut data =
                scan::load_cached_repo_data(&repo_cache, &owner_repo).unwrap_or_else(|| {
                    let _ = sender.send(BackgroundMsg::RepoFetchQueued {
                        repo: owner_repo.clone(),
                    });
                    let (result, meta, signal) = scan::fetch_ci_runs_cached(
                        &client,
                        &repo_url,
                        owner_repo.owner(),
                        owner_repo.repo(),
                        ci_run_count,
                    );
                    scan::emit_service_signal(&sender, signal);
                    let (runs, github_total) = match result {
                        CiFetchResult::Loaded { runs, github_total } => (runs, github_total),
                        CiFetchResult::CacheOnly(runs) => (runs, 0),
                    };
                    let data = CachedRepoData {
                        runs,
                        meta,
                        github_total,
                        pr_data: ProjectPrData::Unfetched,
                    };
                    scan::store_cached_repo_data(&repo_cache, &owner_repo, data.clone());
                    data
                });
            if data.pr_data.needs_fetch() {
                let _ = sender.send(BackgroundMsg::RepoFetchQueued {
                    repo: owner_repo.clone(),
                });
                let stale = data.pr_data.info().cloned();
                let _ = sender.send(BackgroundMsg::PullRequests {
                    repo: owner_repo.clone(),
                    data: ProjectPrData::Loading(stale.clone()),
                });
                let (pr_fetch, signal) = client.fetch_open_pull_requests(owner_repo.clone());
                scan::emit_service_signal(&sender, signal);
                data.pr_data = match pr_fetch {
                    Some(PullRequestFetch::Loaded(info)) => ProjectPrData::Loaded(info),
                    Some(PullRequestFetch::Unavailable(reason)) => {
                        ProjectPrData::Unavailable(ProjectPrUnavailable {
                            reason,
                            stale,
                            fetched_at: None,
                        })
                    },
                    None => ProjectPrData::Unavailable(ProjectPrUnavailable {
                        reason: PullRequestUnavailableReason::Network,
                        stale,
                        fetched_at: None,
                    }),
                };
                scan::store_cached_repo_data(&repo_cache, &owner_repo, data.clone());
            }
            let _ = sender.send(BackgroundMsg::CiRuns {
                path:         path.clone(),
                runs:         data.runs,
                github_total: data.github_total,
            });
            let _ = sender.send(BackgroundMsg::PullRequests {
                repo: owner_repo.clone(),
                data: data.pr_data,
            });
            if let Some(meta) = data.meta {
                let _ = sender.send(BackgroundMsg::RepoMeta {
                    path,
                    stars: meta.stars,
                    description: meta.description,
                });
            }
            // Fire `RepoFetchComplete` from the always-runs tail so the
            // dedup set clears on cache hits too. The startup toast
            // handler is a no-op for repos that were never queued.
            let _ = sender.send(BackgroundMsg::RepoFetchComplete { repo: owner_repo });
        });
    }
    /// Handle a per-checkout git state update. Writes to the
    /// `ProjectInfo.local_git_state` for `path`, runs startup tracking
    /// hooks, and triggers a repo-level fetch if applicable. The repo
    /// fetch trigger is here because either a `RepoInfo` or
    /// `CheckoutInfo` arrival can signal "this repo's state changed";
    /// the dedup set absorbs N attempts for the same `OwnerRepo`.
    pub fn handle_checkout_info(&mut self, path: &Path, info: CheckoutInfo) {
        tracing::trace!(
            target: PERF_LOG_TARGET,
            path = %path.display(),
            git_status = %info.status.label(),
            "checkout_info_applied"
        );
        let status = info.status;
        // Vendored crates and workspace members share their owning checkout's
        // `.git`, so a probe of their path resolves up to the worktree and
        // reports the worktree's branch / main delta and tracked ref — none of
        // which describe the child. They have no independent git identity (CI,
        // branch, and lint already resolve them to the owner), so never store
        // worktree state under a child path. The startup-tracking and
        // repo-fetch bookkeeping below still runs: those resolve `path` to the
        // owner's git directory / repo, so a child-path probe correctly counts
        // toward the owner.
        let stores_own_git_state = !self.project_list.is_vendored_path(path)
            && !self.project_list.is_workspace_member_path(path);
        if stores_own_git_state && let Some(project) = self.project_list.at_path_mut(path) {
            project.local_git_state = LocalGitState::Detected(Box::new(info));
        }
        // The worktree-summary cache embeds each entry's branch name read
        // from this in-memory state; drop it so the rows recompute against
        // the checkout info that just landed.
        self.panes.clear_worktree_summary_cache();
        // Detected git state implies the entry (or submodule) is in a
        // git repo. Ensure a `GitRepo` slot exists for `path` so per-repo
        // writes (CI, GitHub meta, RepoInfo) can land on it.
        self.project_list.ensure_git_repo_for(path);
        if self.scan.is_complete() {
            let git_dir = self
                .startup_git_directory_for_path(path)
                .unwrap_or_else(|| AbsolutePath::from(path));
            self.startup.git.seen.insert(git_dir);
            self.maybe_log_startup_phase_completions();
        }
        self.record_git_status_observation(path, status);
        self.maybe_trigger_repo_fetch(path);
    }
    /// Diff the current `GitStatus` for `path` against the tracker's
    /// baseline; on transition, push or extend the "Git status changes"
    /// task toast.
    fn record_git_status_observation(&mut self, path: &Path, status: GitStatus) {
        let Some(transition) = self
            .git_status_tracker
            .observe(AbsolutePath::from(path), status)
        else {
            return;
        };
        let name = path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("?")
            .to_string();
        let label = state::format_git_status_transition(&name, &transition);
        let seq = self.git_status_tracker.next_item_seq();
        let key = format!("{}#{seq}", path.display());
        let item = TrackedItem {
            label,
            key: key.into(),
            started_at: None,
            completed_at: Some(Instant::now()),
        };
        let reuse = self
            .git_status_tracker
            .current_toast()
            .filter(|id| self.framework.toasts.tracked_item_count(*id) > 0);
        let toast_id = reuse.unwrap_or_else(|| {
            let id = self.framework.toasts.push_task("Git status changes", "", 1);
            self.git_status_tracker.set_current_toast(Some(id));
            id
        });
        self.framework
            .toasts
            .add_new_tracked_items(toast_id, &[item]);
    }
    /// Handle a per-repo git state update. Only the primary checkout
    /// writes `RepoInfo` (linked worktrees share the primary's
    /// `.git/config` by design; admitting last-writer-wins from any
    /// checkout would produce silent arbitration if they ever
    /// diverged). The `path` is the primary's path — the emitter is
    /// responsible for that contract.
    pub fn handle_repo_info(&mut self, path: &Path, mut info: RepoInfo) {
        // Preserve a previously-fetched `first_commit` across refresh.
        // `RepoInfo::get` always returns `None` for it; the value is
        // filled in either by a prior `handle_git_first_commit` write
        // or via the `pending_git_first_commit` map below.
        let preserved_first_commit = self
            .project_list
            .repo_info_for(path)
            .and_then(|existing| existing.first_commit.clone());
        if info.first_commit.is_none() {
            info.first_commit = preserved_first_commit
                .or_else(|| self.scan.pending_git_first_commit_mut().remove(path));
        }
        // Gate GitHub cache invalidation on `FETCH_HEAD` mtime actually
        // advancing. Without this, every watcher tick / commit / branch
        // switch would invalidate the cache and trigger a refetch,
        // burning REST quota. ISO 8601 strings compare lexically in
        // chronological order, so `!=` captures advance reliably.
        let previous_last_fetched = self
            .project_list
            .repo_info_for(path)
            .and_then(|existing| existing.last_fetched.clone());
        let fetch_head_advanced =
            info.last_fetched.is_some() && info.last_fetched != previous_last_fetched;
        // Submodules write to their own `git_repo`; for top-level
        // entries we still apply the primary-only-write policy below.
        let is_submodule_target = self.project_list.is_submodule_path(path);
        if is_submodule_target {
            if let Some(git_repo) = self.project_list.ensure_git_repo_for(path) {
                git_repo.repo_info = Some(info);
            }
        } else if let Some(entry) = self.project_list.entry_containing_mut(path) {
            if entry.root_item.path().as_path() != path {
                // Non-primary write — discard per the policy above.
                return;
            }
            let git_repo = entry.git_repo.get_or_insert_with(Default::default);
            git_repo.repo_info = Some(info);
        }
        if fetch_head_advanced
            && self.scan.is_complete()
            && let Some(url) = self.project_list.fetch_url_for(path)
            && let Some(owner_repo) = ci::parse_owner_repo(&url)
            && !self.net.github.contains_in_flight(&owner_repo)
        {
            scan::invalidate_cached_repo_data(&self.net.github.fetch_cache, &owner_repo);
        }
        self.record_sync_observation(path);
        self.maybe_trigger_repo_fetch(path);
    }
    /// Diff the current sync state for `path` against the tracker's
    /// baseline; on transition, push or extend the "Sync changes" task
    /// toast.
    fn record_sync_observation(&mut self, path: &Path) {
        // Skip while git info is still loading — a not-yet-resolved value is
        // not a real sync state and must not become a baseline.
        let SyncResolution::Resolved(current) = self.project_list.primary_sync_resolution(path)
        else {
            return;
        };
        let Some(transition) = self.sync_tracker.observe(AbsolutePath::from(path), current) else {
            return;
        };
        let name = path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("?")
            .to_string();
        let label = state::format_sync_transition(&name, &transition);
        let seq = self.sync_tracker.next_item_seq();
        let key = format!("{}#{seq}", path.display());
        let item = TrackedItem {
            label,
            key: key.into(),
            started_at: None,
            completed_at: Some(Instant::now()),
        };
        let reuse = self
            .sync_tracker
            .current_toast()
            .filter(|id| self.framework.toasts.tracked_item_count(*id) > 0);
        let toast_id = reuse.unwrap_or_else(|| {
            let id = self.framework.toasts.push_task("Sync changes", "", 1);
            self.sync_tracker.set_current_toast(Some(id));
            id
        });
        self.framework
            .toasts
            .add_new_tracked_items(toast_id, &[item]);
    }
    /// Shared between `handle_repo_info` and `handle_checkout_info`:
    /// kick a GitHub fetch for this path's repo if we have a parseable
    /// remote URL. The dedup set in `App.net.github.repo_fetch_in_flight`
    /// keys on `OwnerRepo`, so a submodule sharing its `OwnerRepo` with
    /// the parent won't cause a duplicate fetch. Cache invalidation is
    /// gated inside `handle_repo_info` by `last_fetched` advance.
    pub(super) fn maybe_trigger_repo_fetch(&mut self, path: &Path) {
        let Some(url) = self.project_list.fetch_url_for(path) else {
            return;
        };
        self.spawn_repo_fetch_for_git_info(path, &url);
    }
    pub(super) fn handle_git_first_commit(&mut self, path: &Path, first_commit: Option<&str>) {
        let first_commit = first_commit.map(String::from);
        // first_commit is per-repo, so it lands on the entry's
        // `RepoInfo`. If the entry's `repo_info` slot doesn't exist yet
        // (`RepoInfo::get` hasn't completed), stash the value in
        // `pending_git_first_commit` and `handle_repo_info` will fold
        // it in when repo info arrives.
        let applied = self
            .project_list
            .entry_containing_mut(path)
            .and_then(|entry| entry.git_repo.as_mut()?.repo_info.as_mut())
            .map(|repo| repo.first_commit.clone_from(&first_commit))
            .is_some();
        if applied {
            self.scan.pending_git_first_commit_mut().remove(path);
        } else if let Some(first_commit) = first_commit {
            self.scan
                .pending_git_first_commit_mut()
                .insert(AbsolutePath::from(path), first_commit);
        } else {
            self.scan.pending_git_first_commit_mut().remove(path);
        }
    }
    pub(super) fn handle_repo_fetch_queued(&mut self, repo: OwnerRepo) {
        // Grow the repo denominator for as long as the startup panel is open,
        // so a fetch queued after local-git completes (and the denominator
        // stabilized) still feeds the GitHub row and holds the panel until it
        // finishes. A re-fetch of an already-seen repo un-marks it, so the
        // row cannot read done while this fetch is in flight. Once the panel
        // has closed, the fetch only drives the steady-state "Retrieving
        // GitHub repo details" toast.
        if self.startup.is_collecting() {
            self.startup.repo.expected.insert(repo.clone());
            self.startup.repo.seen.remove(&repo);
            self.startup.repo.complete_at = None;
        }
        self.net.github_running_mut().insert(repo, Instant::now());
        self.sync_running_repo_fetch_toast();
    }
    pub(super) fn handle_repo_fetch_complete(&mut self, repo: OwnerRepo) {
        self.net.github.repo_fetch_in_flight_mut().remove(&repo);
        self.net.github_running_mut().remove(&repo);
        self.mark_sync_eligible_for(&repo);
        self.startup.repo.seen.insert(repo);
        self.maybe_log_startup_phase_completions();
        self.sync_running_repo_fetch_toast();
    }
    pub(super) fn handle_pull_requests(&mut self, repo: &OwnerRepo, data: &ProjectPrData) {
        let prior = self.project_list.pr_info_for_repo(repo).cloned();
        let data = preserve_live_pr_snapshot_while_loading(data, prior.as_ref());
        let selected_matches = self.selected_repo_matches(repo);
        self.maybe_toast_deleted_pull_requests(repo, prior.as_ref(), &data);
        self.project_list.replace_pr_data_for_repo(repo, &data);
        self.sync_pull_request_check_polls(repo, &data);
        if selected_matches {
            self.scan.bump_generation();
        }
    }
    pub(super) fn handle_pull_request_check_poll_stopped(&mut self, repo: &OwnerRepo, number: u32) {
        let removed = self.net.github.remove_pr_check_poll(repo, number);
        if removed && self.selected_repo_matches(repo) {
            self.scan.bump_generation();
        }
    }
    fn selected_repo_matches(&self, repo: &OwnerRepo) -> bool {
        self.project_list
            .selected_project_path()
            .and_then(|path| self.project_list.fetch_url_for(path))
            .and_then(|url| ci::parse_owner_repo(&url))
            .as_ref()
            == Some(repo)
    }
    fn sync_pull_request_check_polls(&mut self, repo: &OwnerRepo, data: &ProjectPrData) {
        let ProjectPrData::Loaded(info) = data else {
            return;
        };
        let active = self.net.github.pr_check_poll_numbers(repo);
        let checking: HashSet<u32> = info
            .open
            .iter()
            .filter(|pull_request| pull_request.state == PullRequestState::ChecksFailing)
            .map(|pull_request| pull_request.number)
            .collect();
        for pull_request in info.open.iter().filter(|pull_request| {
            active.contains(&pull_request.number)
                && pull_request.state != PullRequestState::ChecksFailing
        }) {
            self.toast_pull_request_checks_finished(repo, pull_request);
        }
        self.net
            .github
            .retain_pr_check_polls_for_repo(repo, &checking);
        for number in checking {
            self.start_pull_request_check_poll(repo, number);
        }
    }
    fn toast_pull_request_checks_finished(
        &mut self,
        repo: &OwnerRepo,
        pull_request: &PullRequestInfo,
    ) {
        self.framework.toasts.push_status(
            "Pull request checks finished",
            format!(
                "{repo}: #{} {} is {}",
                pull_request.number,
                pull_request.title,
                pull_request.state.label()
            ),
        );
    }
    fn start_pull_request_check_poll(&mut self, repo: &OwnerRepo, number: u32) {
        if !self.net.github.insert_pr_check_poll(repo.clone(), number) {
            return;
        }
        let sender = self.background.background_sender();
        let client = self.net.http_client();
        let repo_cache = self.net.github.fetch_cache.clone();
        let repo = repo.clone();
        thread::spawn(move || {
            loop {
                thread::sleep(Duration::from_secs(PR_CHECK_POLL_SECS));
                let (data, signal) =
                    fetch_pull_requests_for_check_poll(&client, &repo_cache, &repo);
                scan::emit_service_signal(&sender, signal);
                let Some(data) = data else {
                    continue;
                };
                let still_checking = pull_request_still_checking(&data, number);
                let _ = sender.send(BackgroundMsg::PullRequests {
                    repo: repo.clone(),
                    data,
                });
                if !still_checking {
                    break;
                }
            }
            let _ = sender.send(BackgroundMsg::PullRequestCheckPollStopped { repo, number });
        });
    }
    fn maybe_toast_deleted_pull_requests(
        &self,
        repo: &OwnerRepo,
        prior: Option<&ProjectPrInfo>,
        data: &ProjectPrData,
    ) {
        let deleted = deleted_pull_requests(prior, data);
        if deleted.is_empty() {
            return;
        }
        self.spawn_pull_request_disappearance_classification(repo.clone(), deleted);
    }
    fn spawn_pull_request_disappearance_classification(
        &self,
        repo: OwnerRepo,
        pull_requests: Vec<PullRequestInfo>,
    ) {
        let sender = self.background.background_sender();
        let client = self.net.http_client();
        thread::spawn(move || {
            for pull_request in pull_requests {
                let (reason, signal) =
                    client.fetch_pull_request_gone_reason(repo.clone(), pull_request.number);
                scan::emit_service_signal(&sender, signal);
                let _ = sender.send(BackgroundMsg::PullRequestDisappeared {
                    repo: repo.clone(),
                    pull_request,
                    reason: reason.unwrap_or(PullRequestGoneReason::Unknown),
                });
            }
        });
    }
    pub(super) fn handle_pull_request_disappeared(
        &mut self,
        repo: &OwnerRepo,
        pull_request: &PullRequestInfo,
        reason: &PullRequestGoneReason,
    ) {
        let (title, body) = pull_request_disappeared_toast(repo, pull_request, reason);
        self.framework.toasts.push_status(title, body);
    }
    /// Flip the sync-toast eligibility flag for every project that resolves
    /// to `repo` via its fetch URL. The baseline is only seeded from a
    /// fully-resolved ahead/behind value — if git info is still loading the
    /// project becomes eligible with no baseline, and the first resolved
    /// observation seeds it silently (so a startup race never toasts).
    fn mark_sync_eligible_for(&mut self, repo: &OwnerRepo) {
        let mut targets: Vec<(AbsolutePath, SyncResolution)> = Vec::new();
        self.project_list.for_each_leaf_path(|path, _| {
            let Some(url) = self.project_list.fetch_url_for(path) else {
                return;
            };
            if ci::parse_owner_repo(&url).as_ref() != Some(repo) {
                return;
            }
            targets.push((
                AbsolutePath::from(path),
                self.project_list.primary_sync_resolution(path),
            ));
        });
        for (path, resolution) in targets {
            if let SyncResolution::Resolved(current) = resolution {
                self.sync_tracker.seed_baseline(path.clone(), current);
            }
            self.sync_tracker.mark_eligible(path);
        }
    }
    pub fn handle_project_discovered(&mut self, item: RootItem) -> bool {
        let legacy_expansions = self.project_list.capture_legacy_root_expansions();
        let discovered_path = item.path().to_path_buf();
        let mut already_exists = false;
        self.project_list.for_each_leaf_path(|path, _| {
            if path == discovered_path {
                already_exists = true;
            }
        });
        if already_exists {
            return false;
        }
        let service_item = item.clone();
        // Insert into the hierarchy directly — under a parent workspace if
        // one exists, otherwise as a top-level peer.
        let discovered_path = item.path().to_path_buf();
        let inline_dirs = self.config.current().tui.inline_dirs.clone();
        let dispatch = self.metadata_dispatch();
        {
            let mut tree = self.mutate_tree();
            tree.insert_into_hierarchy(item, &dispatch);
            tree.regroup_members(&inline_dirs);
        }
        self.register_discovery_shimmer(discovered_path.as_path());
        if !legacy_expansions.is_empty() {
            self.project_list
                .migrate_legacy_root_expansions(&legacy_expansions);
            self.rebuild_visible_rows_now();
        }
        self.reload_lint_history(&discovered_path);
        self.background
            .register_item_background_services(&service_item);
        self.register_lint_project_if_eligible(&service_item);
        // Signal that derived state and caches need refresh.
        // The caller batches multiple discoveries before refreshing once.
        true
    }
    pub fn handle_project_refreshed(&mut self, item: RootItem) -> bool {
        let legacy_expansions = self.project_list.capture_legacy_root_expansions();
        let path = item.path().to_path_buf();
        let service_item = item.clone();
        // Replace the leaf in project_list_items, transferring runtime data
        // from the old item to the incoming one. `worktree_health` is
        // filesystem-detected at refresh time and must survive the info copy.
        // `worktree_status` is no longer on `ProjectInfo` — it lives directly
        // on `Workspace` / `Package` / `NonRustProject` — so this copy cannot
        // clobber it.
        let inline_dirs = self.config.current().tui.inline_dirs.clone();
        let dispatch = self.metadata_dispatch();
        {
            let mut tree = self.mutate_tree();
            // The probe-side leaf comes back with a default `Cargo`, so
            // each replace re-dispatches `cargo metadata`; the first
            // (transient extraction) dispatch is superseded by the
            // second via the store's per-root generation counter.
            let Some(old) = tree.replace_leaf_by_path(&path, item.clone(), &dispatch) else {
                return false;
            };
            let mut item = item;
            for (project_path, info) in old.collect_project_info() {
                if let Some(project) = item.at_path_mut(&project_path) {
                    let fresh_worktree_health = project.worktree_health;
                    *project = info;
                    project.worktree_health = fresh_worktree_health;
                }
                transfer_lint_runs(&old, &mut item, &project_path);
                // Crates.io version/downloads live on `RustInfo` /
                // `VendoredPackage`, not `ProjectInfo`, and are never persisted.
                // Re-fetching on every refresh would repeatedly call crates.io,
                // so transfer the values the old item already holds.
                transfer_crates_io(&old, &mut item, &project_path);
            }
            // Re-replace with the runtime-data-enriched version.
            tree.replace_leaf_by_path(&path, item, &dispatch);
            tree.regroup_members(&inline_dirs);
            tree.regroup_top_level_worktrees();
        }
        self.reload_lint_history(&path);
        if !legacy_expansions.is_empty() {
            self.project_list
                .migrate_legacy_root_expansions(&legacy_expansions);
            self.rebuild_visible_rows_now();
        }
        self.ci.clear_content();
        self.lint.clear_content();
        self.panes.clear_detail_data(None);
        self.background
            .register_item_background_services(&service_item);
        self.register_lint_project_if_eligible(&service_item);
        // Signal that derived state needs refresh (batched by caller).
        true
    }
    fn startup_git_directory_for_path(&self, path: &Path) -> Option<AbsolutePath> {
        self.project_list
            .iter()
            .find(|entry| entry.root_item.at_path(path).is_some())
            .and_then(|entry| entry.root_item.git_directory())
    }
}

fn transfer_lint_runs(old: &RootItem, item: &mut RootItem, path: &AbsolutePath) {
    if let Some(source) = old.lint_at_path(path.as_path()).cloned()
        && let Some(target) = item.lint_at_path_mut(path.as_path())
    {
        *target = source;
    }
}

/// Copy crates.io version/downloads from `old` onto the freshly-scanned
/// `item` for the node at `path`. The node is either a `RustInfo` (workspace
/// root, member, or standalone package) or a `VendoredPackage`; both store the
/// values set by `BackgroundMsg::CratesIoVersion`.
fn transfer_crates_io(old: &RootItem, item: &mut RootItem, path: &AbsolutePath) {
    if let Some(source) = old.rust_info_at_path(path)
        && let (Some(version), Some(downloads)) =
            (source.crates_version(), source.crates_downloads())
        && let Some(target) = item.rust_info_at_path_mut(path)
    {
        let prerelease = source.crates_prerelease().map(str::to_string);
        target.set_crates_io(version.to_string(), prerelease, downloads);
    }
    if let Some(source) = old.vendored_at_path(path)
        && let (Some(version), Some(downloads)) =
            (source.crates_version(), source.crates_downloads())
        && let Some(target) = item.vendored_at_path_mut(path)
    {
        let prerelease = source.crates_prerelease().map(str::to_string);
        target.set_crates_io(version.to_string(), prerelease, downloads);
    }
}
fn preserve_live_pr_snapshot_while_loading(
    data: &ProjectPrData,
    prior: Option<&ProjectPrInfo>,
) -> ProjectPrData {
    match (data, prior) {
        (ProjectPrData::Loading(None), Some(prior)) => ProjectPrData::Loading(Some(prior.clone())),
        _ => data.clone(),
    }
}
fn pull_request_disappeared_toast(
    repo: &OwnerRepo,
    pull_request: &PullRequestInfo,
    reason: &PullRequestGoneReason,
) -> (String, String) {
    let prefix = format!(
        "#{number} {title}",
        number = pull_request.number,
        title = pull_request.title
    );
    match reason {
        PullRequestGoneReason::Merged { base } => (
            "Pull request merged".to_string(),
            format!("{repo}: {prefix} merged into {base}"),
        ),
        PullRequestGoneReason::Closed => (
            "Pull request closed".to_string(),
            format!("{repo}: {prefix} closed"),
        ),
        PullRequestGoneReason::Missing | PullRequestGoneReason::Unknown => (
            "Pull request no longer open".to_string(),
            format!("{repo}: {prefix} is no longer open"),
        ),
    }
}
fn deleted_pull_requests(
    prior: Option<&ProjectPrInfo>,
    data: &ProjectPrData,
) -> Vec<PullRequestInfo> {
    let Some(previous) = prior else {
        return Vec::new();
    };
    let ProjectPrData::Loaded(current) = data else {
        return Vec::new();
    };
    if previous.viewer_login != current.viewer_login {
        return Vec::new();
    }
    let current_numbers: HashSet<u32> = current
        .open
        .iter()
        .map(|pull_request| pull_request.number)
        .collect();
    previous
        .open
        .iter()
        .filter(|pull_request| !current_numbers.contains(&pull_request.number))
        .cloned()
        .collect()
}
fn fetch_pull_requests_for_check_poll(
    client: &HttpClient,
    repo_cache: &RepoCache,
    repo: &OwnerRepo,
) -> (Option<ProjectPrData>, Option<ServiceSignal>) {
    let (pr_fetch, signal) = client.fetch_open_pull_requests(repo.clone());
    let data = match pr_fetch {
        Some(PullRequestFetch::Loaded(info)) => ProjectPrData::Loaded(info),
        Some(PullRequestFetch::Unavailable(_)) | None => return (None, signal),
    };
    store_polled_pull_request_data(repo_cache, repo, &data);
    (Some(data), signal)
}
fn store_polled_pull_request_data(repo_cache: &RepoCache, repo: &OwnerRepo, data: &ProjectPrData) {
    let Some(mut cached) = scan::load_cached_repo_data(repo_cache, repo) else {
        return;
    };
    cached.pr_data = data.clone();
    scan::store_cached_repo_data(repo_cache, repo, cached);
}
fn pull_request_still_checking(data: &ProjectPrData, number: u32) -> bool {
    data.info().is_some_and(|info| {
        info.open.iter().any(|pull_request| {
            pull_request.number == number && pull_request.state == PullRequestState::ChecksFailing
        })
    })
}