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
//! 🧬 **`nornir` root pane** — the server/root operations that are *not*
//! workspace-scoped data views: workspace **lifecycle** (Add / Kill), **Populate**
//! and **Refresh/Poll-now**, plus the server **status / version**.
//!
//! Every other pane is a *view onto one workspace's data*; this one is where a
//! workspace is born and where it dies. (The user notes it could equally have
//! been called "server" — it holds the root, server-level operations.)
//!
//! # Operation layout (decision: ops live in the pane they belong to)
//! * **Add workspace** — form (name + descriptor path/URL + mode + poll) →
//! `Workspaces.Register` (eager populate). CLI: `nornir workspace add`.
//! * **Kill workspace** — a confirm-gated de-register → `Workspaces.Remove`.
//! CLI: `nornir workspace rm`.
//! * **Populate** — clone members now, build async → `Workspaces.Fetch{background}`.
//! CLI: `nornir workspace populate`.
//! * **Refresh / Poll-now** — force a fetch+rebuild now → `Workspaces.Fetch{force}`.
//! CLI: `nornir workspace fetch`.
//! * **Server status** — `Health.Ping` (version + repo count + status).
//!
//! All are **remote-only** (they drive a running `nornir-server`); in local mode
//! the pane shows the same one-line hint as the other server-backed panes.
//!
//! Follows the facett discovery contract the test matrix walks: a `*View`-named
//! type with `local()`/`remote()` ctors, a [`state_json`](NornirRootView::state_json)
//! that reports every button + form field + last result (LAW #6 — "see what the
//! user sees" as data), so the headless matrix mechanically discovers the pane and
//! its operations.
use std::path::PathBuf;
use eframe::egui::{self};
use super::action_log::{ActionLog, Kind};
use super::facett_theme::{Theme, GREEN, RED};
use super::ops_tabs::Server;
use super::remote;
use crate::warehouse::clone_events::CloneEventRow;
/// 🧬 The `nornir` root pane state. Remote-only; holds the Add-workspace form,
/// the kill-confirm latch, and the last result of each root operation so the
/// rendered outcome survives between frames and is reported in `state_json`.
pub struct NornirRootView {
/// Add-workspace form fields.
new_name: String,
new_descriptor: String,
new_mode: String, // "monitored" | "pushed" | "external"
new_poll: String,
/// The workspace selected for the (confirm-gated) Kill button.
kill_target: String,
/// Two-step confirm latch for Kill (a destructive root op).
kill_armed: bool,
/// Last result of each operation (rendered + reported), `Ok(msg)`/`Err(msg)`.
last_add: Option<Result<String, String>>,
last_kill: Option<Result<String, String>>,
last_populate: Option<Result<String, String>>,
last_refresh: Option<Result<String, String>>,
/// Cached `Health.Ping` server identity, fetched on demand.
server_info: Option<Result<remote::ServerInfo, String>>,
/// PLAN #6: cached per-member populate status (`clone_events`) for the active
/// workspace — `Ok(rows)` newest-first, or the load error. Loaded on demand via
/// `Viz.CloneEvents` (remote) or the local warehouse (local mode).
clone_events: Option<Result<Vec<CloneEventRow>, String>>,
/// The workspace the cached `clone_events` belong to (so a workspace switch
/// invalidates the cache).
clone_events_ws: String,
theme: Theme,
}
impl Default for NornirRootView {
fn default() -> Self {
Self {
new_name: String::new(),
new_descriptor: String::new(),
new_mode: "monitored".into(),
new_poll: "60s".into(),
kill_target: String::new(),
kill_armed: false,
last_add: None,
last_kill: None,
last_populate: None,
last_refresh: None,
server_info: None,
clone_events: None,
clone_events_ws: String::new(),
theme: Theme::default(),
}
}
}
impl NornirRootView {
/// Local-warehouse ctor (no server → the pane shows the server-backed hint).
pub fn local() -> Self {
Self::default()
}
/// Remote (thin-client) ctor — identical state; the live `Server` handle is
/// passed per-frame to [`draw`](Self::draw), mirroring the other ops panes.
pub fn remote() -> Self {
Self::default()
}
/// Re-skin with a facett palette (broadcast from the top-bar picker).
pub fn set_palette(&mut self, t: Theme) {
self.theme = t;
}
/// Render the root pane. `srv` is `None` in local mode (shows the hint).
/// `workspaces` is the current picker list (the kill-target choices).
/// Returns `true` when an operation mutated the server's workspace set (Add /
/// Kill / Populate / Refresh succeeded) so the caller can re-list workspaces +
/// reload the view immediately, the same contract `WorkspacePanel::draw_controls`
/// uses for ⟳ Sync now.
#[must_use]
pub fn draw(
&mut self,
ui: &mut egui::Ui,
srv: Option<&Server>,
workspaces: &[String],
active_ws: &str,
local_warehouse: Option<&PathBuf>,
log: &ActionLog,
) -> bool {
let theme = self.theme;
ui.heading("🧬 nornir — server & workspace operations");
// ── Populate status (clone_events, PLAN #6) ──────────────────────────
// Works in BOTH modes: remote reads `Viz.CloneEvents`, local reads the
// workspace warehouse (lock-tolerant). Shows per-member ok/failed + the
// error detail + when, so a thin client sees *why* a member didn't
// populate instead of only missing data.
self.draw_populate_status(ui, srv, active_ws, local_warehouse, log);
let Some(srv) = srv else {
ui.add_space(20.0);
ui.label(
"The nornir root pane's lifecycle ops are server-backed — launch the viz against \
a running nornir-server (NORNIR_SERVER=…) to add/kill/populate workspaces.",
);
return false;
};
let mut mutated = false;
// ── Server status (Health.Ping) ──────────────────────────────────────
ui.separator();
ui.horizontal(|ui| {
ui.strong("server:");
if ui.button("⟳ status").on_hover_text("Health.Ping — version + repo count").clicked() {
log.push(Kind::Rpc, "Health.Ping".to_string());
self.server_info =
Some(remote::ping(&srv.endpoint, &srv.token).map_err(|e| format!("{e:#}")));
}
match &self.server_info {
Some(Ok(i)) => {
ui.colored_label(
GREEN,
format!("{} · nornir {} · {} repo(s)", i.status, i.version, i.repo_count),
);
}
Some(Err(e)) => { ui.colored_label(RED, e); }
None => { ui.colored_label(theme.text_dim, format!("{}", srv.endpoint)); }
}
});
// ── Add workspace (Workspaces.Register, eager populate) ───────────────
ui.separator();
ui.strong("âž• add workspace");
egui::Grid::new("nornir_add_ws").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| {
ui.label("name:");
ui.add(egui::TextEdit::singleline(&mut self.new_name).desired_width(220.0).hint_text("workspace name"));
ui.end_row();
ui.label("descriptor:");
ui.add(
egui::TextEdit::singleline(&mut self.new_descriptor)
.desired_width(360.0)
.hint_text("server-readable nornir-workspace.toml path/URL"),
);
ui.end_row();
ui.label("mode:");
egui::ComboBox::from_id_salt("nornir_add_mode")
.selected_text(self.new_mode.clone())
.show_ui(ui, |ui| {
for m in ["monitored", "pushed", "external"] {
ui.selectable_value(&mut self.new_mode, m.to_string(), m);
}
});
ui.end_row();
ui.label("poll:");
ui.add(egui::TextEdit::singleline(&mut self.new_poll).desired_width(100.0).hint_text("60s"));
ui.end_row();
});
if ui
.button("âž• Add workspace")
.on_hover_text("Workspaces.Register (eager populate) — CLI: nornir workspace add")
.clicked()
&& !self.new_name.trim().is_empty()
{
log.push(Kind::Rpc, format!("Workspaces.Register name={}", self.new_name));
self.last_add = Some(
remote::register_workspace(
&srv.endpoint,
&srv.token,
self.new_name.trim(),
self.new_descriptor.trim(),
&self.new_mode,
self.new_poll.trim(),
)
.map(|(name, mode, members)| format!("registered `{name}` ({mode}, {members} member(s))"))
.map_err(|e| format!("{e:#}")),
);
mutated |= matches!(self.last_add, Some(Ok(_)));
}
result_line(ui, theme, &self.last_add);
// ── Kill workspace (Workspaces.Remove, confirm-gated) ─────────────────
ui.separator();
ui.strong("🗑 kill workspace");
if self.kill_target.is_empty() {
self.kill_target = workspaces.first().cloned().unwrap_or_default();
}
ui.horizontal(|ui| {
egui::ComboBox::from_id_salt("nornir_kill_target")
.selected_text(if self.kill_target.is_empty() { "—".into() } else { self.kill_target.clone() })
.show_ui(ui, |ui| {
for w in workspaces {
ui.selectable_value(&mut self.kill_target, w.clone(), w);
}
});
if !self.kill_armed {
if ui.button("🗑 Kill…").clicked() && !self.kill_target.trim().is_empty() {
self.kill_armed = true;
}
} else {
ui.colored_label(RED, format!("âš remove `{}`?", self.kill_target));
if ui.button("✓ confirm kill").clicked() {
log.push(Kind::Rpc, format!("Workspaces.Remove name={}", self.kill_target));
self.last_kill = Some(
remote::remove_workspace(&srv.endpoint, &srv.token, self.kill_target.trim())
.map(|()| format!("removed `{}`", self.kill_target))
.map_err(|e| format!("{e:#}")),
);
mutated |= matches!(self.last_kill, Some(Ok(_)));
self.kill_armed = false;
}
if ui.button("✕ cancel").clicked() {
self.kill_armed = false;
}
}
});
result_line(ui, theme, &self.last_kill);
// ── Populate + Refresh/Poll-now (Workspaces.Fetch) ────────────────────
ui.separator();
ui.strong("🔄 populate / refresh");
ui.horizontal(|ui| {
let target = if self.kill_target.is_empty() {
workspaces.first().cloned().unwrap_or_default()
} else {
self.kill_target.clone()
};
if ui
.button("⬇ Populate")
.on_hover_text("Workspaces.Fetch{background} — clone members now, build async (CLI: nornir workspace populate)")
.clicked()
&& !target.trim().is_empty()
{
log.push(Kind::Rpc, format!("Workspaces.Fetch(background) name={target}"));
self.last_populate = Some(
fetch(&srv.endpoint, &srv.token, &target, false, true)
.map_err(|e| format!("{e:#}")),
);
mutated |= matches!(self.last_populate, Some(Ok(_)));
}
if ui
.button("⟳ Refresh / poll-now")
.on_hover_text("Workspaces.Fetch{force} — poll + rebuild this workspace now (CLI: nornir workspace fetch)")
.clicked()
&& !target.trim().is_empty()
{
log.push(Kind::Rpc, format!("Workspaces.Fetch(force) name={target}"));
self.last_refresh = Some(
fetch(&srv.endpoint, &srv.token, &target, true, false)
.map_err(|e| format!("{e:#}")),
);
mutated |= matches!(self.last_refresh, Some(Ok(_)));
}
});
result_line(ui, theme, &self.last_populate);
result_line(ui, theme, &self.last_refresh);
mutated
}
/// PLAN #6: render the per-member **populate status** for `active_ws` — the
/// `clone_events` outcomes (ok / failed + error detail + when). Loaded on
/// demand (a ⟳ button), and auto-loaded once when the active workspace
/// changes, so a thin client sees *why* a member didn't populate.
fn draw_populate_status(
&mut self,
ui: &mut egui::Ui,
srv: Option<&Server>,
active_ws: &str,
local_warehouse: Option<&PathBuf>,
log: &ActionLog,
) {
let theme = self.theme;
ui.separator();
ui.horizontal(|ui| {
ui.strong("🩺 populate status");
ui.colored_label(theme.text_dim, active_ws);
if ui
.button("⟳ load")
.on_hover_text("clone_events — per-member populate outcomes (Viz.CloneEvents / local warehouse)")
.clicked()
{
log.push(Kind::Rpc, format!("Viz.CloneEvents workspace={active_ws}"));
self.clone_events = Some(load_clone_events(srv, active_ws, local_warehouse));
self.clone_events_ws = active_ws.to_string();
}
});
// Auto-load once on a workspace switch (or first paint) so the pane shows
// status without a manual click — matches the other data panes.
if self.clone_events.is_none() || self.clone_events_ws != active_ws {
self.clone_events = Some(load_clone_events(srv, active_ws, local_warehouse));
self.clone_events_ws = active_ws.to_string();
}
match &self.clone_events {
Some(Ok(rows)) if rows.is_empty() => {
ui.colored_label(theme.text_dim, "no clone/populate events recorded yet");
}
Some(Ok(rows)) => {
let failed = rows.iter().filter(|r| r.status == "error").count();
if failed == 0 {
ui.colored_label(GREEN, format!("✓ all {} member event(s) ok", rows.len()));
} else {
ui.colored_label(RED, format!("✗ {failed} member(s) failed to populate"));
}
egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| {
egui::Grid::new("nornir_clone_events").num_columns(4).striped(true).spacing([12.0, 2.0]).show(ui, |ui| {
ui.strong("member"); ui.strong("op"); ui.strong("status"); ui.strong("detail");
ui.end_row();
for r in rows.iter().take(50) {
ui.label(&r.member);
ui.label(&r.op);
if r.status == "error" {
ui.colored_label(RED, "✗ error");
} else {
ui.colored_label(GREEN, "✓ ok");
}
ui.label(&r.detail);
ui.end_row();
}
});
});
}
Some(Err(e)) => { ui.colored_label(RED, format!("✗ {e}")); }
None => {}
}
}
/// The `nornir` pane's slice of `state_json` (LAW #6): every button this pane
/// hosts (so the matrix can mechanically discover the new operation surface),
/// the Add-workspace form's current field values, the kill-confirm state, and
/// the last result of each root operation. No "TODO"/"not wired" sentinels.
pub fn state_json(&self) -> serde_json::Value {
let res = |r: &Option<Result<String, String>>| match r {
None => serde_json::json!({ "ran": false }),
Some(Ok(m)) => serde_json::json!({ "ran": true, "ok": true, "message": m }),
Some(Err(e)) => serde_json::json!({ "ran": true, "ok": false, "error": e }),
};
serde_json::json!({
"palette": self.theme.name,
// The operation buttons this pane exposes — id ⇒ the gRPC RPC each
// fires (CLI parity in the doc). The matrix walks this to prove every
// root op is wired.
"buttons": [
{ "id": "server_status", "rpc": "Health.Ping", "heavy": false },
{ "id": "add_workspace", "rpc": "Workspaces.Register", "heavy": false },
{ "id": "kill_workspace", "rpc": "Workspaces.Remove", "heavy": false, "confirm": true },
{ "id": "populate", "rpc": "Workspaces.Fetch", "heavy": false },
{ "id": "refresh", "rpc": "Workspaces.Fetch", "heavy": false },
{ "id": "populate_status", "rpc": "Viz.CloneEvents", "heavy": false },
],
"add_form": {
"name": self.new_name,
"descriptor": self.new_descriptor,
"mode": self.new_mode,
"poll": self.new_poll,
},
"kill": { "target": self.kill_target, "armed": self.kill_armed },
"results": {
"add": res(&self.last_add),
"kill": res(&self.last_kill),
"populate": res(&self.last_populate),
"refresh": res(&self.last_refresh),
},
"server": match &self.server_info {
None => serde_json::json!({ "pinged": false }),
Some(Ok(i)) => serde_json::json!({
"pinged": true, "ok": true,
"status": i.status, "version": i.version, "repo_count": i.repo_count,
}),
Some(Err(e)) => serde_json::json!({ "pinged": true, "ok": false, "error": e }),
},
// PLAN #6: the per-member populate status this pane renders — every
// member's clone outcome (ok/error + detail + when) for the active
// workspace, so the matrix can assert the failed member + error is
// surfaced ("see what the user sees" as data, LAW #6).
"populate_status": match &self.clone_events {
None => serde_json::json!({ "loaded": false }),
Some(Err(e)) => serde_json::json!({ "loaded": true, "ok": false, "error": e }),
Some(Ok(rows)) => serde_json::json!({
"loaded": true,
"ok": true,
"workspace": self.clone_events_ws,
"total": rows.len(),
"failed": rows.iter().filter(|r| r.status == "error").count(),
"members": rows.iter().map(|r| serde_json::json!({
"member": r.member,
"op": r.op,
"status": r.status,
"detail": r.detail,
"remote": r.remote,
"ts": crate::warehouse::clone_events::ts_to_rfc3339(r.ts_micros),
"elapsed_ms": r.elapsed_ms,
})).collect::<Vec<_>>(),
}),
},
})
}
/// Test/headless helper: inject populate-status rows directly (the same rows a
/// `Viz.CloneEvents` read would yield) so the matrix can assert `state_json`
/// surfaces a failed member + its error without a live server. (LAW: tests
/// inject real values + assert real output.)
pub fn set_clone_events_for_test(&mut self, workspace: &str, rows: Vec<CloneEventRow>) {
self.clone_events_ws = workspace.to_string();
self.clone_events = Some(Ok(rows));
}
}
/// Load the active workspace's `clone_events` populate outcomes: remote via the
/// `Viz.CloneEvents` RPC, local via the workspace warehouse (lock-tolerant
/// `open_read_only`). Returns rows newest-first or a human error string.
fn load_clone_events(
srv: Option<&Server>,
active_ws: &str,
local_warehouse: Option<&PathBuf>,
) -> Result<Vec<CloneEventRow>, String> {
if let Some(srv) = srv {
return remote::fetch_clone_events(&srv.endpoint, &srv.token, active_ws)
.map_err(|e| format!("{e:#}"));
}
// Local mode: read the workspace's own warehouse without contending the
// single-writer lock.
let Some(root) = local_warehouse else {
return Ok(Vec::new());
};
use crate::warehouse::clone_events::{query_clone_events, CloneSelector};
let wh = crate::warehouse::iceberg::IcebergWarehouse::open_read_only(root)
.map_err(|e| format!("open warehouse: {e:#}"))?;
wh.block_on(query_clone_events(&wh, &CloneSelector::Workspace(active_ws.to_string())))
.map_err(|e| format!("{e:#}"))
}
/// Render an `Ok`/`Err` result line in the palette colours (shared by the ops).
fn result_line(ui: &mut egui::Ui, theme: Theme, r: &Option<Result<String, String>>) {
let _ = theme;
match r {
Some(Ok(m)) => { ui.colored_label(GREEN, format!("✓ {m}")); }
Some(Err(e)) => { ui.colored_label(RED, format!("✗ {e}")); }
None => {}
}
}
/// Thin wrapper over `Workspaces.Fetch` that yields a one-line human summary
/// (Populate uses `background=true`; Refresh uses `force=true`).
fn fetch(
endpoint: &str,
token: &str,
name: &str,
force: bool,
background: bool,
) -> anyhow::Result<String> {
// `fetch_workspace` only exposes `force`; the background path is the same
// RPC with `background=true`, surfaced here via the dedicated helper.
let (fetched, changed, errors, snapshot) = if background {
remote::populate_workspace(endpoint, token, name)?
} else {
remote::fetch_workspace(endpoint, token, name, force)?
};
let snap = if snapshot.is_empty() { String::new() } else { format!(" → snapshot {}", &snapshot[..12.min(snapshot.len())]) };
let errs = if errors.is_empty() { String::new() } else { format!(", {} error(s)", errors.len()) };
Ok(format!("{} fetched, {} changed{snap}{errs}", fetched, changed.len()))
}
#[cfg(test)]
mod tests {
use super::*;
/// LAW 1 (inject-assert) + LAW #6 (components emit what they render): inject a
/// `clone_events` row-set with one OK and one FAILED member into the pane, then
/// assert `state_json` surfaces the failed member, its error detail, the
/// failed-count, and the `Viz.CloneEvents` button — "see what the user sees" as
/// data. Not a "didn't panic" test.
#[test]
fn state_json_surfaces_failed_member_populate_status() {
let mut view = NornirRootView::remote();
view.set_clone_events_for_test(
"nordisk",
vec![
CloneEventRow {
ts_micros: 2,
workspace: "nordisk".into(),
member: "korp".into(),
remote: "https://github.com/nordisk/korp".into(),
op: "clone-fetch".into(),
status: "error".into(),
detail: "clone-fetch …: Couldn't obtain Username".into(),
elapsed_ms: 7,
},
CloneEventRow {
ts_micros: 1,
workspace: "nordisk".into(),
member: "facett".into(),
remote: "git@github.com:nordisk/facett.git".into(),
op: "clone-fetch".into(),
status: "ok".into(),
detail: "abc123".into(),
elapsed_ms: 42,
},
],
);
let s = view.state_json();
let ps = &s["populate_status"];
assert_eq!(ps["loaded"], true);
assert_eq!(ps["ok"], true);
assert_eq!(ps["workspace"], "nordisk");
assert_eq!(ps["total"], 2);
assert_eq!(ps["failed"], 1, "one member failed to populate");
let members = ps["members"].as_array().expect("members array");
let korp = members
.iter()
.find(|m| m["member"] == "korp")
.expect("failed member korp is surfaced");
assert_eq!(korp["status"], "error");
assert!(
korp["detail"].as_str().unwrap().contains("Couldn't obtain Username"),
"the error detail is readable in state_json, got: {}",
korp["detail"]
);
assert_eq!(korp["op"], "clone-fetch");
assert!(korp["ts"].as_str().unwrap().contains('T'), "ts rendered as RFC3339");
// The populate-status button is discoverable by the matrix.
let buttons = s["buttons"].as_array().unwrap();
assert!(
buttons.iter().any(|b| b["id"] == "populate_status" && b["rpc"] == "Viz.CloneEvents"),
"the populate-status surface is wired to Viz.CloneEvents"
);
}
}