holger-ui 0.1.1

Operator/admin UI for holger over the HolgerObject core API — egui via facett, embedded (LocalHolger, direct core calls) or remote (RemoteHolger gRPC).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! Transport-agnostic view-model for the holger UI.
//!
//! Everything the UI renders is produced here by calling the core
//! [`HolgerObject`] API. That trait is satisfied by `LocalHolger` (direct
//! in-process rust calls into holger core) or `RemoteHolger` (gRPC) — the UI
//! does not care which. There is **no egui in this module**: every view is plain
//! data with a `state_json()` method, so the UI's state can be asserted
//! headlessly (the nordisk "see what the user sees as data" law).
//!
//! The single [`UiData`] handle owns a private current-thread tokio runtime and
//! runs exactly one core call per UI action (the nornir-viz idiom), so an egui
//! `update` loop can stay synchronous.

use std::sync::Arc;

use serde::Serialize;
use serde_json::{json, Value};
use traits::{ArtifactId, Health, HolgerObject, RepositoryInfo};

/// Archive browse view — backs the Archive tab (`ArchiveService`). Holds the raw
/// file paths inside the znippy archive backing `repository` plus its stats
/// (file count, total uncompressed bytes, archive/repo name). `error` carries a
/// core/transport failure from either the `archive_info` or `list_archive_files`
/// call that fed it.
#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
pub struct ArchiveView {
    pub repository: String,
    pub files: Vec<String>,
    pub file_count: u64,
    pub total_uncompressed_bytes: u64,
    pub archive_path: String,
    pub error: Option<String>,
}

impl ArchiveView {
    pub fn state_json(&self) -> Value {
        serde_json::to_value(self).unwrap_or(Value::Null)
    }
}

/// One repository row in the picker/sidebar — mirrors [`RepositoryInfo`].
///
/// `writable` is exactly the flag the Upload control reads; `has_archive` gates
/// the Archive tab.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct RepoRow {
    pub name: String,
    pub repo_type: String,
    pub writable: bool,
    pub has_archive: bool,
}

impl From<RepositoryInfo> for RepoRow {
    fn from(r: RepositoryInfo) -> Self {
        Self {
            name: r.name,
            repo_type: r.repo_type,
            writable: r.writable,
            has_archive: r.has_archive,
        }
    }
}

/// Status / About view — backs the Status tab (`Health`).
#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
pub struct StatusView {
    pub status: String,
    pub version: String,
    pub uptime_seconds: i64,
    /// `true` once a successful `health()` has populated this view.
    pub loaded: bool,
    /// Last error from `health()`, if any.
    pub error: Option<String>,
}

impl StatusView {
    pub fn state_json(&self) -> Value {
        serde_json::to_value(self).unwrap_or(Value::Null)
    }
}

/// Repo picker view — backs the Repos tab (`ListRepositories`).
#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
pub struct ReposView {
    pub repos: Vec<RepoRow>,
    /// Index into `repos` of the active selection, if any.
    pub selected: Option<usize>,
    pub error: Option<String>,
}

impl ReposView {
    pub fn state_json(&self) -> Value {
        serde_json::to_value(self).unwrap_or(Value::Null)
    }

    /// The currently selected repo row, if any.
    pub fn selected_repo(&self) -> Option<&RepoRow> {
        self.selected.and_then(|i| self.repos.get(i))
    }

    /// Whether the Upload control should be enabled: a writable repo is selected.
    /// Exactly the `RepositoryInfo.writable` gate from the UI brief.
    pub fn upload_enabled(&self) -> bool {
        self.selected_repo().map(|r| r.writable).unwrap_or(false)
    }
}

/// Artifact fetch view — backs the Artifact tab (`FetchArtifact`).
///
/// The raw bytes are kept on the view but **never** serialized into
/// `state_json()` (only `size_bytes`), so headless snapshots stay small and
/// don't leak payloads.
#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
pub struct ArtifactView {
    pub repository: String,
    pub namespace: Option<String>,
    pub name: String,
    pub version: String,
    pub size_bytes: u64,
    pub content_type: String,
    /// `true` if the last fetch returned bytes; `false` for a clean `NOT_FOUND`.
    pub found: bool,
    /// Transport/server error (distinct from a clean not-found).
    pub error: Option<String>,
    #[serde(skip)]
    pub data: Vec<u8>,
}

