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
//! egui presentation for the holger UI, built from [facett] components.
//!
//! One [`UiData`] drives everything; each tab issues at most one blocking core
//! call per click (the nornir-viz idiom). The repo list is rendered with a
//! `facett::table::Table` facet; the rest is plain themed egui. Selection +
//! every visible value live in [`UiData`]'s views, which expose `state_json()`
//! — so the same screen can be asserted headlessly.

use eframe::egui;
use egui::Ui;
use facett::look::Theme as LookTheme; // the unified facett look & feel (one preset/frame)
use facett::table::Table;
use facett::Facet;
use serde_json::{json, Value};
use traits::ArtifactId;

use crate::data::UiData;

/// The default look preset for holger-ui: the running-OS-matched preset's index
/// into [`LookTheme::PRESETS`] (Windows L/D, macOS L/D, Device). Linux/unknown →
/// Windows-dark (facett's documented default). Pure → unit-testable with no
/// window, the same shape korp uses.
pub fn default_look_preset() -> usize {
    let want = LookTheme::from_os(egui::os::OperatingSystem::from_target_os()).name;
    LookTheme::preset_names().iter().position(|n| *n == want).unwrap_or(1)
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Tab {
    Status,
    Repos,
    Browse,
    Archive,
    Artifact,
    Upload,
}

/// The holger UI application: a [`UiData`] handle + the tab's input fields.
pub struct HolgerUiApp {
    data: UiData,
    tab: Tab,
    repo: String,
    namespace: String,
    name: String,
    version: String,
    upload_path: String,
    notice: Option<String>,
    /// Active look preset — an index into [`LookTheme::PRESETS`]. The app applies
    /// this preset every frame; `apply` installs the full egui Style AND publishes
    /// the derived legacy palette so the facett Table facets re-theme coherently
    /// (COH-1). Replaces the old `facett::Theme::sci_fi()` call.
    look_preset: usize,
}

impl HolgerUiApp {
    /// Build the app over a connected data layer and prime the first views.
    pub fn new(mut data: UiData) -> Self {
        data.refresh_status();
        data.refresh_repos();
        let repo = data
            .repos
            .selected_repo()
            .map(|r| r.name.clone())
            .unwrap_or_default();
        Self {
            data,
            tab: Tab::Status,
            repo,
            namespace: String::new(),
            name: String::new(),
            version: String::new(),
            upload_path: String::new(),
            notice: None,
            look_preset: default_look_preset(),
        }
    }

    // ── look & feel (unified `facett::look::Theme`) ─────────────────────────────

    /// The active look preset's [`LookTheme`].
    pub fn look_theme(&self) -> LookTheme {
        let presets = LookTheme::PRESETS;
        presets[self.look_preset.min(presets.len() - 1)]()
    }

    /// Switch the active look preset (clamped); returns the new preset name.
    pub fn set_look_preset(&mut self, idx: usize) -> String {
        self.look_preset = idx.min(LookTheme::PRESETS.len() - 1);
        self.look_theme().name
    }

    /// Apply the active preset to `ctx` — installs the full egui Style and
    /// publishes the derived legacy palette so the facett Table facets follow
    /// (COH-1). Re-applying takes effect next frame, no restart.
    pub fn apply_look(&self, ctx: &egui::Context) {
        self.look_theme().apply(ctx);
    }

    /// The look state the operator sees, as observable JSON for headless robot
    /// tests: the active preset name, the full preset roster, and the resolved
    /// legacy palette (the colours every facett view actually paints with). This
    /// is what proves "the active preset + a coherent palette" without a screen.
    pub fn look_state_json(&self) -> Value {
        let theme = self.look_theme();
        let pal = theme.to_legacy_palette();
        let hex = |c: egui::Color32| format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b());
        json!({
            "preset": theme.name,
            "preset_index": self.look_preset,
            "presets": LookTheme::preset_names(),
            "dark": theme.is_dark(),
            "palette": {
                "bg": hex(pal.bg),
                "text": hex(pal.text),
                "text_dim": hex(pal.text_dim),
                "accent": hex(pal.accent),
                "panel_bg": hex(pal.panel_bg),
                "node_fill": hex(pal.node_fill),
            },
        })
    }

    fn status_tab(&mut self, ui: &mut Ui) {
        if ui.button("⟳ refresh").clicked() {
            self.data.refresh_status();
        }
        ui.separator();
        let s = &self.data.status;
        if let Some(err) = &s.error {
            ui.colored_label(egui::Color32::RED, format!("error: {err}"));
        }
        egui::Grid::new("status_grid").striped(true).show(ui, |ui| {
            ui.label("status");
            ui.label(if s.status.is_empty() { "" } else { &s.status });
            ui.end_row();
            ui.label("version");
            ui.label(if s.version.is_empty() { "" } else { &s.version });
            ui.end_row();
            ui.label("uptime (s)");
            ui.label(s.uptime_seconds.to_string());
            ui.end_row();
        });
    }

    fn repos_tab(&mut self, ui: &mut Ui) {
        if ui.button("⟳ refresh").clicked() {
            self.data.refresh_repos();
        }
        ui.separator();
        if let Some(err) = &self.data.repos.error {
            ui.colored_label(egui::Color32::RED, format!("error: {err}"));
        }

        // Selection row (collect first so we don't hold a borrow across the click).
        let entries: Vec<(usize, String)> = self
            .data
            .repos
            .repos
            .iter()
            .enumerate()
            .map(|(i, r)| (i, r.name.clone()))
            .collect();
        let selected = self.data.repos.selected;
        let mut clicked = None;
        ui.horizontal_wrapped(|ui| {
            for (i, name) in &entries {
                if ui.selectable_label(selected == Some(*i), name).clicked() {
                    clicked = Some(*i);
                }
            }
        });
        if let Some(i) = clicked {
            self.data.select_repo(i);
            self.repo = entries[i].1.clone();
        }

        ui.separator();
        // facett Table facet for the repo×capability grid.
        let mut table = Table::new(
            "repositories",
            vec![
                "name".into(),
                "type".into(),
                "writable".into(),
                "archive".into(),
            ],
        );
        for r in &self.data.repos.repos {
            table.push_row(vec![
                r.name.clone(),
                r.repo_type.clone(),
                r.writable.to_string(),
                r.has_archive.to_string(),
            ]);
        }
        if let Some(sel) = self.data.repos.selected {
            table.select_row(sel);
        }
        table.ui(ui);
    }

    fn browse_tab(&mut self, ui: &mut Ui) {
        // Snapshot the selected repo name to a local String before mutating
        // `self.data` (the refresh borrows it mutably).
        let target = self
            .data
            .repos
            .selected_repo()
            .map(|r| r.name.clone());
        ui.label(format!(
            "browsing repo: {}",
            target.clone().unwrap_or_else(|| "(none selected)".into())
        ));
        let do_refresh = ui
            .add_enabled(target.is_some(), egui::Button::new("⟳ refresh"))
            .clicked();
        if do_refresh {
            if let Some(repo) = target {
                self.data.refresh_browse(&repo, None);
            }
        }
        ui.separator();
        if let Some(err) = &self.data.browse.error {
            ui.colored_label(egui::Color32::RED, format!("error: {err}"));
        }

        // facett Table facet for the artifact listing.
        let mut table = Table::new(
            "browse",
            vec![
                "name".into(),
                "version".into(),
                "size".into(),
                "type".into(),
            ],
        );
        for e in &self.data.browse.entries {
            table.push_row(vec![
                e.name.clone(),
                e.version.clone(),
                e.size_bytes.to_string(),
                e.content_type.clone(),
            ]);
        }
        table.ui(ui);

        // Pagination footer: count + a load-more button when the listing has a
        // continuation token.
        ui.separator();
        let loaded = self.data.browse.entries.len();
        let has_more = !self.data.browse.next_page_token.is_empty();
        ui.horizontal(|ui| {
            ui.label(format!(
                "{loaded} shown{}",
                if has_more { " (more available)" } else { "" }
            ));
            if has_more && ui.button("load more").clicked() {
                self.data.load_more_browse();
            }
        });
    }

    fn archive_tab(&mut self, ui: &mut Ui) {
        // Snapshot the selected repo name to a local String before mutating
        // `self.data` (refresh_archive borrows it mutably).
        let target = self
            .data
            .repos
            .selected_repo()
            .map(|r| r.name.clone());
        ui.label(format!(
            "archive of repo: {}",
            target.clone().unwrap_or_else(|| "(none selected)".into())
        ));
        let do_refresh = ui
            .add_enabled(target.is_some(), egui::Button::new("⟳ refresh"))
            .clicked();
        if do_refresh {
            if let Some(repo) = target {
                self.data.refresh_archive(&repo, None);
            }
        }
        ui.separator();
        if let Some(err) = &self.data.archive.error {
            ui.colored_label(egui::Color32::RED, format!("error: {err}"));
        }

        // Archive stats (file count / total uncompressed bytes / archive name).
        let a = &self.data.archive;
        egui::Grid::new("archive_stats").striped(true).show(ui, |ui| {
            ui.label("files");
            ui.label(a.file_count.to_string());
            ui.end_row();
            ui.label("uncompressed bytes");
            ui.label(a.total_uncompressed_bytes.to_string());
            ui.end_row();
            ui.label("archive");
            ui.label(if a.archive_path.is_empty() {
                ""
            } else {
                &a.archive_path
            });
            ui.end_row();
        });
        ui.separator();

        // facett Table facet for the raw archive file paths (single column).
        let mut table = Table::new("archive", vec!["path".into()]);
        for path in &self.data.archive.files {
            table.push_row(vec![path.clone()]);
        }
        table.ui(ui);
    }

    fn artifact_tab(&mut self, ui: &mut Ui) {
        egui::Grid::new("artifact_inputs").show(ui, |ui| {
            ui.label("repository");
            ui.text_edit_singleline(&mut self.repo);
            ui.end_row();
            ui.label("namespace");
            ui.text_edit_singleline(&mut self.namespace);
            ui.end_row();
            ui.label("name");
            ui.text_edit_singleline(&mut self.name);
            ui.end_row();
            ui.label("version");
            ui.text_edit_singleline(&mut self.version);
            ui.end_row();
        });
        if ui.button("fetch").clicked() {
            let id = ArtifactId {
                namespace: if self.namespace.is_empty() {
                    None
                } else {
                    Some(self.namespace.clone())
                },
                name: self.name.clone(),
                version: self.version.clone(),
            };
            let repo = self.repo.clone();
            self.data.fetch_artifact(&repo, id);
        }
        ui.separator();
        let a = &self.data.artifact;
        if let Some(err) = &a.error {
            ui.colored_label(egui::Color32::RED, format!("error: {err}"));
        } else if a.repository.is_empty() {
            ui.label("enter an artifact id and fetch");
        } else if a.found {
            ui.label(format!(
                "{} / {} {}{} bytes ({})",
                a.repository, a.name, a.version, a.size_bytes, a.content_type
            ));
        } else {
            ui.colored_label(egui::Color32::YELLOW, "not found");
        }
    }

    fn upload_tab(&mut self, ui: &mut Ui) {
        let writable = self.data.repos.upload_enabled();
        let target = self.data.repos.selected_repo().map(|r| r.name.clone());
        ui.label(format!(
            "target repo: {}",
            target.clone().unwrap_or_else(|| "(none selected)".into())
        ));
        if !writable {
            ui.colored_label(
                egui::Color32::YELLOW,
                "selected repo is read-only — pick a writable repo on the Repos tab",
            );
        }
        egui::Grid::new("upload_inputs").show(ui, |ui| {
            ui.label("name");
            ui.text_edit_singleline(&mut self.name);
            ui.end_row();
            ui.label("version");
            ui.text_edit_singleline(&mut self.version);
            ui.end_row();
            ui.label("file path");
            ui.text_edit_singleline(&mut self.upload_path);
            ui.end_row();
        });
        let do_upload = ui
            .add_enabled(writable, egui::Button::new("upload"))
            .clicked();
        if do_upload {
            if let Some(repo) = target {
                match std::fs::read(&self.upload_path) {
                    Ok(bytes) => {
                        let id = ArtifactId {
                            namespace: None,
                            name: self.name.clone(),
                            version: self.version.clone(),
                        };
                        self.notice = Some(match self.data.put_artifact(&repo, &id, &bytes) {
                            Ok(()) => format!("uploaded {} bytes to {repo}", bytes.len()),
                            Err(e) => format!("upload failed: {e}"),
                        });
                    }
                    Err(e) => self.notice = Some(format!("read failed: {e}")),
                }
            }
        }
        if let Some(n) = &self.notice {
            ui.separator();
            ui.label(n);
        }
    }
}

