forgetop-server 1.9.0

Local dashboard server and embedded web UI for forgetop. Internal crate: no API stability guarantees, use the `forgetop` binary instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! JSON shapes for the dashboard API, and the fetch functions that build them from the
//! same `SectionService` the TUI uses. Read-only in wave 1.

use std::sync::Arc;

use forgetop_core::domain::{
    CheckRun, CommentThread, Commit, FileChange, Notification, PipelineApproval, PipelineRun,
    ProviderType, PullRequest, PullRequestStatus, TimelineEvent, TimelineEventKind, WorkItem,
};
use forgetop_core::filter::run_triggered_by;
use forgetop_core::launchpad::{self, EntryItem, PipeInput, PrInput, WiInput};
use forgetop_core::provider::{
    ItemRef, PipelineSource, PrDecoration, PrWriteSupport, PullRequestFilter, PullRequestQuery,
    PullRequestSource, WorkItemQuery, WorkItemSource,
};
use forgetop_core::service::{ConnectionHealthService, SectionService};
use serde::Serialize;

fn log_fetch_failure(operation: &'static str) {
    forgetop_core::diag::log(operation, "provider fetch failed");
}

/// One item tagged with the connection it came from (the "Provider" column in the TUI).
#[derive(Serialize)]
pub struct PrRow {
    pub connection_id: String,
    pub connection: String,
    pub provider: ProviderType,
    pub pull_request: PullRequest,
    /// True when this row's decorated fields are missing and worth fetching per row. Only the
    /// providers whose list endpoint omits them say yes, so the other three cost nothing.
    pub needs_decoration: bool,
}

#[derive(Serialize)]
pub struct WiRow {
    pub connection_id: String,
    pub connection: String,
    pub provider: ProviderType,
    pub work_item: WorkItem,
}

#[derive(Serialize)]
pub struct PipeRow {
    pub connection_id: String,
    pub connection: String,
    pub provider: ProviderType,
    pub run: PipelineRun,
    /// The pipeline (definition) name this run belongs to, resolved from discovery — shown
    /// before the run name in the list. `None` if discovery doesn't name it.
    pub definition_name: Option<String>,
    /// Pending approval gates on this run (empty unless it's in-flight and the provider
    /// supports approvals) — drives the approve/reject buttons.
    pub approvals: Vec<PipelineApproval>,
}

#[derive(Serialize)]
pub struct NotifRow {
    pub connection_id: String,
    pub connection: String,
    pub provider: ProviderType,
    pub notification: Notification,
}

#[derive(Serialize)]
pub struct HealthRow {
    pub connection_id: String,
    pub display_name: String,
    pub provider: ProviderType,
    pub healthy: bool,
}

/// Which slice of pull requests the PR page is showing. The provider `list(query)` does the
/// filtering (the same path the TUI uses), so each view is correct for real providers, not just demo.
#[derive(Clone, Copy)]
pub enum PrView {
    /// Open PRs across the bound connections.
    All,
    /// Your own open PRs (authored by you, still open).
    Yours,
    /// PRs you authored that have merged (newest first is applied client-side by the default sort).
    MergedByYou,
    /// PRs where you're a requested reviewer.
    ReviewRequested,
}

impl PrView {
    /// Parses the `?view=` query param; anything unrecognised (or absent) means `All`.
    pub fn parse(s: Option<&str>) -> PrView {
        match s {
            Some("yours") => PrView::Yours,
            Some("merged") => PrView::MergedByYou,
            Some("review_requested") => PrView::ReviewRequested,
            _ => PrView::All,
        }
    }

    fn query(self) -> PullRequestQuery {
        let (filter, include_completed) = match self {
            // "Merged by you" needs completed PRs; we keep only the merged ones below.
            PrView::MergedByYou => (PullRequestFilter::Mine, true),
            PrView::Yours => (PullRequestFilter::Mine, false),
            PrView::ReviewRequested => (PullRequestFilter::ReviewRequested, false),
            PrView::All => (PullRequestFilter::All, false),
        };
        // The dashboard renders decorated fields (mergeable, +/-) per visible row from
        // `/api/pr/decoration`, so the list itself doesn't pay for them. On a five-repository
        // scope that is the difference between one list call per repo and ~50 extra per repo.
        PullRequestQuery { filter, include_completed, limit: Some(50), decorate: false }
    }