impl ArtifactView {
    pub fn state_json(&self) -> Value {
        serde_json::to_value(self).unwrap_or(Value::Null)
    }
}

/// One artifact row in a repository listing — mirrors [`traits::ArtifactEntry`]
/// (the proto `ArtifactEntry`), with the id flattened into the columns the
/// Browse table renders.
#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
pub struct BrowseRow {
    pub namespace: Option<String>,
    pub name: String,
    pub version: String,
    pub size_bytes: i64,
    pub content_type: String,
}

/// Browse view — backs the Browse tab (`ListArtifacts`). Holds one page of
/// entries for the active `repository` plus the opaque `next_page_token` the
/// core returned (empty when the listing is exhausted).
#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
pub struct BrowseView {
    pub repository: String,
    pub entries: Vec<BrowseRow>,
    pub next_page_token: String,
    pub error: Option<String>,
}

impl BrowseView {
    pub fn state_json(&self) -> Value {
        serde_json::to_value(self).unwrap_or(Value::Null)
    }
}

/// The UI's data layer: a holger handle + a private current-thread runtime so the
/// async core calls can be driven synchronously (one blocking call per UI
/// action — the nornir-viz idiom).
pub struct UiData {
    holger: Arc<dyn HolgerObject>,
    rt: tokio::runtime::Runtime,
    pub status: StatusView,
    pub repos: ReposView,
    pub artifact: ArtifactView,
    pub browse: BrowseView,
    pub archive: ArchiveView,
}

impl UiData {
    /// Build a data layer around any `HolgerObject` (embedded or remote).
    pub fn new(holger: Arc<dyn HolgerObject>) -> anyhow::Result<Self> {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;
        Ok(Self {
            holger,
            rt,
            status: StatusView::default(),
            repos: ReposView::default(),
            artifact: ArtifactView::default(),
            browse: BrowseView::default(),
            archive: ArchiveView::default(),
        })
    }

    /// Build a data layer from a handle plus a caller-provided runtime. Use this
    /// when the handle's transport (e.g. a tonic channel) must be created on the
    /// **same** runtime that later drives its calls — the single-runtime tonic
    /// idiom. [`UiData::new`] is the common case (it makes its own current-thread
    /// runtime).
    pub fn with_runtime(holger: Arc<dyn HolgerObject>, rt: tokio::runtime::Runtime) -> Self {
        Self {
            holger,
            rt,
            status: StatusView::default(),
            repos: ReposView::default(),
            artifact: ArtifactView::default(),
            browse: BrowseView::default(),
            archive: ArchiveView::default(),
        }
    }

    /// Run one async core call to completion on the private runtime.
    fn block<T>(&self, fut: impl std::future::Future<Output = T>) -> T {
        self.rt.block_on(fut)
    }

    /// Refresh the Status tab from `health()`.
    pub fn refresh_status(&mut self) {
        match self.block(self.holger.health()) {
            Ok(Health {
                status,
                version,
                uptime_seconds,
            }) => {
                self.status = StatusView {
                    status,
                    version,
                    uptime_seconds,
                    loaded: true,
                    error: None,
                };
            }
            Err(e) => {
                self.status.loaded = false;
                self.status.error = Some(e.to_string());
            }
        }
    }

    /// Refresh the repo picker from `list_repositories()`. Selection is preserved
    /// by name across refreshes; a first load selects the first repo.
    pub fn refresh_repos(&mut self) {
        let prev = self.repos.selected_repo().map(|r| r.name.clone());
        match self.block(self.holger.list_repositories()) {
            Ok(list) => {
                let repos: Vec<RepoRow> = list.into_iter().map(RepoRow::from).collect();
                let selected = prev
                    .and_then(|name| repos.iter().position(|r| r.name == name))
                    .or(if repos.is_empty() { None } else { Some(0) });
                self.repos = ReposView {
                    repos,
                    selected,
                    error: None,
                };
            }
            Err(e) => self.repos.error = Some(e.to_string()),
        }
    }