impl eframe::App for HolgerUiApp {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        // Unified look & feel: install the active preset's full egui Style +
        // publish its derived legacy palette so every facett Table re-themes
        // coherently (COH-1). Replaces the old per-crate `Theme::sci_fi()`.
        self.apply_look(&ui.ctx().clone());

        egui::Panel::top("tabs").show_inside(ui, |ui| {
            ui.horizontal(|ui| {
                ui.heading("holger");
                ui.separator();
                ui.selectable_value(&mut self.tab, Tab::Status, "Status");
                ui.selectable_value(&mut self.tab, Tab::Repos, "Repos");
                ui.selectable_value(&mut self.tab, Tab::Browse, "Browse");
                ui.selectable_value(&mut self.tab, Tab::Archive, "Archive");
                ui.selectable_value(&mut self.tab, Tab::Artifact, "Artifact");
                ui.selectable_value(&mut self.tab, Tab::Upload, "Upload");
            });
            // The look-&-feel preset switcher (Windows/macOS/Device, light+dark).
            ui.horizontal(|ui| {
                ui.label("look:")
                    .on_hover_text("Unified facett look & feel — re-themes every view");
                let names = LookTheme::preset_names();
                let mut pick = None;
                for (i, name) in names.iter().enumerate() {
                    if ui.selectable_label(self.look_preset == i, name).clicked() {
                        pick = Some(i);
                    }
                }
                if let Some(i) = pick {
                    self.set_look_preset(i);
                }
            });
        });
        egui::CentralPanel::default().show_inside(ui, |ui| match self.tab {
            Tab::Status => self.status_tab(ui),
            Tab::Repos => self.repos_tab(ui),
            Tab::Browse => self.browse_tab(ui),
            Tab::Archive => self.archive_tab(ui),
            Tab::Artifact => self.artifact_tab(ui),
            Tab::Upload => self.upload_tab(ui),
        });
    }
}