    /// `Mine + include_completed` also returns your closed-but-not-merged PRs; drop those.
    fn keep(self, pr: &PullRequest) -> bool {
        match self {
            PrView::MergedByYou => matches!(pr.status, PullRequestStatus::Merged),
            _ => true,
        }
    }
}

pub async fn pull_requests(sections: &SectionService, view: PrView) -> Vec<PrRow> {
    let mut out = Vec::new();
    if let Ok(feeds) = sections.pull_request_feeds().await.inspect_err(|_| log_fetch_failure("dashboard.pull_requests.feeds")) {
        let query = view.query();
        for feed in feeds {
            // The list skipped decoration, so say whether these rows are actually missing anything.
            let needs_decoration = feed.source.list_omits_decoration();
            if let Ok(list) = feed.source.list(&query).await.inspect_err(|_| log_fetch_failure("dashboard.pull_requests.list")) {
                out.extend(list.into_iter().filter(|pr| view.keep(pr)).map(|pr| PrRow {
                    connection_id: feed.connection.connection_id().to_string(),
                    connection: feed.connection.display_name().to_string(),
                    provider: feed.connection.provider_type(),
                    pull_request: pr,
                    needs_decoration,
                }));
            }
        }
    }
    out
}

pub async fn work_items(sections: &SectionService) -> Vec<WiRow> {
    let mut out = Vec::new();
    if let Ok(feeds) = sections.work_item_feeds().await.inspect_err(|_| log_fetch_failure("dashboard.work_items.feeds")) {
        let query = WorkItemQuery { mine_only: true, include_completed: false, limit: Some(50) };
        for feed in feeds {
            if let Ok(list) = feed.source.list(&query).await.inspect_err(|_| log_fetch_failure("dashboard.work_items.list")) {
                out.extend(list.into_iter().map(|wi| WiRow {
                    connection_id: feed.connection.connection_id().to_string(),
                    connection: feed.connection.display_name().to_string(),
                    provider: feed.connection.provider_type(),
                    work_item: wi,
                }));
            }
        }
    }
    out
}

pub async fn pipelines(sections: &SectionService) -> Vec<PipeRow> {
    let mut out = Vec::new();
    if let Ok(feeds) = sections.pipeline_feeds().await.inspect_err(|_| log_fetch_failure("dashboard.pipelines.feeds")) {
        for feed in feeds {
            let defs = feed
                .source
                .discover()
                .await
                .inspect_err(|_| log_fetch_failure("dashboard.pipelines.discover"))
                .unwrap_or_default();
            let def_names: std::collections::HashMap<String, String> =
                defs.iter().map(|d| (d.id.clone(), d.name.clone())).collect();
            let supports = feed.source.supports_approvals();
            for result in feed.list_runs(&defs).await {
                if let Ok(runs) = result.inspect_err(|_| log_fetch_failure("dashboard.pipelines.list")) {
                    for mut run in runs {
                        // Only in-flight runs can be waiting on a gate — bound the extra calls.
                        let approvals = if supports && run.status.is_active() {
                            feed.source
                                .pending_approvals(&run.item_ref())
                                .await
                                .inspect_err(|_| log_fetch_failure("dashboard.pipelines.pending_approvals"))
                                .unwrap_or_default()
                        } else {
                            Vec::new()
                        };
                        run.status = run.shown_status(approvals.iter().any(|a| a.blocks_run));
                        out.push(PipeRow {
                            connection_id: feed.connection.connection_id().to_string(),
                            connection: feed.connection.display_name().to_string(),
                            provider: feed.connection.provider_type(),
                            definition_name: def_names.get(&run.definition_id).cloned(),
                            approvals,
                            run,
                        });
                    }
                }
            }
        }
    }
    out
}

pub async fn notifications(sections: &SectionService) -> Vec<NotifRow> {
    let mut out = Vec::new();
    if let Ok(feeds) = sections.notification_feeds().await.inspect_err(|_| log_fetch_failure("dashboard.notifications.feeds")) {
        for feed in feeds {
            if let Ok(list) = feed.source.list().await.inspect_err(|_| log_fetch_failure("dashboard.notifications.list")) {
                out.extend(list.into_iter().map(|n| NotifRow {
                    connection_id: feed.connection.connection_id().to_string(),
                    connection: feed.connection.display_name().to_string(),
                    provider: feed.connection.provider_type(),
                    notification: n,
                }));
            }
        }
    }
    out.sort_by_key(|r| std::cmp::Reverse(r.notification.updated_at)); // newest first
    out
}