    /// Select a repo by index (a click handler / headless-test entry point).
    pub fn select_repo(&mut self, idx: usize) {
        if idx < self.repos.repos.len() {
            self.repos.selected = Some(idx);
        }
    }

    /// Fetch an artifact into the Artifact tab. A clean `NOT_FOUND` is rendered
    /// as `found = false` (not an error); transport/server failures land in
    /// `error`.
    pub fn fetch_artifact(&mut self, repository: &str, id: ArtifactId) {
        let res = self.block(self.holger.fetch(repository, &id));
        let mut view = ArtifactView {
            repository: repository.to_string(),
            namespace: id.namespace,
            name: id.name,
            version: id.version,
            ..Default::default()
        };
        match res {
            Ok(Some(bytes)) => {
                view.size_bytes = bytes.len() as u64;
                view.content_type = "application/octet-stream".into();
                view.found = true;
                view.data = bytes;
            }
            Ok(None) => view.found = false,
            Err(e) => view.error = Some(e.to_string()),
        }
        self.artifact = view;
    }

    /// Page size for the Browse tab.
    const BROWSE_PAGE_SIZE: u32 = 100;

    /// Refresh the Browse tab from `list_artifacts()` for `repository`,
    /// optionally narrowed by a `name_filter` substring — loads the FIRST page
    /// (up to [`Self::BROWSE_PAGE_SIZE`]). The continuation token is kept on the
    /// view; call [`UiData::load_more_browse`] to append the next page. A core
    /// error lands in `error`.
    pub fn refresh_browse(&mut self, repository: &str, name_filter: Option<String>) {
        let res = self.block(self.holger.list_artifacts(
            repository,
            name_filter,
            Self::BROWSE_PAGE_SIZE,
            None,
        ));
        let mut view = BrowseView {
            repository: repository.to_string(),
            ..Default::default()
        };
        match res {
            Ok((entries, next_page_token)) => {
                view.entries = entries
                    .into_iter()
                    .map(|e| BrowseRow {
                        namespace: e.id.namespace,
                        name: e.id.name,
                        version: e.id.version,
                        size_bytes: e.size_bytes,
                        content_type: e.content_type,
                    })
                    .collect();
                view.next_page_token = next_page_token;
            }
            Err(e) => view.error = Some(e.to_string()),
        }
        self.browse = view;
    }

    /// Append the next page of the current Browse listing using the stored
    /// continuation token. No-op when the listing is exhausted (empty token).
    pub fn load_more_browse(&mut self) {
        if self.browse.next_page_token.is_empty() {
            return;
        }
        let repository = self.browse.repository.clone();
        let token = self.browse.next_page_token.clone();
        let res = self.block(self.holger.list_artifacts(
            &repository,
            None,
            Self::BROWSE_PAGE_SIZE,
            Some(token),
        ));
        match res {
            Ok((entries, next_page_token)) => {
                self.browse
                    .entries
                    .extend(entries.into_iter().map(|e| BrowseRow {
                        namespace: e.id.namespace,
                        name: e.id.name,
                        version: e.id.version,
                        size_bytes: e.size_bytes,
                        content_type: e.content_type,
                    }));
                self.browse.next_page_token = next_page_token;
                self.browse.error = None;
            }
            Err(e) => self.browse.error = Some(e.to_string()),
        }
    }

    /// Refresh the Archive tab for `repository`: load the archive stats
    /// (`archive_info`) and the raw file paths (`list_archive_files`, optionally
    /// narrowed by a path `prefix`). Two core calls feed one view; an error from
    /// **either** lands in `error` (and leaves the rest at its default). The
    /// `repository` is always recorded so the UI shows which repo it tried.
    pub fn refresh_archive(&mut self, repository: &str, prefix: Option<String>) {
        let mut view = ArchiveView {
            repository: repository.to_string(),
            ..Default::default()
        };
        match self.block(self.holger.archive_info(repository)) {
            Ok(info) => {
                view.file_count = info.file_count;
                view.total_uncompressed_bytes = info.total_uncompressed_bytes;
                view.archive_path = info.archive_path;
            }
            Err(e) => view.error = Some(e.to_string()),
        }
        if view.error.is_none() {
            match self.block(self.holger.list_archive_files(repository, prefix)) {
                Ok(files) => view.files = files,
                Err(e) => view.error = Some(e.to_string()),
            }
        }
        self.archive = view;
    }