#[cfg(test)]
#[allow(deprecated)] // ctx.style()/run + CentralPanel::show are the headless-render path (mirrors facett's harness)
mod look_tests {
    //! Robot-UI cell for the unified facett look & feel (the "all consumers,
    //! holger too" migration). Runs only under `--features gui` (where `app`
    //! compiles). It drives the *real* holger-ui app's look surface headlessly and
    //! asserts its observable state — the active preset + a coherent palette — and
    //! that switching the preset actually re-themes every facett view via the
    //! published legacy palette (COH-1). No display, no GPU.
    //!
    //! LAW: inject real input + assert real output. We inject a concrete preset
    //! index (a "click" on the look switcher) and assert the rendered palette
    //! changes accordingly and that egui picked up the new style — never just
    //! "didn't panic".

    use super::*;
    use server_lib::exposed::fast_routes::FastRoutes;
    use server_lib::LocalHolger;
    use traits::HolgerObject;

    /// Emit one functional-status row for a real check. Gated behind
    /// `--features testmatrix` (this module already requires `gui`) so release
    /// builds strip it (the dep is optional).
    #[cfg(feature = "testmatrix")]
    fn fstatus(component: &str, check: &str, ok: bool, detail: &str) {
        nornir_testmatrix::functional_status(component, check, ok, detail);
    }