// ---- launchpad ----

/// The domain object behind a launchpad row, tagged so the frontend can switch on it.
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum LaunchpadItem {
    Pr { pull_request: PullRequest },
    Wi { work_item: WorkItem },
    Pipe { run: PipelineRun, definition_name: Option<String> },
}

/// One launchpad entry: its triage bucket (with display metadata) plus the item itself.
#[derive(Serialize)]
pub struct LaunchpadRow {
    pub bucket: &'static str,
    pub bucket_title: &'static str,
    pub column: usize,
    pub muted: bool,
    pub connection_id: String,
    pub connection: String,
    pub provider: ProviderType,
    #[serde(flatten)]
    pub item: LaunchpadItem,
}

/// The query behind every Command Center PR fetch. It **decorates**, for two separate reasons —
/// either one alone would be enough:
///
/// * it *ranks* on `mergeable` ([`launchpad::classify_pr`], author branch), and
/// * it *renders* `checks` on every PR row, whatever the role.
///
/// So "decorate only the rows we rank on" would be wrong here: a review-requested row is never
/// ranked on a decorated field but is still shown with its check status, and turning decoration
/// off would blank that out. The cost stays bounded because providers decorate **after** the
/// cross-scope sort and cap, so it scales with the rows returned, not with the repository scope.
///
/// The list page is the opposite case and does turn it off — it fetches decoration per visible
/// row from `/api/pr/decoration` instead.
fn launchpad_query(filter: PullRequestFilter, include_completed: bool) -> PullRequestQuery {
    PullRequestQuery { filter, include_completed, limit: Some(50), decorate: true }
}

/// Fetches PRs for a role into launchpad inputs. `include_completed` is on for your own PRs so
/// recently-merged ones can surface.
async fn pr_inputs(sections: &SectionService, filter: PullRequestFilter, include_completed: bool) -> Vec<PrInput> {
    let mut out = Vec::new();
    if let Ok(feeds) = sections.pull_request_feeds().await.inspect_err(|_| log_fetch_failure("dashboard.launchpad.pull_request_feeds")) {
        let query = launchpad_query(filter, include_completed);
        for feed in feeds {
            if let Ok(list) = feed.source.list(&query).await.inspect_err(|_| log_fetch_failure("dashboard.launchpad.pull_requests")) {
                out.extend(list.into_iter().map(|pr| PrInput {
                    connection_id: feed.connection.connection_id().to_string(),
                    connection: feed.connection.display_name().to_string(),
                    provider: feed.connection.provider_type(),
                    pr,
                }));
            }
        }
    }
    out
}

async fn wi_inputs(sections: &SectionService) -> Vec<WiInput> {
    let mut out = Vec::new();
    if let Ok(feeds) = sections.work_item_feeds().await.inspect_err(|_| log_fetch_failure("dashboard.launchpad.work_item_feeds")) {
        let query = WorkItemQuery { mine_only: true, include_completed: false, limit: Some(50) };
        for feed in feeds {
            if let Ok(list) = feed.source.list(&query).await.inspect_err(|_| log_fetch_failure("dashboard.launchpad.work_items")) {
                out.extend(list.into_iter().map(|wi| WiInput {
                    connection_id: feed.connection.connection_id().to_string(),
                    connection: feed.connection.display_name().to_string(),
                    provider: feed.connection.provider_type(),
                    wi,
                }));
            }
        }
    }
    out
}