    /// Upload bytes to a (writable) repo. The core error is returned verbatim so
    /// the UI can map it to an affordance (PERMISSION_DENIED → "read-only", …).
    pub fn put_artifact(&self, repository: &str, id: &ArtifactId, data: &[u8]) -> anyhow::Result<()> {
        self.block(self.holger.put(repository, id, data))
    }

    /// One combined snapshot of every view — the headless `$APP_STATE` a robot
    /// test asserts against.
    pub fn state_json(&self) -> Value {
        json!({
            "status": self.status.state_json(),
            "repos": self.repos.state_json(),
            "artifact": self.artifact.state_json(),
            "browse": self.browse.state_json(),
            "archive": self.archive.state_json(),
        })
    }
}

#[cfg(feature = "gui")]
impl UiData {
    /// Connect to a remote holger gRPC endpoint (no credentials).
    pub fn connect_remote(endpoint: &str) -> anyhow::Result<Self> {
        Self::connect_remote_with_token(endpoint, None)
    }

    /// Connect to a remote holger gRPC endpoint, optionally with an OIDC bearer
    /// token injected on every request (needed for write access on an
    /// auth-enabled server).
    ///
    /// The data layer's private runtime owns the channel — so the connect and
    /// every later call share one current-thread runtime (the single-runtime
    /// tonic idiom the nornir viz uses; avoids a channel outliving the runtime
    /// that spawned it).
    pub fn connect_remote_with_token(endpoint: &str, token: Option<&str>) -> anyhow::Result<Self> {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;
        let holger: Arc<dyn HolgerObject> = match token {
            Some(t) => Arc::new(
                rt.block_on(server_lib::RemoteHolger::connect_with_token(endpoint.to_string(), t))?,
            ),
            None => {
                Arc::new(rt.block_on(server_lib::RemoteHolger::connect(endpoint.to_string()))?)
            }
        };
        Ok(Self::with_runtime(holger, rt))
    }

