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
//! The async event loop: a single `tokio::select!` over four sources —
//! crossterm `EventStream`, a tick interval, a render interval, and an
//! `mpsc<Action>` domain channel that background data tasks push into.
//!
//! This file is the central router. It owns:
//! - the pane components and the active-pane focus,
//! - the [`DataConfig`] resolved from the environment,
//! - the live kube client and a lazily-built `AgentDialer`,
//! - the spawn sites that drive the real data adapters and forward their
//! results back as [`Action`]s.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use color_eyre::Result;
use futures::{FutureExt, StreamExt};
use ratatui::crossterm::event::{
Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
};
use ratatui::layout::{Constraint, Layout};
use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{Paragraph, Tabs};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tokio::time::{MissedTickBehavior, interval};
/// Run forensics fleet enrichment at most every N ticks (N × `tick_rate`),
/// rather than on every 250 ms tick — token/turn counts move slowly.
const ENRICH_EVERY_TICKS: u64 = 8;
use crate::action::{Action, ApprovalDecision, Pane, QuestionDecision};
use crate::components::Component;
use crate::components::approvals::{ApprovalOutcome, Approvals};
use crate::components::fleet::Fleet;
use crate::components::questions::{QuestionOutcomeView, Questions};
use crate::components::tools::Tools;
use crate::components::transcript::Transcript;
use crate::data::{self, DataConfig};
use crate::tui::Tui;
/// The cockpit model: the pane components, the active pane, and the
/// loop plumbing.
pub(crate) struct Model {
tui: Tui,
should_quit: bool,
tick_rate: Duration,
render_rate: Duration,
/// The currently focused pane.
active: Pane,
fleet: Fleet,
transcript: Transcript,
approvals: Approvals,
tools: Tools,
questions: Questions,
/// Connection configuration resolved from the environment.
config: DataConfig,
/// Live kube client, built once at startup (cheap to clone).
kube: Option<kube::Client>,
/// Auto port-forwards keeping the localhost data endpoints alive. Held for
/// the lifetime of the cockpit; dropping one aborts its accept loop. Empty
/// when both endpoints came from explicit env/flag overrides.
forwards: Vec<data::portforward::Forward>,
/// The most recent background-task error, shown in the global status line
/// regardless of which pane is focused. Cleared on navigation.
status: Option<String>,
/// Monotonic tick counter, used to rate-limit forensics enrichment.
tick_count: u64,
/// Set while a fleet-enrichment pass is running, so overlapping passes are
/// skipped — a slow forensics endpoint cannot pile up detached tasks.
enrich_in_flight: Arc<AtomicBool>,
action_tx: UnboundedSender<Action>,
action_rx: UnboundedReceiver<Action>,
}
impl Model {
/// Construct the model with an explicit data configuration and its action
/// channel. Used by the library entrypoint so the embedding CLI can layer
/// flag overrides over the environment.
///
/// # Errors
/// Returns an error if the terminal handle cannot be created.
pub(crate) fn with_config(config: DataConfig) -> Result<Self> {
let (action_tx, action_rx) = mpsc::unbounded_channel();
Ok(Self {
tui: Tui::new()?,
should_quit: false,
tick_rate: Duration::from_millis(250),
render_rate: Duration::from_millis(16),
active: Pane::Fleet,
fleet: Fleet::default(),
transcript: Transcript::default(),
approvals: Approvals::default(),
tools: Tools::default(),
questions: Questions::default(),
config,
kube: None,
forwards: Vec::new(),
status: None,
tick_count: 0,
enrich_in_flight: Arc::new(AtomicBool::new(false)),
action_tx,
action_rx,
})
}
/// A clone of the sender background data tasks use to feed the loop.
#[must_use]
pub(crate) fn action_sender(&self) -> UnboundedSender<Action> {
self.action_tx.clone()
}
/// Spawn the startup background work: build the kube client, load the fleet
/// snapshot, and start the long-lived `Conversation` watch. Forensics
/// enrichment is layered on per-tick (see [`Self::poll_enrichment`]).
///
/// Failures are surfaced as `Action::Error` rather than crashing the loop —
/// a cockpit with no kube reachability still renders (empty) and lets the
/// operator read the error line.
async fn spawn_background_work(&mut self) {
let tx = self.action_sender();
let namespace = self.config.namespace.clone();
match data::fleet::build_client().await {
Ok(client) => {
self.kube = Some(client.clone());
// Auto-wire the localhost data endpoints: any endpoint the
// operator didn't pin via env/flag is served by an in-process
// port-forward to the control-plane pod (the same bridge
// `polychrome send` uses). This is what makes a bare
// `polychrome` populate the transcript/approvals panes with no
// `kubectl port-forward` and no `PC_TUI_*` vars. It only binds
// local listeners here (no kube round-trip), so it never blocks
// first paint; pods are resolved lazily inside each forward.
self.auto_forward(&client, &namespace);
// Initial snapshot.
{
let tx = tx.clone();
let client = client.clone();
let namespace = namespace.clone();
tokio::spawn(async move {
match data::fleet::load_fleet(&client, &namespace).await {
Ok(rows) => {
let _ = tx.send(Action::FleetLoaded(rows));
}
Err(err) => {
let _ = tx.send(Action::Error(format!("fleet load: {err}")));
}
}
});
}
// Long-lived watch → FleetDelta per change.
{
let tx = tx.clone();
tokio::spawn(async move {
match data::fleet::watch_fleet(&client, &namespace).await {
Ok(stream) => {
futures::pin_mut!(stream);
while let Some(item) = stream.next().await {
match item {
Ok(row) => {
if tx.send(Action::FleetDelta(row)).is_err() {
break; // loop gone
}
}
Err(err) => {
let _ = tx
.send(Action::Error(format!("fleet watch: {err}")));
}
}
}
}
Err(err) => {
let _ = tx.send(Action::Error(format!("fleet watch open: {err}")));
}
}
});
}
}
Err(err) => {
let _ = tx.send(Action::Error(format!(
"kube client unavailable (fleet/tools disabled): {err}"
)));
}
}
}
/// Stand up the in-process port-forwards for any data endpoint not already
/// pinned by an env/flag override, filling the resolved [`DataConfig`] with
/// the localhost URLs they serve.
///
/// Binding is local-only (no kube round-trip), so this returns immediately
/// and never blocks the cockpit's first paint. Each forward resolves the
/// control-plane pod lazily and per-connection, so a pod restart self-heals;
/// bind failures land in the status line, and live per-connection failures
/// (no Running pod, broken stream) surface via the action channel. The held
/// [`data::portforward::Forward`] guards keep each forward alive until the
/// `Model` is dropped.
fn auto_forward(&mut self, client: &kube::Client, namespace: &str) {
let tx = self.action_sender();
// (port, status label, is the agent/approval endpoint?) — the bool picks
// which `config` field to fill, the only structural difference between
// the two otherwise-identical forwards.
for (remote_port, label, is_agent) in [
(data::portforward::AGENT_PORT, "agent", true),
(data::portforward::FORENSICS_PORT, "forensics", false),
] {
let already_pinned = if is_agent {
self.config.agent_addr.is_some()
} else {
self.config.forensics_base_url.is_some()
};
if already_pinned {
continue;
}
match data::portforward::start(
client.clone(),
namespace.to_owned(),
remote_port,
label,
tx.clone(),
) {
Ok(fwd) => {
if is_agent {
self.config.agent_addr = Some(fwd.url.clone());
} else {
self.config.forensics_base_url = Some(fwd.url.clone());
}
self.forwards.push(fwd);
}
Err(err) => self.status = Some(format!("{label} port-forward failed: {err}")),
}
}
}
/// Run the event loop until quit.
///
/// # Errors
/// Returns an error if entering the terminal or a draw fails.
pub(crate) async fn run(&mut self) -> Result<()> {
self.tui.enter()?;
self.spawn_background_work().await;
let mut events = EventStream::new();
let mut tick = interval(self.tick_rate);
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut render = interval(self.render_rate);
render.set_missed_tick_behavior(MissedTickBehavior::Skip);
while !self.should_quit {
tokio::select! {
maybe_event = events.next().fuse() => {
match maybe_event {
Some(Ok(event)) => {
if let Some(action) = map_event(event) {
let _ = self.action_tx.send(action);
}
}
Some(Err(_)) => { /* transient read error; ignore */ }
None => { self.should_quit = true; }
}
}
_ = tick.tick() => { let _ = self.action_tx.send(Action::Tick); }
_ = render.tick() => { let _ = self.action_tx.send(Action::Render); }
Some(action) = self.action_rx.recv() => { self.update(action)?; }
}
}
crate::tui::Tui::exit();
Ok(())
}
/// Dispatch one action: handle loop-level variants, route the rest to the
/// pane components, and re-queue any follow-up actions they emit.
// Takes `Action` by value: it owns the action for the duration of dispatch
// and clones owned ids/decisions out of it; a reference would just push the
// clones to every caller.
#[allow(clippy::needless_pass_by_value)]
fn update(&mut self, action: Action) -> Result<()> {
// ---- loop-level handling (consumes some actions, augments others) ----
match &action {
Action::Quit => {
self.should_quit = true;
return Ok(());
}
Action::Suspend => {
// Restore the terminal, stop on SIGTSTP, and repaint on resume.
if let Err(err) = self.tui.suspend() {
self.status = Some(format!("suspend failed: {err}"));
}
let _ = self.action_tx.send(Action::Render);
return Ok(());
}
Action::Render => {
self.render()?;
return Ok(());
}
Action::Tick => {
self.tick_count = self.tick_count.wrapping_add(1);
self.poll_enrichment();
// Fall through so components can also react to ticks if needed.
}
Action::Resize(_, _) => {
let _ = self.action_tx.send(Action::Render);
}
Action::Nav(pane) => {
self.active = *pane;
// A deliberate navigation dismisses a stale background error.
self.status = None;
}
// Surface every background-task fault in the global status line so
// errors from any pane's loads are visible regardless of focus.
Action::Error(msg) => {
self.status = Some(msg.clone());
// Fall through: components may also react (e.g. approvals).
}
// Top-level key bindings: quit + pane switching. Pane-local keys
// (movement, approve/reject, etc.) still fan out to components below.
// While the focused pane is capturing text, single-key globals are
// suppressed so they reach the editor (Ctrl-C still quits, handled
// inside `global_key`).
Action::Key(key) => {
let ctrl_c = key.modifiers.contains(KeyModifiers::CONTROL)
&& matches!(key.code, KeyCode::Char('c' | 'C'));
let intercept = ctrl_c || !self.active_pane().capturing_input();
// Re-queue the synthesized action (e.g. Nav/Quit) and stop: a
// pane switch should not also be consumed as a pane-local key in
// the same dispatch.
if intercept && let Some(loop_action) = self.global_key(*key) {
let _ = self.action_tx.send(loop_action);
return Ok(());
}
}
// The operator selected a conversation: kick off its per-conversation
// loads (transcript history, tools, approvals projection).
Action::Select(id) => {
self.on_select(id.clone());
}
// A decision was made in the approvals pane: submit it via the THIN
// path and report back as ApprovalSubmitted/Error.
Action::ApprovalDecide(decision) => {
self.submit_approval(decision.clone());
}
// A decision was made in the questions pane: submit it via the
// THIN path and report back as QuestionSubmitted/Error — mirrors
// `Action::ApprovalDecide` above.
Action::QuestionDecide(decision) => {
self.submit_question(decision.clone());
}
_ => {}
}
// Fan out to all components; re-queue follow-ups.
let mut follow_ups = Vec::new();
for component in self.components_mut() {
if let Some(next) = component.handle(&action) {
follow_ups.push(next);
}
}
// A fleet-originated `Select` (Enter on a row) must also pivot focus to
// the transcript. The fleet component can only emit one follow-up
// (`Select`); the router layers the `Nav` on. We only do this when the
// fleet pane is active so a programmatic `Select` from elsewhere does
// not steal focus.
if self.active == Pane::Fleet && matches!(&action, Action::Select(_)) {
follow_ups.push(Action::Nav(Pane::Transcript));
}
for next in follow_ups {
let _ = self.action_tx.send(next);
}
Ok(())
}
/// Map top-level keys to loop actions (pane switch / quit). Returns `None`
/// for keys that should fall through to the focused pane.
const fn global_key(&self, key: KeyEvent) -> Option<Action> {
// Ctrl-C always quits, from any pane and any mode — in raw mode the
// terminal delivers it as a key event, not SIGINT, so we handle it here.
if key.modifiers.contains(KeyModifiers::CONTROL)
&& matches!(key.code, KeyCode::Char('c' | 'C'))
{
return Some(Action::Quit);
}
// Ctrl-Z suspends to the shell from any pane (job control).
if key.modifiers.contains(KeyModifiers::CONTROL)
&& matches!(key.code, KeyCode::Char('z' | 'Z'))
{
return Some(Action::Suspend);
}
match key.code {
KeyCode::Char('q') => Some(Action::Quit),
KeyCode::Tab => Some(Action::Nav(next_pane(self.active))),
KeyCode::BackTab => Some(Action::Nav(prev_pane(self.active))),
// Esc steps back to the fleet (the home screen); a no-op there.
// While a pane is capturing text this never fires (the caller gates
// on `capturing_input`), so it still cancels the reason editor.
KeyCode::Esc | KeyCode::Char('1') => Some(Action::Nav(Pane::Fleet)),
KeyCode::Char('2') => Some(Action::Nav(Pane::Transcript)),
KeyCode::Char('3') => Some(Action::Nav(Pane::Approvals)),
KeyCode::Char('4') => Some(Action::Nav(Pane::Tools)),
KeyCode::Char('5') => Some(Action::Nav(Pane::Questions)),
_ => None,
}
}
/// On a new conversation selection, spawn the per-conversation data loads.
/// Each is best-effort: a disabled forensics server or missing CR surfaces
/// an `Action::Error` and leaves the relevant pane empty.
fn on_select(&self, conversation_id: String) {
let tx = self.action_sender();
// Transcript history (forensics).
if let Some(base) = self.config.forensics_base_url.clone() {
data::transcript::spawn_history(base.clone(), conversation_id.clone(), tx.clone());
// Approvals projection (forensics) → ApprovalPending per entry.
let tx2 = tx.clone();
let conv = conversation_id.clone();
tokio::spawn(async move {
match data::approvals::load_approvals(&base, &conv).await {
Ok(views) => {
for view in views {
if tx2.send(Action::ApprovalPending(view)).is_err() {
break;
}
}
}
Err(err) => {
let _ = tx2.send(Action::Error(format!("approvals load: {err}")));
}
}
});
}
// Questions (`#1660`): `QuestionService.ListPending`, over the SAME
// agent endpoint approval submission uses — no forensics questions
// projection exists (see `data::questions`'s own doc).
if let Some(agent_addr) = self.config.agent_addr.clone() {
let tx3 = tx.clone();
let conv = conversation_id.clone();
tokio::spawn(async move {
match data::questions::load_questions(&agent_addr, &conv).await {
Ok(views) => {
for view in views {
if tx3.send(Action::QuestionPending(view)).is_err() {
break;
}
}
}
Err(err) => {
let _ = tx3.send(Action::Error(format!("questions load: {err}")));
}
}
});
}
// Tools (kube `Conversation` spec). Last use of `tx`/`conversation_id`,
// so move them in rather than cloning.
if let Some(client) = self.kube.clone() {
let namespace = self.config.namespace.clone();
tokio::spawn(async move {
match data::tools::load_tools(&client, &namespace, &conversation_id).await {
Ok(views) => {
let _ = tx.send(Action::ToolsLoaded(views));
}
Err(err) => {
let _ = tx.send(Action::Error(format!("tools load: {err}")));
}
}
});
}
}
/// Submit an approval decision through the THIN path (control plane signs).
fn submit_approval(&self, decision: ApprovalDecision) {
let tx = self.action_sender();
let Some(agent_addr) = self.config.agent_addr.clone() else {
// No agent endpoint (auto-forward failed and none pinned): report
// rather than silently dropping the operator's decision.
let _ = tx.send(Action::Error(
"no AgentService endpoint — approval not submitted (is the control plane reachable?)"
.to_owned(),
));
return;
};
tokio::spawn(async move {
match data::approvals::submit_decision(&agent_addr, &decision).await {
Ok(reply) => {
// Fold the signed outcome onto the item directly from the
// reply, so the decided/signed state shows immediately even
// when no forensics server is configured for a re-poll. The
// control plane is the signer on the THIN path, so a
// `persisted` reply is by construction validly signed; a
// forensics re-poll independently re-verifies later.
let outcome = reply.persisted.then(|| ApprovalOutcome {
approved: decision.approved,
reason: decision.reason.clone(),
signer_pk_hex: reply.signed_by_hex,
signature_hex: reply.signature_hex,
signature_valid: true,
});
let _ = tx.send(Action::ApprovalSubmitted {
conversation_id: decision.conversation_id.clone(),
turn_id: decision.turn_id.clone(),
request_id: decision.request_id.clone(),
persisted: reply.persisted,
outcome,
});
}
Err(err) => {
let _ = tx.send(Action::Error(format!("approval submit: {err}")));
}
}
});
}
/// Submit a question decision through the THIN path (control plane
/// signs) — mirrors [`Self::submit_approval`]'s own shape.
fn submit_question(&self, decision: QuestionDecision) {
let tx = self.action_sender();
let Some(agent_addr) = self.config.agent_addr.clone() else {
let _ = tx.send(Action::Error(
"no AgentService endpoint — answer not submitted (is the control plane reachable?)"
.to_owned(),
));
return;
};
tokio::spawn(async move {
match data::questions::submit_decision(&agent_addr, &decision).await {
Ok(reply) => {
// Fold a locally-built outcome onto the item directly —
// the RPC reply carries only persisted/signature fields,
// never the state/selected_label the decision itself
// already names, mirroring `submit_approval`'s own
// "no forensics re-poll dependency" reasoning.
let outcome = reply.persisted.then(|| QuestionOutcomeView {
state: if decision.selected_index.is_some() {
"answered".to_owned()
} else {
"declined".to_owned()
},
selected_label: decision.selected_label.clone(),
});
let _ = tx.send(Action::QuestionSubmitted {
call_id: decision.call_id.clone(),
index: decision.index,
persisted: reply.persisted,
outcome,
});
}
Err(err) => {
let _ = tx.send(Action::Error(format!("question submit: {err}")));
}
}
});
}
/// Forensics enrichment: refresh metric fields for the fleet rows when a
/// forensics server is configured. Best-effort; runs at most once every
/// [`ENRICH_EVERY_TICKS`] ticks and never overlaps a prior pass, so a slow
/// or hung forensics endpoint cannot pile up detached tasks or clone the
/// fleet on every tick.
fn poll_enrichment(&self) {
if !self.tick_count.is_multiple_of(ENRICH_EVERY_TICKS) {
return;
}
let Some(base) = self.config.forensics_base_url.clone() else {
return;
};
// Skip if the previous enrichment pass is still in flight. The running
// task clears the flag when it finishes (the shared HTTP client carries
// a request timeout, so a pass cannot hang forever).
if self.enrich_in_flight.swap(true, Ordering::AcqRel) {
return;
}
let tx = self.action_sender();
let rows: Vec<_> = self.fleet.rows.clone();
let in_flight = Arc::clone(&self.enrich_in_flight);
tokio::spawn(async move {
// Merge in conversations that live only in the forensics event log
// (shared-harness mode creates no kube `Conversation` CR), so they
// still surface in the fleet alongside the controller-managed ones.
let mut all = rows;
if let Ok(ids) = data::fleet::list_conversations(&base).await {
let known: std::collections::HashSet<&str> =
all.iter().map(|r| r.id.as_str()).collect();
let mut extra: Vec<_> = ids
.iter()
.filter(|id| !known.contains(id.as_str()))
.map(|id| data::fleet::forensics_row(id))
.collect();
drop(known);
all.append(&mut extra);
}
for mut row in all {
if data::fleet::enrich_row(&base, &mut row).await.is_ok()
&& tx.send(Action::FleetDelta(row)).is_err()
{
break;
}
}
in_flight.store(false, Ordering::Release);
});
}
/// The currently focused pane as a `Component` (read-only).
fn active_pane(&self) -> &dyn Component {
match self.active {
Pane::Fleet => &self.fleet,
Pane::Transcript => &self.transcript,
Pane::Approvals => &self.approvals,
Pane::Tools => &self.tools,
Pane::Questions => &self.questions,
}
}
/// The controls-footer text: the focused pane's hints followed by the
/// always-available global keys. Rendered on every screen so there is
/// always a visible way to switch panes and quit.
fn footer_hints(&self) -> String {
let mut parts: Vec<String> = self
.active_pane()
.controls()
.iter()
.map(|(key, action)| format!("{key} {action}"))
.collect();
parts.push("Tab/1-5 panes".to_owned());
if self.active != Pane::Fleet {
parts.push("Esc back".to_owned());
}
parts.push("^Z suspend".to_owned());
parts.push("q/^C quit".to_owned());
parts.join(" · ")
}
/// All pane components in dispatch order.
fn components_mut(&mut self) -> [&mut dyn Component; 5] {
[
&mut self.fleet,
&mut self.transcript,
&mut self.approvals,
&mut self.tools,
&mut self.questions,
]
}
/// The single draw site, fired only by `Action::Render`. Renders the active
/// pane full-area (layout is a follow-up; the contract is one component per
/// pane).
fn render(&mut self) -> Result<()> {
let active = self.active;
let status = self.status.clone();
let hints = self.footer_hints();
let fleet = &mut self.fleet;
let transcript = &mut self.transcript;
let approvals = &mut self.approvals;
let tools = &mut self.tools;
let questions = &mut self.questions;
self.tui.draw(|frame| {
let area = frame.area();
// A top nav bar (so every feature is visible), the active pane in
// the middle, and a controls footer (so there is always a way out);
// the footer grows by one row for the error line when present.
let footer_rows = if status.is_some() { 2 } else { 1 };
let parts = Layout::vertical([
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(footer_rows),
])
.split(area);
let (tabs_area, body, footer) = (parts[0], parts[1], parts[2]);
// Top nav bar: every pane, the active one highlighted.
let tabs = Tabs::new(Pane::ALL.iter().map(|p| p.title()))
.select(active.index())
.divider("│")
.style(Style::default().fg(Color::DarkGray))
.highlight_style(
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD | Modifier::REVERSED),
);
frame.render_widget(tabs, tabs_area);
let component: &mut dyn Component = match active {
Pane::Fleet => fleet,
Pane::Transcript => transcript,
Pane::Approvals => approvals,
Pane::Tools => tools,
Pane::Questions => questions,
};
let _ = component.draw(frame, body);
// Footer: optional error line on top, controls hint always at the
// bottom row.
let (err_area, hint_area) = if status.is_some() {
let rows =
Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).split(footer);
(Some(rows[0]), rows[1])
} else {
(None, footer)
};
if let (Some(rect), Some(msg)) = (err_area, status.as_ref()) {
frame.render_widget(
Paragraph::new(format!("⚠ {msg}")).style(Style::default().fg(Color::Red)),
rect,
);
}
frame.render_widget(
Paragraph::new(hints.as_str()).style(Style::default().fg(Color::DarkGray)),
hint_area,
);
})?;
Ok(())
}
}
/// The next pane in the Tab cycle.
const fn next_pane(p: Pane) -> Pane {
match p {
Pane::Fleet => Pane::Transcript,
Pane::Transcript => Pane::Approvals,
Pane::Approvals => Pane::Tools,
Pane::Tools => Pane::Questions,
Pane::Questions => Pane::Fleet,
}
}
/// The previous pane in the Shift-Tab cycle.
const fn prev_pane(p: Pane) -> Pane {
match p {
Pane::Fleet => Pane::Questions,
Pane::Transcript => Pane::Fleet,
Pane::Approvals => Pane::Transcript,
Pane::Tools => Pane::Approvals,
Pane::Questions => Pane::Tools,
}
}
/// Map a crossterm `Event` into the [`Action`] vocabulary. Pattern 3:
/// `SIGWINCH` arrives here as `Event::Resize`.
#[allow(clippy::needless_pass_by_value)] // owns the event; moves inner data into the Action
fn map_event(event: Event) -> Option<Action> {
match event {
Event::Key(
key @ KeyEvent {
kind: KeyEventKind::Press,
..
},
) => Some(Action::Key(key)),
Event::Mouse(m) => Some(Action::Mouse(m)),
Event::Resize(w, h) => Some(Action::Resize(w, h)),
_ => None,
}
}