/// Pipeline inputs with the derived flags the classifier needs: the pipeline's display name (from
/// discovery), whether an in-flight run is waiting on an approval gate you can respond to, and
/// whether you started it. Mirrors the TUI's pipeline reload.
async fn pipe_inputs(sections: &SectionService) -> Vec<PipeInput> {
    let mut out = Vec::new();
    if let Ok(feeds) = sections.pipeline_feeds().await.inspect_err(|_| log_fetch_failure("dashboard.launchpad.pipeline_feeds")) {
        for feed in feeds {
            let defs = feed
                .source
                .discover()
                .await
                .inspect_err(|_| log_fetch_failure("dashboard.launchpad.pipeline_discovery"))
                .unwrap_or_default();
            let def_names: std::collections::HashMap<String, String> =
                defs.iter().map(|d| (d.id.clone(), d.name.clone())).collect();
            let supports = feed.source.supports_approvals();
            // An identity that can't be established owns no runs — see `run_triggered_by`.
            let me = feed
                .source
                .current_user()
                .await
                .inspect_err(|_| log_fetch_failure("dashboard.launchpad.pipeline_current_user"))
                .unwrap_or_default();
            for result in feed.list_runs(&defs).await {
                if let Ok(runs) = result.inspect_err(|_| log_fetch_failure("dashboard.launchpad.pipelines")) {
                    for mut run in runs {
                        let approvals = if supports && run.status.is_active() {
                            feed.source
                                .pending_approvals(&run.item_ref())
                                .await
                                .inspect_err(|_| log_fetch_failure("dashboard.launchpad.pipeline_approvals"))
                                .unwrap_or_default()
                        } else {
                            Vec::new()
                        };
                        // Any pending gate holds the run; only one you can answer puts it in your queue.
                        run.status = run.shown_status(approvals.iter().any(|a| a.blocks_run));
                        let awaiting_approval = approvals.iter().any(|x| x.can_respond);
                        out.push(PipeInput {
                            connection_id: feed.connection.connection_id().to_string(),
                            connection: feed.connection.display_name().to_string(),
                            provider: feed.connection.provider_type(),
                            definition_name: def_names.get(&run.definition_id).cloned(),
                            awaiting_approval,
                            triggered_by_me: run_triggered_by(&run, me.as_deref()),
                            run,
                        });
                    }
                }
            }
        }
    }
    out
}

/// Which capped reference lists had more entries than they show — drives the "more…" links.
#[derive(Serialize)]
pub struct LaunchpadMore {
    pub needs_review: bool,
    pub your_work: bool,
    pub your_open_prs: bool,
    pub recently_merged: bool,
    pub recent_pipelines: bool,
}

/// The Launchpad payload: display-ordered rows plus per-bucket overflow flags.
#[derive(Serialize)]
pub struct LaunchpadResponse {
    pub rows: Vec<LaunchpadRow>,
    pub more: LaunchpadMore,
}

pub async fn launchpad(sections: &SectionService) -> LaunchpadResponse {
    let review = pr_inputs(sections, PullRequestFilter::ReviewRequested, false).await;
    let mine = pr_inputs(sections, PullRequestFilter::Mine, true).await;
    let wis = wi_inputs(sections).await;
    let pipes = pipe_inputs(sections).await;

    let built = launchpad::build(&review, &mine, &wis, &pipes);
    let rows = built
        .entries
        .into_iter()
        .map(|e| LaunchpadRow {
            bucket: e.bucket.key(),
            bucket_title: e.bucket.title(),
            column: e.bucket.column(),
            muted: e.bucket.muted(),
            connection_id: e.connection_id,
            connection: e.connection,
            provider: e.provider,
            item: match e.item {
                EntryItem::Pr(pr) => LaunchpadItem::Pr { pull_request: pr },
                EntryItem::Wi(wi) => LaunchpadItem::Wi { work_item: wi },
                EntryItem::Pipe { run, definition_name } => LaunchpadItem::Pipe { run, definition_name },
            },
        })
        .collect();
    LaunchpadResponse {
        rows,
        more: LaunchpadMore {
            needs_review: built.overflow.needs_review,
            your_work: built.overflow.your_work,
            your_open_prs: built.overflow.your_open_prs,
            recently_merged: built.overflow.recently_merged,
            recent_pipelines: built.overflow.recent_pipelines,
        },
    }
}

// ---- pull request detail ----

/// Everything the PR detail view needs, fetched in one shot.
#[derive(Serialize)]
pub struct PrDetail {
    pub pull_request: PullRequest,
    pub threads: Vec<CommentThread>,
    pub timeline: Vec<TimelineEvent>,
    pub changes: Vec<FileChange>,
    pub checks: Vec<CheckRun>,
    pub commits: Vec<Commit>,
    /// The signed-in user's handle on this connection, when it can be established — what the
    /// pane shows your vote and comments as before the provider lists them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub me: Option<String>,
    /// Which pull-request writes this connection supports (resolve threads, draft, close/reopen,
    /// request reviewer) — the pane disables the controls a provider can't perform.
    pub writes: PrWriteSupport,
}