    /// Connect to a remote holger gRPC endpoint over TLS (and mTLS when a
    /// `client_identity` cert+key is supplied), optionally with a bearer token.
    ///
    /// Same single-runtime pattern as [`UiData::connect_remote_with_token`]: the
    /// data layer's private current-thread runtime owns the TLS channel, so the
    /// connect and every later call share one runtime.
    ///
    /// NOTE: only the client TLS path is built here; there is no end-to-end mTLS
    /// integration test (it needs generated certs + a TLS server — a manual /
    /// mannequin step). This path is verified to *compile* only.
    pub fn connect_remote_with_tls(
        endpoint: &str,
        ca: Option<Vec<u8>>,
        client_identity: Option<(Vec<u8>, Vec<u8>)>,
        token: Option<&str>,
    ) -> anyhow::Result<Self> {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;
        let holger: Arc<dyn HolgerObject> = Arc::new(rt.block_on(
            server_lib::RemoteHolger::connect_with_tls(
                endpoint.to_string(),
                ca,
                client_identity,
                token.map(|t| t.to_string()),
            ),
        )?);
        Ok(Self::with_runtime(holger, rt))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use std::collections::HashMap;
    use std::sync::Mutex;

    /// A configurable in-memory `HolgerObject` for driving the view-model with no
    /// server. `fail` flips every call to an error (transport-failure path).
    #[derive(Default)]
    struct FakeHolger {
        repos: Vec<RepositoryInfo>,
        artifacts: HashMap<(String, String), Vec<u8>>, // (repo, name) -> bytes
        /// Canned listings keyed by repository name — what `list_artifacts`
        /// returns (filtered by `name_filter` substring when one is given).
        listings: HashMap<String, Vec<traits::ArtifactEntry>>,
        puts: Mutex<Vec<(String, String, Vec<u8>)>>,
        fail: bool,
    }

    impl FakeHolger {
        fn key(repo: &str, id: &ArtifactId) -> (String, String) {
            (repo.to_string(), id.name.clone())
        }
    }

    #[async_trait]
    impl HolgerObject for FakeHolger {
        async fn fetch(&self, repository: &str, id: &ArtifactId) -> anyhow::Result<Option<Vec<u8>>> {
            if self.fail {
                anyhow::bail!("boom");
            }
            Ok(self.artifacts.get(&Self::key(repository, id)).cloned())
        }
        async fn put(&self, repository: &str, id: &ArtifactId, data: &[u8]) -> anyhow::Result<()> {
            if self.fail {
                anyhow::bail!("boom");
            }
            // Mirror the server: reject writes to a read-only repo.
            let writable = self
                .repos
                .iter()
                .find(|r| r.name == repository)
                .map(|r| r.writable)
                .unwrap_or(false);
            if !writable {
                anyhow::bail!("Repository is read-only");
            }
            self.puts
                .lock()
                .unwrap()
                .push((repository.to_string(), id.name.clone(), data.to_vec()));
            Ok(())
        }
        async fn list_repositories(&self) -> anyhow::Result<Vec<RepositoryInfo>> {
            if self.fail {
                anyhow::bail!("boom");
            }
            Ok(self.repos.clone())
        }
        async fn list_artifacts(
            &self,
            repository: &str,
            name_filter: Option<String>,
            _limit: u32,
            _page_token: Option<String>,
        ) -> anyhow::Result<(Vec<traits::ArtifactEntry>, String)> {
            if self.fail {
                anyhow::bail!("boom");
            }
            // An unknown / empty repo yields an empty page (mirrors a server
            // returning nothing), not an error.
            let entries = self
                .listings
                .get(repository)
                .cloned()
                .unwrap_or_default()
                .into_iter()
                .filter(|e| match &name_filter {
                    Some(f) => e.id.name.contains(f.as_str()),
                    None => true,
                })
                .collect();
            Ok((entries, String::new()))
        }
        async fn list_archive_files(
            &self,
            repository: &str,
            prefix: Option<String>,
        ) -> anyhow::Result<Vec<String>> {
            if self.fail {
                anyhow::bail!("boom");
            }
            // Canned archive listing for the known repo "rust-arch"; unknown
            // repos yield an empty listing (mirrors a backend with no archive).
            let files: Vec<String> = if repository == "rust-arch" {
                vec![
                    "crates/serde-1.0.0.crate".to_string(),
                    "crates/tokio-1.2.0.crate".to_string(),
                    "index/config.json".to_string(),
                ]
            } else {
                Vec::new()
            };
            Ok(match prefix {
                Some(p) => files.into_iter().filter(|f| f.starts_with(&p)).collect(),
                None => files,
            })
        }
        async fn archive_info(&self, repository: &str) -> anyhow::Result<traits::ArchiveInfo> {
            if self.fail {
                anyhow::bail!("boom");
            }
            if repository == "rust-arch" {
                Ok(traits::ArchiveInfo {
                    file_count: 3,
                    total_uncompressed_bytes: 600,
                    archive_path: "rust-arch".into(),
                })
            } else {
                Ok(traits::ArchiveInfo::default())
            }
        }
        async fn health(&self) -> anyhow::Result<Health> {
            if self.fail {
                anyhow::bail!("boom");
            }
            Ok(Health {
                status: "ok".into(),
                version: "9.9.9".into(),
                uptime_seconds: 42,
            })
        }
    }

    fn repo(name: &str, writable: bool) -> RepositoryInfo {
        RepositoryInfo {
            name: name.into(),
            repo_type: "Rust".into(),
            writable,
            has_archive: true,
        }
    }

    fn ui(fake: FakeHolger) -> UiData {
        UiData::new(Arc::new(fake)).expect("runtime")
    }

    fn entry(name: &str, version: &str, size: i64) -> traits::ArtifactEntry {
        traits::ArtifactEntry {
            id: ArtifactId {
                namespace: None,
                name: name.into(),
                version: version.into(),
            },
            size_bytes: size,
            content_type: "application/octet-stream".into(),
        }
    }

    #[test]
    fn status_ok_populates_view_and_state_json() {
        let mut d = ui(FakeHolger::default());
        d.refresh_status();
        assert!(d.status.loaded);
        assert_eq!(d.status.version, "9.9.9");
        assert_eq!(d.status.uptime_seconds, 42);
        assert!(d.status.error.is_none());

        let s = d.status.state_json();
        assert_eq!(s["loaded"], json!(true));
        assert_eq!(s["version"], json!("9.9.9"));
    }

    #[test]
    fn status_error_is_surfaced_not_loaded() {
        let mut d = ui(FakeHolger {
            fail: true,
            ..Default::default()
        });
        d.refresh_status();
        assert!(!d.status.loaded);
        assert_eq!(d.status.error.as_deref(), Some("boom"));
    }

    #[test]
    fn repos_load_selects_first_and_preserves_selection_by_name() {
        let mut d = ui(FakeHolger {
            repos: vec![repo("rust-prod", false), repo("rust-dev", true)],
            ..Default::default()
        });
        d.refresh_repos();
        assert_eq!(d.repos.repos.len(), 2);
        assert_eq!(d.repos.selected, Some(0));
        assert_eq!(d.repos.selected_repo().unwrap().name, "rust-prod");

        // Select the writable one, then refresh: selection sticks to "rust-dev".
        d.select_repo(1);
        d.refresh_repos();
        assert_eq!(d.repos.selected_repo().unwrap().name, "rust-dev");
    }

    #[test]
    fn upload_enabled_tracks_selected_repo_writable() {
        let mut d = ui(FakeHolger {
            repos: vec![repo("rust-prod", false), repo("rust-dev", true)],
            ..Default::default()
        });
        d.refresh_repos();
        // rust-prod (read-only) selected first.
        assert!(!d.repos.upload_enabled());
        d.select_repo(1); // rust-dev (writable)
        assert!(d.repos.upload_enabled());
    }

    #[test]
    fn fetch_found_sets_size_and_does_not_leak_bytes_into_state_json() {
        let mut arts = HashMap::new();
        arts.insert(("rust-prod".to_string(), "serde".to_string()), vec![1u8; 100]);
        let mut d = ui(FakeHolger {
            artifacts: arts,
            ..Default::default()
        });
        let id = ArtifactId {
            namespace: None,
            name: "serde".into(),
            version: "1.0.0".into(),
        };
        d.fetch_artifact("rust-prod", id);
        assert!(d.artifact.found);
        assert_eq!(d.artifact.size_bytes, 100);
        assert_eq!(d.artifact.data.len(), 100);

        let s = d.artifact.state_json();
        assert_eq!(s["size_bytes"], json!(100));
        assert_eq!(s["found"], json!(true));
        assert!(s.get("data").is_none(), "raw bytes must not appear in state_json");
    }

    #[test]
    fn fetch_missing_is_not_found_not_error() {
        let mut d = ui(FakeHolger::default());
        let id = ArtifactId {
            namespace: None,
            name: "nope".into(),
            version: "0.0.0".into(),
        };
        d.fetch_artifact("rust-prod", id);
        assert!(!d.artifact.found);
        assert!(d.artifact.error.is_none());
    }

    #[test]
    fn fetch_transport_error_is_surfaced() {
        let mut d = ui(FakeHolger {
            fail: true,
            ..Default::default()
        });
        let id = ArtifactId {
            namespace: None,
            name: "serde".into(),
            version: "1.0.0".into(),
        };
        d.fetch_artifact("rust-prod", id);
        assert!(!d.artifact.found);
        assert_eq!(d.artifact.error.as_deref(), Some("boom"));
    }

    #[test]
    fn put_rejected_on_read_only_repo() {
        let d = ui(FakeHolger {
            repos: vec![repo("rust-prod", false)],
            ..Default::default()
        });
        let id = ArtifactId {
            namespace: None,
            name: "mycrate".into(),
            version: "0.1.0".into(),
        };
        let err = d.put_artifact("rust-prod", &id, b"bytes").unwrap_err();
        assert!(err.to_string().contains("read-only"));
    }

    #[test]
    fn put_succeeds_on_writable_repo() {
        let d = ui(FakeHolger {
            repos: vec![repo("rust-dev", true)],
            ..Default::default()
        });
        let id = ArtifactId {
            namespace: None,
            name: "mycrate".into(),
            version: "0.1.0".into(),
        };
        d.put_artifact("rust-dev", &id, b"bytes").unwrap();
    }

    #[test]
    fn combined_state_json_has_all_three_views() {
        let d = ui(FakeHolger::default());
        let s = d.state_json();
        assert!(s.get("status").is_some());
        assert!(s.get("repos").is_some());
        assert!(s.get("artifact").is_some());
        assert!(s.get("browse").is_some());
        assert!(s.get("archive").is_some());
    }

    #[test]
    fn archive_lists_files_and_stats() {
        let mut d = ui(FakeHolger::default());

        // Known archive-backed repo: stats + file paths populate the view.
        d.refresh_archive("rust-arch", None);
        assert!(d.archive.error.is_none(), "archive error: {:?}", d.archive.error);
        assert_eq!(d.archive.repository, "rust-arch");
        assert_eq!(d.archive.file_count, 3);
        assert_eq!(d.archive.total_uncompressed_bytes, 600);
        assert_eq!(d.archive.archive_path, "rust-arch");
        assert_eq!(d.archive.files.len(), 3);
        assert_eq!(d.archive.files[0], "crates/serde-1.0.0.crate");

        // A path prefix narrows the listing (stats stay whole-archive).
        d.refresh_archive("rust-arch", Some("index/".into()));
        assert_eq!(d.archive.files, vec!["index/config.json".to_string()]);
        assert_eq!(d.archive.file_count, 3);

        // state_json carries the files + stats.
        let s = d.archive.state_json();
        assert_eq!(s["repository"], json!("rust-arch"));
        assert_eq!(s["file_count"], json!(3));

        // An unknown / non-archive repo is empty, not an error.
        d.refresh_archive("does-not-exist", None);
        assert!(d.archive.error.is_none());
        assert!(d.archive.files.is_empty());
        assert_eq!(d.archive.file_count, 0);
    }

    #[test]
    fn archive_transport_error_is_surfaced() {
        let mut d = ui(FakeHolger {
            fail: true,
            ..Default::default()
        });
        d.refresh_archive("rust-arch", None);
        assert_eq!(d.archive.error.as_deref(), Some("boom"));
        assert!(d.archive.files.is_empty());
    }

    #[test]
    fn browse_lists_artifacts_for_repo() {
        let mut listings = HashMap::new();
        listings.insert(
            "rust-prod".to_string(),
            vec![entry("serde", "1.0.0", 100), entry("tokio", "1.2.0", 200)],
        );
        let mut d = ui(FakeHolger {
            listings,
            ..Default::default()
        });

        d.refresh_browse("rust-prod", None);
        assert!(d.browse.error.is_none());
        assert_eq!(d.browse.repository, "rust-prod");
        assert_eq!(d.browse.entries.len(), 2);
        assert_eq!(d.browse.entries[0].name, "serde");
        assert_eq!(d.browse.entries[0].size_bytes, 100);
        assert_eq!(d.browse.entries[1].name, "tokio");

        // name_filter narrows by substring.
        d.refresh_browse("rust-prod", Some("ser".into()));
        assert_eq!(d.browse.entries.len(), 1);
        assert_eq!(d.browse.entries[0].name, "serde");

        // state_json carries the entries.
        let s = d.browse.state_json();
        assert_eq!(s["repository"], json!("rust-prod"));
        assert_eq!(s["entries"][0]["name"], json!("serde"));
    }

    #[test]
    fn browse_unknown_repo_is_empty_not_error() {
        let mut d = ui(FakeHolger::default());
        d.refresh_browse("does-not-exist", None);
        assert!(d.browse.error.is_none());
        assert!(d.browse.entries.is_empty());
        assert_eq!(d.browse.next_page_token, "");
    }
}