    /// A holger-ui app over an empty (no-repo) LocalHolger — enough to exercise
    /// the look surface, which is independent of the data layer.
    fn app() -> HolgerUiApp {
        let routes = FastRoutes::new(Vec::new());
        let holger: std::sync::Arc<dyn HolgerObject> = std::sync::Arc::new(LocalHolger::new(routes));
        let data = UiData::new(holger).expect("runtime");
        HolgerUiApp::new(data)
    }

    /// The look surface exposes exactly the facett preset roster, and the default
    /// preset is the OS-resolved one (Linux/unknown → windows-dark) — the value an
    /// operator would see selected on first launch.
    #[test]
    fn default_preset_is_os_resolved_and_roster_is_facett_presets() {
        let app = app();
        let s = app.look_state_json();

        // The roster the switcher renders is facett's canonical preset list.
        let presets = s["presets"].as_array().expect("look state has a presets roster");
        assert_eq!(
            presets.len(),
            LookTheme::PRESETS.len(),
            "the look switcher lists every facett preset: {s}"
        );

        // The active preset is the OS-resolved default and matches the index.
        let want = LookTheme::PRESETS[default_look_preset()]().name;
        assert_eq!(s["preset"], want, "first-launch preset is the OS default: {s}");
        assert_eq!(s["preset_index"].as_u64(), Some(default_look_preset() as u64));

        #[cfg(feature = "testmatrix")]
        fstatus(
            "holger-ui",
            "look_default_preset_and_roster",
            presets.len() == LookTheme::PRESETS.len()
                && s["preset"] == want
                && s["preset_index"].as_u64() == Some(default_look_preset() as u64),
            &format!("roster {} presets, OS default = {}", presets.len(), want),
        );
    }