/// Resolves the PR source for a connection id (the one the action/detail is scoped to).
pub async fn pr_source(sections: &SectionService, conn: &str) -> Option<Arc<dyn PullRequestSource>> {
    sections
        .pull_request_feeds()
        .await
        .inspect_err(|_| log_fetch_failure("dashboard.pull_requests.feeds"))
        .ok()?
        .into_iter()
        .find(|f| f.connection.connection_id() == conn)
        .map(|f| f.source)
}

/// Fold each conversation comment into the timeline as a lightweight "commented" event, so the
/// activity feed is complete (the provider timelines carry actions, not comments). Inline diff
/// comments are skipped — those belong to code review, shown on the diff. Sorted oldest → newest.
fn with_comment_events(mut timeline: Vec<TimelineEvent>, threads: &[CommentThread]) -> Vec<TimelineEvent> {
    for t in threads.iter().filter(|t| t.file_path.is_none()) {
        for c in &t.comments {
            timeline.push(TimelineEvent {
                actor: Some(c.author.clone()),
                kind: TimelineEventKind::Commented,
                summary: "commented".into(),
                at: c.created_at,
            });
        }
    }
    timeline.sort_by_key(|a| a.at);
    timeline
}

pub async fn pr_detail(sections: &SectionService, conn: &str, item: &ItemRef) -> Option<PrDetail> {
    let source = pr_source(sections, conn).await?;
    let pull_request = source.get(item).await.inspect_err(|_| log_fetch_failure("dashboard.pr_detail.get")).ok()?;
    // The detail extras are best-effort: a provider that doesn't expose one just yields empties.
    let threads = source
        .threads(item)
        .await
        .inspect_err(|_| log_fetch_failure("dashboard.pr_detail.threads"))
        .unwrap_or_default();
    let timeline = with_comment_events(
        source
            .timeline(item)
            .await
            .inspect_err(|_| log_fetch_failure("dashboard.pr_detail.timeline"))
            .unwrap_or_default(),
        &threads,
    );
    Some(PrDetail {
        pull_request,
        threads,
        timeline,
        changes: source
            .changes(item)
            .await
            .inspect_err(|_| log_fetch_failure("dashboard.pr_detail.changes"))
            .unwrap_or_default(),
        checks: source
            .checks(item)
            .await
            .inspect_err(|_| log_fetch_failure("dashboard.pr_detail.checks"))
            .unwrap_or_default(),
        commits: source
            .commits(item)
            .await
            .inspect_err(|_| log_fetch_failure("dashboard.pr_detail.commits"))
            .unwrap_or_default(),
        me: source
            .current_user()
            .await
            .inspect_err(|_| log_fetch_failure("dashboard.pr_detail.current_user"))
            .ok()
            .flatten(),
        writes: source.pr_writes(),
    })
}

/// The fields the PR list leaves out, for one pull request — fetched per visible row rather than
/// for every row of every repository in the scope.
pub async fn pr_decoration(sections: &SectionService, conn: &str, item: &ItemRef) -> Option<PrDecoration> {
    let source = pr_source(sections, conn).await?;
    source.decorate(item).await.inspect_err(|_| log_fetch_failure("dashboard.pr_decoration")).ok()
}

/// Files changed by a single commit on the PR (empty for providers without a per-commit diff API).
pub async fn pr_commit_changes(sections: &SectionService, conn: &str, item: &ItemRef, sha: &str) -> Option<Vec<FileChange>> {
    let source = pr_source(sections, conn).await?;
    Some(
        source
            .commit_changes(item, sha)
            .await
            .inspect_err(|_| log_fetch_failure("dashboard.pr_commit_changes"))
            .unwrap_or_default(),
    )
}

/// One file's full text as of `sha` (the PR's head when `None`), fetched only when a diff is
/// expanded. `None` for an unknown connection, a failed fetch, or a forge with no text to give.
pub async fn pr_file_text(sections: &SectionService, conn: &str, item: &ItemRef, path: &str, sha: Option<&str>) -> Option<String> {
    let source = pr_source(sections, conn).await?;
    source.file_text(item, path, sha).await.inspect_err(|_| log_fetch_failure("dashboard.pr_file_text")).ok().flatten()
}

// ---- work-item detail ----

/// Everything the work-item detail view needs.
#[derive(Serialize)]
pub struct WiDetail {
    pub work_item: WorkItem,
    pub threads: Vec<CommentThread>,
    pub timeline: Vec<TimelineEvent>,
}

/// Resolves the work-item source for a connection id.
pub async fn wi_source(sections: &SectionService, conn: &str) -> Option<Arc<dyn WorkItemSource>> {
    sections
        .work_item_feeds()
        .await
        .inspect_err(|_| log_fetch_failure("dashboard.work_items.feeds"))
        .ok()?
        .into_iter()
        .find(|f| f.connection.connection_id() == conn)
        .map(|f| f.source)
}

pub async fn wi_detail(sections: &SectionService, conn: &str, item: &ItemRef) -> Option<WiDetail> {
    let source = wi_source(sections, conn).await?;
    let work_item = source.get(item).await.inspect_err(|_| log_fetch_failure("dashboard.wi_detail.get")).ok()?;
    // Comments are best-effort: a provider that doesn't expose them just yields empties.
    let threads = source
        .threads(item)
        .await
        .inspect_err(|_| log_fetch_failure("dashboard.wi_detail.threads"))
        .unwrap_or_default();
    let timeline = with_comment_events(
        source
            .timeline(item)
            .await
            .inspect_err(|_| log_fetch_failure("dashboard.wi_detail.timeline"))
            .unwrap_or_default(),
        &threads,
    );
    Some(WiDetail { work_item, threads, timeline })
}

// ---- pipeline detail ----

/// Everything the pipeline drill-in needs: the full run (stages → jobs → steps) plus any
/// pending approval gates the current user can act on.
#[derive(Serialize)]
pub struct PipelineDetail {
    pub run: PipelineRun,
    pub approvals: Vec<PipelineApproval>,
}

/// Resolves the pipeline source for a connection id.
pub async fn pipe_source(sections: &SectionService, conn: &str) -> Option<Arc<dyn PipelineSource>> {
    sections
        .pipeline_feeds()
        .await
        .inspect_err(|_| log_fetch_failure("dashboard.pipelines.feeds"))
        .ok()?
        .into_iter()
        .find(|f| f.connection.connection_id() == conn)
        .map(|f| f.source)
}

pub async fn pipeline_detail(sections: &SectionService, conn: &str, run: &ItemRef) -> Option<PipelineDetail> {
    let source = pipe_source(sections, conn).await?;
    let mut run = source.get_run(run).await.inspect_err(|_| log_fetch_failure("dashboard.pipeline_detail.get")).ok()?;
    // Only in-flight runs can be waiting on a gate — mirror the list endpoint's bound.
    let approvals = if source.supports_approvals() && run.status.is_active() {
        source
            .pending_approvals(&run.item_ref())
            .await
            .inspect_err(|_| log_fetch_failure("dashboard.pipeline_detail.pending_approvals"))
            .unwrap_or_default()
    } else {
        Vec::new()
    };
    run.status = run.shown_status(approvals.iter().any(|a| a.blocks_run));
    Some(PipelineDetail { run, approvals })
}

/// Logs for a run, optionally scoped to a single job. Best-effort: `None` when the connection
/// isn't found or the provider can't supply logs.
pub async fn pipeline_logs(sections: &SectionService, conn: &str, run: &ItemRef, job_id: Option<&str>) -> Option<String> {
    let source = pipe_source(sections, conn).await?;
    source.logs(run, job_id).await.inspect_err(|_| log_fetch_failure("dashboard.pipeline_logs.get")).ok()
}