    /// Injecting a preset switch (the operator clicking "device") changes the
    /// active preset AND the resolved palette the facett views paint with — proof
    /// the migration re-themes coherently, not just that it stored an index.
    #[test]
    fn switching_preset_rethemes_the_resolved_palette() {
        let mut app = app();

        // Find the device + a windows preset by name so the test is order-stable.
        let names = LookTheme::preset_names();
        let device = names.iter().position(|n| n == "device").expect("device preset exists");
        let win_dark = names.iter().position(|n| n == "windows-dark").expect("windows-dark exists");

        // Drive: select windows-dark, capture its palette.
        let name = app.set_look_preset(win_dark);
        assert_eq!(name, "windows-dark");
        let win_state = app.look_state_json();
        let win_bg = win_state["palette"]["bg"].clone();

        // Drive: select device (a click on the switcher), capture its palette.
        let name = app.set_look_preset(device);
        assert_eq!(name, "device");
        let dev_state = app.look_state_json();

        // Observe: the active preset + a different, fully-populated palette.
        assert_eq!(dev_state["preset"], "device", "active preset switched: {dev_state}");
        let dev_bg = dev_state["palette"]["bg"].clone();
        assert_ne!(win_bg, dev_bg, "device must paint a different surface than windows-dark");

        // The palette is coherent — every role is a real hex colour, none empty.
        let roles = ["bg", "text", "text_dim", "accent", "panel_bg", "node_fill"];
        for role in roles {
            let c = dev_state["palette"][role].as_str().unwrap_or("");
            assert!(
                c.starts_with('#') && c.len() == 7,
                "palette role `{role}` must be a #rrggbb colour, got {c:?}: {dev_state}"
            );
        }
        let all_hex = roles.iter().all(|role| {
            let c = dev_state["palette"][role].as_str().unwrap_or("");
            c.starts_with('#') && c.len() == 7
        });
        let _ = all_hex;

        #[cfg(feature = "testmatrix")]
        fstatus(
            "holger-ui",
            "look_switch_rethemes_palette",
            dev_state["preset"] == "device" && win_bg != dev_bg && all_hex,
            &format!("windows-dark bg={win_bg} != device bg={dev_bg}, all 6 roles #rrggbb={all_hex}"),
        );
    }

    /// `apply` installs the preset's full egui Style AND publishes the derived
    /// legacy palette into the context, so every facett component (the Table
    /// facets) follows with no per-view wiring (COH-1). We apply headlessly and
    /// read the published palette back through `facett::theme(ui)`.
    #[test]
    fn apply_publishes_the_coherent_legacy_palette_into_egui() {
        let mut app = app();
        let device = LookTheme::preset_names().iter().position(|n| n == "device").unwrap();
        app.set_look_preset(device);

        let ctx = egui::Context::default();
        app.apply_look(&ctx);

        // The egui Style picked up the preset's spacing (not egui's default).
        let theme = app.look_theme();
        assert_eq!(
            ctx.style().spacing.item_spacing,
            theme.metrics.item_spacing_vec(),
            "apply installed the preset's spacing into the egui Style"
        );

        // The legacy palette every facett view reads is the device preset's.
        let mut got = String::new();
        let _ = ctx.run(egui::RawInput::default(), |ctx| {
            egui::CentralPanel::default().show(ctx, |ui| {
                got = facett::theme(ui).name.to_string();
            });
        });
        assert_eq!(got, "device", "facett views resolve the applied preset's palette");

        #[cfg(feature = "testmatrix")]
        fstatus(
            "holger-ui",
            "look_apply_publishes_legacy_palette",
            ctx.style().spacing.item_spacing == theme.metrics.item_spacing_vec() && got == "device",
            &format!("egui spacing matches preset; facett::theme resolves \"{got}\""),
        );
    }
}