pub async fn health(svc: &ConnectionHealthService) -> Vec<HealthRow> {
    svc.check_all()
        .await
        .into_iter()
        .map(|h| HealthRow {
            connection_id: h.connection.id.clone(),
            display_name: h.connection.display_name.clone(),
            provider: h.connection.provider_type,
            healthy: h.healthy,
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use forgetop_core::domain::{CheckStatus, MergeableState, Reviewer, ReviewVote, User};

    fn pr(reviewers: Vec<Reviewer>) -> PullRequest {
        PullRequest {
            repository: Some("acme/pay".into()),
            id: "7".into(),
            number: Some(7),
            title: "Add retries".into(),
            description: None,
            author: User { id: "me".into(), display_name: "me".into(), handle: Some("me".into()), avatar_url: None },
            status: PullRequestStatus::Open,
            is_draft: false,
            source_ref: None,
            target_ref: None,
            reviewers,
            labels: vec![],
            checks: CheckStatus::Passed,
            check_summary: None,
            mergeable: MergeableState::Mergeable,
            changed_files: 0,
            additions: 0,
            deletions: 0,
            created_at: None,
            updated_at: None,
            url: None,
        }
    }

    fn approver() -> Reviewer {
        Reviewer {
            user: User { id: "priya".into(), display_name: "Priya".into(), handle: None, avatar_url: None },
            vote: ReviewVote::Approved,
            is_required: false,
        }
    }

    /// Every Command Center fetch decorates — for *both* roles, not just the ranked one.
    ///
    /// It is tempting to decorate only what the classifier ranks on, since `classify_pr` reads
    /// `mergeable` on the author branch alone. That is a trap: the Command Center also *renders*
    /// `checks` on every PR row, so a review-requested row fetched undecorated still looks
    /// wrong — it silently loses its check status. Both halves are asserted below, so removing
    /// either reason still leaves the other holding this test up.
    #[test]
    fn the_launchpad_decorates_every_fetch_it_ranks_or_renders_from() {
        for filter in [PullRequestFilter::Mine, PullRequestFilter::ReviewRequested, PullRequestFilter::All] {
            assert!(launchpad_query(filter, false).decorate, "{filter:?} feeds rows the Command Center renders checks on");
        }

        // Reason 1 — ranking: the same PR lands in a different bucket on `mergeable` alone, so an
        // undecorated "mine" fetch would rank an approved, mergeable PR as not ready to merge.
        let ready = pr(vec![approver()]);
        let mut conflicting = pr(vec![approver()]);
        conflicting.mergeable = MergeableState::Conflicting;
        assert_ne!(
            launchpad::classify_pr(&ready, launchpad::PrRole::Author).map(|b| b.key()),
            launchpad::classify_pr(&conflicting, launchpad::PrRole::Author).map(|b| b.key()),
        );

        // Reason 2 — rendering: a review-requested row is never *ranked* on a decorated field…
        let mut decorated = pr(vec![]);
        decorated.mergeable = MergeableState::Conflicting;
        decorated.checks = CheckStatus::Failed;
        assert_eq!(
            launchpad::classify_pr(&pr(vec![]), launchpad::PrRole::Reviewer).map(|b| b.key()),
            launchpad::classify_pr(&decorated, launchpad::PrRole::Reviewer).map(|b| b.key()),
            "ranking alone would say the review fetch needs no decoration"
        );
        // …but `checks` is a decorated field the row is drawn with, which is why it does.
        assert_ne!(decorated.checks, CheckStatus::None, "checks is what an undecorated row would lose");
    }

    /// Only the provider whose list endpoint actually omits the decorated fields asks the
    /// dashboard to fetch them per row. GitLab, Azure and Bitbucket fill everything they have
    /// from the list payload, so asking them would be one call per row returning what we had.
    #[tokio::test]
    async fn only_providers_whose_list_omits_decoration_ask_for_a_per_row_fetch() {
        use forgetop_providers::{bitbucket, github, gitlab};
        use forgetop_core::provider::{Connection, ProviderFactory};

        let conn = |provider, organization, repository, username| Connection {
            id: "c".into(),
            provider_type: provider,
            display_name: "c".into(),
            base_url: None,
            organization,
            project: None,
            repository,
            username,
            credential_ref: None,
            repo_scope: None,
        };
        let gh = github::GitHubFactory.create(&conn(ProviderType::GitHub, None, Some("acme/pay".into()), None), None).unwrap();
        assert!(gh.pull_requests().unwrap().list_omits_decoration(), "GitHub's /pulls omits them");

        let gl = gitlab::GitLabFactory.create(&conn(ProviderType::GitLab, None, Some("g/p".into()), None), None).unwrap();
        assert!(!gl.pull_requests().unwrap().list_omits_decoration(), "GitLab fills them from the list");

        let bb = bitbucket::BitbucketFactory
            .create(&conn(ProviderType::Bitbucket, Some("ws".into()), Some("repo".into()), Some("u".into())), None)
            .unwrap();
        assert!(!bb.pull_requests().unwrap().list_omits_decoration(), "Bitbucket fills them from the list");
    }
}