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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
//! Dashboard state machine. Deliberately free of terminal I/O so key handling
//! and selection logic stay unit-testable; `mod.rs` owns the crossterm/ratatui
//! side and feeds decoded key events in here.
use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::{Mutex, Weak};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use ratatui::layout::Rect;
use super::data::{visible_nodes, Node, Snapshot};
#[cfg(test)]
use super::data::ContainerStatus;
use super::procs::ProcState;
use super::prompt::{Prompt, PromptAction};
use super::select::{Candidate, Region, RegionId, Selection};
use super::settings::Settings;
use super::term::{TermParser, TermTabs};
mod access;
mod actions;
mod command_line;
mod forms;
mod identity;
mod inbox;
mod procs;
mod selection;
mod terminal;
mod thread_actions;
#[cfg(test)]
mod test_support;
mod tree;
mod view;
pub use crate::inbox::Thread;
pub use inbox::{
chip, pane_feed, pane_header, short_age, title_of, HeaderRow, InboxFocus, InboxView, PaneLine, Tone,
View,
};
pub use forms::{form_lines, form_title, forms_offset, pinned_forms, FormSpot};
pub use actions::{PendingDone, VerbEnd, not_yet_code};
pub use identity::{IdentityOn, IdentityReq};
pub use procs::{PendingSessionRm, PendingSignal, Signal};
pub use selection::{copy_key_intercepted, Extract};
pub use terminal::{ExecCli, Redial};
pub use view::{
BuildLogModal, ConfigKind, ConfigView, ConfirmModal, Fetch, HelpModal, Modal, Pane, Side, TextModal, BUILD_LOG_LINES,
LOG_LINES,
};
use view::{col_near, divider_pct};
/// The five top-level views. Machines is listed only while a machine is
/// registered ([`App::tabs`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Tab {
Instances,
Services,
Ports,
Inbox,
Machines,
}
impl Tab {
pub const ALL: [Tab; 5] = [Tab::Instances, Tab::Services, Tab::Ports, Tab::Inbox, Tab::Machines];
pub fn title(self) -> &'static str {
match self {
Tab::Instances => "Instances",
Tab::Services => "Services",
Tab::Ports => "Ports",
Tab::Inbox => "Inbox",
Tab::Machines => "Machines",
}
}
fn index(self) -> usize {
match self {
Tab::Instances => 0,
Tab::Services => 1,
Tab::Ports => 2,
Tab::Inbox => 3,
Tab::Machines => 4,
}
}
}
/// Where keystrokes go. `Dashboard` is the classic table/tree navigation;
/// `Terminal` forwards nearly every key to the active integrated terminal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Focus {
Dashboard,
Terminal,
}
/// One row of the Ports tab: a live forward, projected from the daemon's
/// `forwards.list` rows by the daemon worker (`tui/daemon.rs`). Plain data,
/// so [`App`] stays free of the forward module.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PortRow {
/// Stable forward id, used to target a `d` (stop) at the right forward.
pub id: u64,
/// Host side, e.g. `"127.0.0.1:3000"`.
pub local: String,
/// Route label, e.g. `"api:3000"` or `"postgres:5432 (via instance api)"`.
/// Already carries the `(via …)` suffix, so the table needs no VIA column.
pub target: String,
/// Listening process (`node (pid 412)`), when known.
pub process: Option<String>,
/// Coarse state: `"active"`, `"connecting"`, or `"error: …"`.
pub state: String,
/// Open connection count.
pub conns: usize,
/// Started from a sandbox's `forwardPorts`, not by hand.
pub configured: bool,
/// Made by the opener for a URL's loopback port, not by hand.
pub open: bool,
/// The machine whose instance or service it reaches; `None` for this
/// host's.
pub machine: Option<String>,
}
/// A forward the user asked for, for the event loop to send as `forwards.add`
/// through the daemon worker. Mirrors the CLI's `(instance, service, address, spec)` inputs;
/// `spec` is a validated `[host:]port` string. `instance` and `service` are
/// names on `machine` (bare, never [`qualify`](crate::tui::remote::qualify)d keys); a machine's
/// forward carries the config root there (`root`), which the call sends as
/// its `dir`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PortRequest {
pub instance: String,
pub service: Option<String>,
pub address: Option<String>,
pub spec: String,
pub machine: Option<String>,
pub root: Option<String>,
}
pub struct App {
pub dir: PathBuf,
pub tab: Tab,
/// Selected row per tab, indexed by `Tab::index`.
selected: [usize; 5],
/// Collapsed tree groups on the Instances tab, keyed by sandbox name (and
/// [`ORPHANS_NAME`](super::data::ORPHANS_NAME) for the orphan group). Empty
/// means all expanded; survives snapshot refreshes.
collapsed: BTreeSet<String>,
/// Instances (by name) whose process layer is expanded on the Instances tab.
/// Default empty (all collapsed); survives snapshot refreshes.
expanded_procs: BTreeSet<String>,
/// Cached process state per instance name. Kept across collapse (stale is
/// fine); a fetch overwrites only the keys it fetched. Absent = not yet
/// fetched, which renders as a placeholder row.
pub procs: BTreeMap<String, ProcState>,
/// Set when an instance's procs are freshly expanded so the event loop
/// fetches immediately instead of waiting for the next proc tick; the loop
/// clears it.
pub needs_proc_fetch: bool,
/// Latest data collected off-thread; `None` until the first snapshot lands.
pub snapshot: Option<Snapshot>,
pub modal: Modal,
/// Command prompt, when open (`:`). Occupies the bottom bar and swallows keys.
pub prompt: Option<Prompt>,
/// Action awaiting execution by the event loop (it sends the verb
/// request, or suspends for `exec`, keeping [`App`] I/O-free).
pub pending_action: Option<PromptAction>,
/// A verb the identity modal let go (`identity.rs`): returned by
/// [`Self::take_pending_action`] ahead of `pending_action`, unasked.
cleared_action: Option<PromptAction>,
/// The identity request (the offer's read, a modal's answer) for the
/// event loop to hand the daemon worker.
pending_identity: Option<IdentityReq>,
/// The first snapshot asked for the identity offer.
identity_offered: bool,
/// What an identity answer did, for the released verb's status line.
identity_note: Option<String>,
/// Pending permission requests (`access.pending`), oldest first.
pub access: Vec<crate::serve::api::AccessRequest>,
/// Requests answered or put off here: their modal doesn't open by
/// itself again (`access.rs`).
access_quiet: BTreeSet<String>,
/// An answer for the event loop to send as `access.decide`.
pending_decide: Option<(String, crate::broker::asks::Answer)>,
/// Until when the access modal that opened by itself ignores answers.
access_guard: Option<std::time::Instant>,
/// The event loop's clock as of its last [`Self::set_clock`]; `None`
/// before the first.
clock: Option<std::time::Instant>,
/// Appended to the status line the event loop writes after launching a
/// [`PromptAction::Code`]: an Inbox `vscode` action's caveats (a goto it
/// couldn't honor, the event and child done queued), which would
/// otherwise be overwritten by the launch outcome.
pub code_note: Option<String>,
/// Instances with an `s` stop request in flight, so repeated `s` presses
/// don't send a second one. Cleared when its answer arrives
/// ([`App::verb_answered`]).
pub stopping: BTreeSet<String>,
/// Instances with a start request in flight (same dedup rule as
/// `stopping`).
pub starting: BTreeSet<String>,
/// A thread host action waiting on the start of its stopped target
/// (`thread_actions.rs`): run once a snapshot shows the target up
/// ([`App::set_snapshot`]), dropped if the start request fails. A newer
/// such action replaces it.
after_start: Option<(String, thread_actions::Deferred)>,
/// Done-flag changes the event loop should send as `instances.done`
/// requests (a thread's child on the Inbox thread `done`/reopen).
pub pending_done: Vec<PendingDone>,
/// An `instances.signal` request the event loop should send (the
/// SIGTERM/SIGKILL shortcuts on a process row). Runs without suspending.
pub pending_signal: Option<PendingSignal>,
/// A `sessions.rm` the event loop should send (`K` on a session row).
pub pending_session_rm: Option<PendingSessionRm>,
/// Instance whose `run`/`rebuild`/`start` the event loop should cancel
/// (`d` on an in-flight row, confirmed): `instances.cancel` through the
/// daemon, which SIGINTs its recorded pid's group.
pub pending_cancel: Option<String>,
/// Instance id whose build log the event loop should read into the open
/// [`BuildLogModal`].
pub pending_build_log: Option<String>,
/// A build-log read was handed to the event loop and isn't answered yet
/// ([`App::take_build_log_read`]).
build_log_in_flight: bool,
/// When the open build log is next re-read while it's being written
/// ([`App::tick_build_log`]).
build_log_due: Option<std::time::Instant>,
/// Daemon reads the open modals wait on, for the event loop to send.
pending_fetch: Vec<Fetch>,
/// The container the logs modal shows, so a late answer for another
/// one is dropped ([`App::set_logs`]).
logs_container: Option<String>,
/// Live forwards shown on the Ports tab, fed by the daemon worker
/// (`forwards.list`). Empty until the worker reports; set via
/// [`Self::set_ports`].
pub ports: Vec<PortRow>,
/// A forward the event loop should start through the daemon worker (the
/// `p` shortcut / `port` prompt).
pub pending_port: Option<PortRequest>,
/// Id of a forward the event loop should stop (the `d` shortcut on the Ports
/// tab), through the daemon worker.
pub pending_unport: Option<u64>,
/// A machine whose `agent` the event loop should set, and to what (the
/// `a` shortcut on the Machines tab), through the daemon worker.
pub pending_machine_set: Option<(String, bool)>,
/// Container notifications shown on the Inbox tab (docs/architecture/dashboard/inbox-tab.md),
/// as last loaded from the shared store (`crate::inbox::store`).
pub inbox: InboxView,
/// Changes the event loop owes the store (`d`, `D`, mark-read); already
/// applied to `inbox`, which the reload after them confirms.
pub pending_inbox: Vec<crate::inbox::Op>,
/// A notification link the event loop should hand to the desktop opener
/// (`enter` in the Inbox thread pane).
pub pending_open: Option<String>,
/// Every dispatcher's children by key, owner id → key → instance name
/// (`dispatch::thread_children`), refreshed by the event loop with each
/// snapshot so the thread pane resolves a `child` without reading state.
pub thread_children: BTreeMap<String, BTreeMap<String, String>>,
/// Why the snapshot is stale (the daemon connection is down), until the
/// next push: the header marks the kept snapshot stale with it, or with
/// none yet the tree says it in place of the rows.
pub snapshot_error: Option<crate::tui::data::FetchError>,
/// The registered machines' link states, from the last snapshot
/// (docs/architecture/daemon/machines.md, *Dashboard*), set by [`Self::set_machines`]. Empty
/// without any: the tree is exactly as before machines (no machine column) and the Machines
/// tab isn't listed.
pub machines: Vec<crate::serve::snapshots::SnapshotMachine>,
/// Seconds east of UTC for Inbox timestamps; the event loop sets it once
/// at startup (0 = UTC when unknown).
pub utc_offset: i64,
/// One-line status shown in the help-bar area (e.g. `code` launch outcome).
pub status: Option<String>,
/// True while the config-modal divider is being dragged with the mouse.
dragging_divider: bool,
/// Whether keys drive the dashboard or the active terminal.
pub focus: Focus,
/// Open integrated-terminal tabs, shared across both top-level tabs. Empty
/// until the user opens one with `t`.
pub terms: TermTabs,
/// Whether the outer terminal speaks the kitty keyboard protocol, so new
/// terminals offer it to their child. Set once by the event loop.
pub kitty: bool,
/// The `devsandbox exec` an instance's terminal tab runs. Set once by
/// the event loop (finding the executable is I/O); `Err` is why a tab
/// can't open.
pub exec_cli: Result<ExecCli, String>,
/// The mouse text selection, shown until a press elsewhere, `esc`, a tab
/// switch or a modal opening/closing clears it (`selection.rs`).
selection: Option<Selection>,
/// A left press inside a region that a drag would turn into a selection.
candidate: Option<Candidate>,
/// Selectable regions of the last frame, registered by `ui::draw` (hence
/// the `RefCell`: drawing borrows the app immutably), so a press is
/// hit-tested against what is on screen.
regions: RefCell<Vec<Region>>,
/// Set by a release ending a selection drag or a copy key: the next draw
/// reads the text off the frame it drew, into `clipboard` to copy it, or
/// into `measured` for the `selected N chars` hint.
extract_requested: Cell<Option<Extract>>,
/// Text the event loop owes the clipboard (OSC 52), filled by the draw.
clipboard: RefCell<Option<String>>,
/// Char count of a selection released without copying (copy on select
/// off), filled by the draw for the event loop's status hint.
measured: Cell<Option<(usize, RegionId)>>,
/// Dashboard settings (`settings.rs`), loaded by the event loop at
/// startup; the `?` modal flips them.
pub settings: Settings,
/// A toggle changed `settings` since the event loop last saved them.
settings_dirty: bool,
/// The outer terminal keeps ctrl+shift+c for its own copy
/// (`selection::copy_key_intercepted`, detected by the event loop at
/// startup): hints and help name ctrl-c instead. Wording only.
pub copy_key_intercepted: bool,
/// The button of a press forwarded to a mouse-tracking terminal child,
/// until its release: its drags and release go to the child too (clamped
/// to the body when they leave it), and the press forms no selection.
term_mouse_down: Option<MouseButton>,
/// The last hover report sent to an `AnyMotion` terminal child: which
/// session (a `Weak` so a closed tab's slot can't be mistaken for a new
/// one) and the body cell. crossterm reports a `Moved` per pixel-cell
/// change in the *outer* terminal, so the same body cell repeats; this
/// sends each cell once. Cleared off the body and on any press, so the
/// next hover after either is always reported.
term_hover: Option<(Weak<Mutex<TermParser>>, (u16, u16))>,
pub should_quit: bool,
}
impl App {
pub fn new(dir: PathBuf) -> Self {
Self {
dir,
tab: Tab::Instances,
selected: [0; 5],
collapsed: BTreeSet::new(),
expanded_procs: BTreeSet::new(),
procs: BTreeMap::new(),
needs_proc_fetch: false,
snapshot: None,
modal: Modal::None,
prompt: None,
pending_action: None,
cleared_action: None,
pending_identity: None,
identity_offered: false,
identity_note: None,
access: Vec::new(),
access_quiet: BTreeSet::new(),
pending_decide: None,
access_guard: None,
clock: None,
code_note: None,
stopping: BTreeSet::new(),
starting: BTreeSet::new(),
after_start: None,
pending_signal: None,
pending_session_rm: None,
pending_cancel: None,
pending_build_log: None,
build_log_in_flight: false,
build_log_due: None,
pending_fetch: Vec::new(),
logs_container: None,
pending_done: Vec::new(),
ports: Vec::new(),
pending_port: None,
pending_unport: None,
pending_machine_set: None,
inbox: InboxView::default(),
pending_inbox: Vec::new(),
pending_open: None,
thread_children: BTreeMap::new(),
snapshot_error: None,
machines: Vec::new(),
utc_offset: 0,
status: None,
dragging_divider: false,
focus: Focus::Dashboard,
terms: TermTabs::default(),
kitty: false,
exec_cli: Err("the devsandbox executable isn't known yet".into()),
selection: None,
candidate: None,
regions: RefCell::new(Vec::new()),
extract_requested: Cell::new(None),
clipboard: RefCell::new(None),
measured: Cell::new(None),
settings: Settings::default(),
settings_dirty: false,
copy_key_intercepted: false,
term_mouse_down: None,
term_hover: None,
should_quit: false,
}
}
/// Install a freshly collected snapshot and re-clamp the Instances selection
/// in case rows shrank. I/O-free: the caller does the collecting. Installed
/// as is: the daemon carries cpu/mem over between its stats rounds, and a
/// row it left without them (a stopped container) stays so.
pub fn set_snapshot(&mut self, snapshot: Snapshot) {
self.snapshot = Some(snapshot);
self.clamp_selection();
self.refresh_build_log();
self.run_after_start();
self.offer_identity_once();
}
/// Install the daemon's latest forward rows and re-clamp the Ports
/// selection in case it shrank. I/O-free: the daemon worker does the
/// collecting.
pub fn set_ports(&mut self, ports: Vec<PortRow>) {
self.ports = ports;
self.clamp_selection();
}
/// Install the snapshot's registered machines. The last one gone while
/// the Machines tab is open leaves it for Instances (the tab is no
/// longer listed).
pub fn set_machines(&mut self, machines: Vec<crate::serve::snapshots::SnapshotMachine>) {
self.machines = machines;
if self.machines.is_empty() && self.tab == Tab::Machines {
self.set_tab(Tab::Instances);
}
self.clamp_selection();
}
/// The tabs listed in the bar, in order: [`Tab::ALL`] minus Machines
/// while no machine is registered.
pub fn tabs(&self) -> Vec<Tab> {
Tab::ALL.into_iter().filter(|&t| t != Tab::Machines || !self.machines.is_empty()).collect()
}
/// Clamp every tab's selection into `[0, row_count)` (or 0 when empty).
fn clamp_selection(&mut self) {
for tab in Tab::ALL {
let rows = self.row_count_for(tab);
let slot = tab.index();
if rows == 0 {
self.selected[slot] = 0;
} else if self.selected[slot] >= rows {
self.selected[slot] = rows - 1;
}
}
}
/// Selected row index for the active tab.
pub fn selected(&self) -> usize {
self.selected[self.tab.index()]
}
/// Row count for the active tab. Zero means "nothing to select".
fn row_count(&self) -> usize {
self.row_count_for(self.tab)
}
fn row_count_for(&self, tab: Tab) -> usize {
match tab {
Tab::Instances => self.visible_nodes().len(),
Tab::Services => self.snapshot.as_ref().map_or(0, |s| s.services.len()),
Tab::Ports => self.ports.len(),
Tab::Inbox => self.inbox.rows().len(),
Tab::Machines => self.machines.len(),
}
}
/// Flattened Instances-tree nodes for the current snapshot + collapse state.
/// Empty until a snapshot lands. Cheap; recomputed on demand.
pub fn visible_nodes(&self) -> Vec<Node> {
match &self.snapshot {
Some(s) => visible_nodes(
&s.sandboxes,
&s.instances,
&self.collapsed,
&self.expanded_procs,
&self.procs,
),
None => Vec::new(),
}
}
/// Whether a tree group (sandbox name /
/// [`ORPHANS_NAME`](super::data::ORPHANS_NAME)) is collapsed. Used by the
/// renderer to pick the ▸/▾ marker.
pub fn is_collapsed_group(&self, key: &str) -> bool {
self.collapsed.contains(key)
}
/// The tree node under the Instances-tab cursor, if any.
fn selected_node(&self) -> Option<Node> {
self.visible_nodes()
.get(self.selected[Tab::Instances.index()])
.copied()
}
/// Cycle over the listed tabs ([`Self::tabs`]), by position in that list.
pub fn next_tab(&mut self) {
let tabs = self.tabs();
let i = tabs.iter().position(|&t| t == self.tab).unwrap_or(0);
self.set_tab(tabs[(i + 1) % tabs.len()]);
}
pub fn prev_tab(&mut self) {
let tabs = self.tabs();
let i = tabs.iter().position(|&t| t == self.tab).unwrap_or(0);
self.set_tab(tabs[(i + tabs.len() - 1) % tabs.len()]);
}
/// Apply a key event to the state. No terminal I/O here (the modal open path queues
/// daemon `Fetch`es for the event loop — see [`Self::open_config`]).
pub fn on_key(&mut self, key: KeyEvent) {
let modal = std::mem::discriminant(&self.modal);
let term = (self.terms.active(), self.terms.sessions().len());
self.dispatch_key(key);
// A request listed while keys went elsewhere opens once they don't.
self.open_access();
// A modal opening or closing, or another terminal tab (`[`/`]`/`x`,
// `t`), changes what's on screen under the selection: a terminal
// selection would otherwise read the next session's rows.
if std::mem::discriminant(&self.modal) != modal || (self.terms.active(), self.terms.sessions().len()) != term {
self.clear_selection();
}
// Whatever the key did to the Inbox cursor (moved it, dismissed the
// row under it, switched views), the pane follows in one place.
self.sync_inbox_selection();
}
fn dispatch_key(&mut self, key: KeyEvent) {
// `esc` drops a selection first, and only that, wherever the keys go
// except a focused terminal's shell, which owns its `esc`.
let to_shell = self.prompt.is_none() && matches!(self.modal, Modal::None) && self.focus == Focus::Terminal;
if key.code == KeyCode::Esc && self.selection.is_some() && !to_shell {
self.clear_selection();
return;
}
// The copy shortcut over a selection, even into a focused terminal
// (this runs ahead of `on_key_terminal`): it re-copies rather than
// reaching the PTY. Without a selection it goes on as before.
if self.selection_key(&key) {
return;
}
// A legacy terminal sends ctrl+shift+c as plain ctrl+c, which would
// quit: over a dashboard selection it copies (a second one, with the
// selection cleared by `esc` or a click, still quits). A focused shell
// keeps its ctrl+c (SIGINT), the prompt its own.
if self.selection.is_some()
&& !to_shell
&& self.prompt.is_none()
&& key.code == KeyCode::Char('c')
&& key.modifiers == KeyModifiers::CONTROL
{
self.extract_requested.set(Some(Extract::Copy));
return;
}
// The prompt swallows every key while open, ahead of the modal and the
// dashboard bindings.
if self.prompt.is_some() {
self.on_key_prompt(key);
return;
}
// Ctrl-D out of shell habit, or the EOF a closing pty sends, must not
// count as `d` (rm), nor alt-y as a confirm.
if self.stray_chord(&key) {
return;
}
// The modal swallows every key while it is up; the tab bar and tables
// must not react underneath it.
if !matches!(self.modal, Modal::None) {
self.on_key_modal(key);
return;
}
// A focused terminal is next in line, ahead of the dashboard bindings:
// nearly every key belongs to the shell, not the tables.
if self.focus == Focus::Terminal {
self.on_key_terminal(key);
return;
}
// A focused Inbox thread (or its input) shadows the dashboard keys:
// the `1`-`9` action keys over the tab keys, text over everything.
if self.tab == Tab::Inbox && self.inbox.focus != InboxFocus::List {
self.on_key_inbox_pane(key);
return;
}
// Any dashboard key dismisses a lingering status line.
self.status = None;
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
// A selected process row has its own action set: signals only. The
// instance-forwarding shortcuts (rename/vscode/stop/logs/config/terminal)
// are disabled here, leaving navigation and the SIGTERM/SIGKILL keys.
// A session row's are attach and end instead.
let on_proc = self.tab == Tab::Instances
&& matches!(self.selected_node(), Some(Node::Proc { .. }));
let on_session = on_proc && self.selected_session().is_some();
match key.code {
KeyCode::Char('q') => self.should_quit = true,
KeyCode::Char('c') if ctrl => self.should_quit = true,
KeyCode::Char(':') => self.open_prompt(),
KeyCode::Tab => self.next_tab(),
KeyCode::BackTab => self.prev_tab(),
KeyCode::Char('1') => self.set_tab(Tab::Instances),
KeyCode::Char('2') => self.set_tab(Tab::Services),
KeyCode::Char('3') => self.set_tab(Tab::Ports),
KeyCode::Char('4') => self.set_tab(Tab::Inbox),
KeyCode::Char('5') if !self.machines.is_empty() => self.set_tab(Tab::Machines),
// Enter a terminal: ctrl-] or F12. No-op with a status hint when none
// are open.
KeyCode::Char(']') if ctrl => self.enter_terminal(),
KeyCode::F(12) => self.enter_terminal(),
// Inbox list: `o`/`t`/`l`/`p`/`d`/`u` act on the selected thread,
// ahead of the instance keys they share letters with.
KeyCode::Char('o' | 't' | 'l' | 'p' | 'd' | 'u') if self.tab == Tab::Inbox => {
self.on_inbox_thread_key(key.code);
}
// Process-row signals; `t` doubles as SIGTERM there, otherwise it
// opens a terminal.
KeyCode::Char('a') | KeyCode::Enter if on_session => self.attach_selected_session(),
KeyCode::Char('K') if on_session => self.end_selected_session(),
KeyCode::Char('t') if on_session => self.status = Some("a attaches, K ends the session".into()),
KeyCode::Char('t') if on_proc => self.signal_selected_proc(Signal::Term),
KeyCode::Char('K') if on_proc => self.signal_selected_proc(Signal::Kill),
KeyCode::Char('t') => self.open_terminal(false),
KeyCode::Char('T') if !on_proc => self.open_terminal(true),
KeyCode::Char('a') if self.tab == Tab::Instances && !on_proc => self.attach_session(),
KeyCode::Char(']') => self.terms.next(),
KeyCode::Char('[') => self.terms.prev(),
KeyCode::Char('x') => self.terms.close_active(),
KeyCode::Up | KeyCode::Char('k') => self.select_up(),
KeyCode::Down | KeyCode::Char('j') => self.select_down(),
KeyCode::Right if self.tab == Tab::Instances => self.tree_expand(),
KeyCode::Char(' ') if self.tab == Tab::Instances => self.tree_toggle(),
KeyCode::Left if self.tab == Tab::Instances => self.tree_collapse(),
// Inbox list: `enter` focuses the selected thread (whose own
// `enter` opens the link), `r`/`i` its input; `←`/`→` step the
// views.
KeyCode::Enter if self.tab == Tab::Inbox => self.focus_inbox_thread(),
KeyCode::Char('r' | 'i') if self.tab == Tab::Inbox => self.focus_inbox_input(),
KeyCode::Left if self.tab == Tab::Inbox => self.step_inbox_view(-1),
KeyCode::Right if self.tab == Tab::Inbox => self.step_inbox_view(1),
KeyCode::Enter | KeyCode::Char('e') if !on_proc => self.open_config(),
KeyCode::Char('r') if self.tab == Tab::Instances && !on_proc => {
self.open_rename_or_run_prompt()
}
KeyCode::Char('o') if self.tab == Tab::Instances && !on_proc => self.attach_code(),
KeyCode::Char('s') if self.tab == Tab::Instances && !on_proc => {
self.stop_or_start_instance()
}
KeyCode::Char('d') if self.tab == Tab::Instances && !on_proc => self.remove_instance(),
KeyCode::Char('P') if self.tab == Tab::Instances && !on_proc => self.switch_profile(),
KeyCode::Char('l') if !on_proc => self.open_logs(),
KeyCode::Char('b') if self.tab == Tab::Instances && !on_proc => self.open_build_log(),
// Forwarding: `p` opens the `port` prompt prefilled from the selected
// instance (Instances, not a process row) or service (Services); `d`
// stops the selected forward on the Ports tab.
KeyCode::Char('p') if self.tab == Tab::Instances && !on_proc => {
self.open_port_prompt_instance()
}
KeyCode::Char('p') if self.tab == Tab::Services => self.open_port_prompt_service(),
KeyCode::Char('d') if self.tab == Tab::Ports => self.stop_selected_forward(),
KeyCode::Char('a') if self.tab == Tab::Machines => self.toggle_selected_agent(),
KeyCode::Char('D') if self.tab == Tab::Inbox => self.clear_notifications(),
KeyCode::Char('U') if matches!(self.tab, Tab::Instances | Tab::Services) => {
self.request_identity_offer()
}
KeyCode::Char('?') => self.open_help(),
_ => {}
}
}
/// Whether `key` is a character with modifiers beyond shift (uppercase
/// may arrive with it) bound for a zone of one-key bindings that doesn't
/// bind it: those zones' letters and symbols fire bare, their only chords
/// being ctrl-c (quit) and ctrl-] (the terminal). A modal binds none.
fn stray_chord(&self, key: &KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else { return false };
let mods = key.modifiers.difference(KeyModifiers::SHIFT);
if mods.is_empty() || self.takes_raw_keys() {
return false;
}
!matches!(self.modal, Modal::None) || !(mods == KeyModifiers::CONTROL && matches!(c, 'c' | ']'))
}
/// Whether keys go to the PTY or a text input (past the prompt), which
/// own their modified keys.
fn takes_raw_keys(&self) -> bool {
if !matches!(self.modal, Modal::None) {
return false;
}
if self.focus == Focus::Terminal {
return true;
}
self.tab == Tab::Inbox
&& match self.inbox.focus {
InboxFocus::Input => true,
InboxFocus::Form => self.inbox.form.as_ref().is_some_and(|e| e.editing.is_some()),
_ => false,
}
}
/// Apply a mouse event over the full frame `area`. The config modal (when
/// open) owns the mouse: a press/drag on or near the divider column resizes
/// the split; the scroll wheel scrolls the pane under the cursor. Otherwise,
/// with terminals open, clicks and the wheel drive the terminal panel
/// ([`Self::terminal_mouse`]); on the Inbox tab, the list/thread divider
/// drags and the list and pane take clicks ([`Self::inbox_mouse`]); a
/// click on a tab title switches to it ([`Self::tab_bar_mouse`]). Text
/// selection comes first ([`Self::selection_mouse`]): a drag it owns
/// never reaches them, and a press reaches both. I/O-free.
pub fn on_mouse(&mut self, ev: &MouseEvent, area: Rect) {
let modal = std::mem::discriminant(&self.modal);
if !self.selection_mouse(ev) {
self.route_mouse(ev, area);
if ev.kind == MouseEventKind::Down(MouseButton::Left) {
self.selection_press(ev);
}
}
self.open_access();
if std::mem::discriminant(&self.modal) != modal {
self.clear_selection();
}
}
/// [`Self::on_mouse`] for everything but text selection. A text modal
/// (logs, build log, help) takes the wheel, 3 lines a notch like the
/// config view; nothing under it sees it.
fn route_mouse(&mut self, ev: &MouseEvent, area: Rect) {
let wheel = match ev.kind {
MouseEventKind::ScrollUp => Some(-3),
MouseEventKind::ScrollDown => Some(3),
_ => None,
};
if let Some(delta) = wheel {
match &mut self.modal {
Modal::Logs(view) | Modal::Help(HelpModal { text: view, .. }) => {
view.scroll_by(delta);
return;
}
// Its own, so scrolling to the bottom follows the build again.
Modal::BuildLog(view) => {
view.scroll_by(delta);
return;
}
_ => {}
}
}
let Modal::Config(view) = &mut self.modal else {
self.dragging_divider = false;
self.help_mouse(ev, area);
self.inbox_mouse(ev, area);
self.tab_bar_mouse(ev, area);
self.terminal_mouse(ev, area);
// As after a key: a click or wheel may have moved the Inbox cursor.
self.sync_inbox_selection();
return;
};
// Divider column: the boundary between the left (config) pane and the
// right (inspect) pane, i.e. split_pct of the modal width.
let divider = (area.width as u32 * view.split_pct as u32 / 100) as u16;
match ev.kind {
MouseEventKind::Down(MouseButton::Left) => {
if col_near(ev.column, divider) {
self.dragging_divider = true;
view.split_pct = divider_pct(ev.column, area.width);
}
}
MouseEventKind::Drag(MouseButton::Left) => {
if self.dragging_divider {
view.split_pct = divider_pct(ev.column, area.width);
}
}
MouseEventKind::Up(MouseButton::Left) => {
self.dragging_divider = false;
}
MouseEventKind::ScrollDown => {
Self::wheel_scroll(view, ev.column, divider, 3);
}
MouseEventKind::ScrollUp => {
Self::wheel_scroll(view, ev.column, divider, -3);
}
_ => {}
}
}
/// A left press on a tab title switches to that tab, through [`Self::set_tab`]
/// like the `1`-`5` keys (so leaving the Inbox reads what it showed). Not
/// under a modal or the prompt, which own the input. Unlike the keys it
/// works while an Inbox thread has focus: the click names its target.
/// The terminal panel's click-away unfocuses a focused terminal on the
/// same press. The hit-test is `ui`'s, shared with the drawing.
fn tab_bar_mouse(&mut self, ev: &MouseEvent, area: Rect) {
if ev.kind != MouseEventKind::Down(MouseButton::Left)
|| self.prompt.is_some()
|| !matches!(self.modal, Modal::None)
{
return;
}
if let Some(tab) = super::ui::tab_hit(self, area, ev.column, ev.row) {
self.set_tab(tab);
}
}
}
#[cfg(test)]
mod tests {
use super::test_support::*;
use super::*;
#[test]
fn tab_switching() {
let mut app = new_app();
assert_eq!(app.tab, Tab::Instances);
app.on_key(key(KeyCode::Tab));
assert_eq!(app.tab, Tab::Services);
app.on_key(key(KeyCode::Tab));
assert_eq!(app.tab, Tab::Ports);
app.on_key(key(KeyCode::Tab));
assert_eq!(app.tab, Tab::Inbox);
app.on_key(key(KeyCode::Tab));
assert_eq!(app.tab, Tab::Instances);
app.on_key(key(KeyCode::BackTab));
assert_eq!(app.tab, Tab::Inbox);
app.on_key(key(KeyCode::BackTab));
assert_eq!(app.tab, Tab::Ports);
app.on_key(key(KeyCode::BackTab));
assert_eq!(app.tab, Tab::Services);
app.on_key(key(KeyCode::BackTab));
assert_eq!(app.tab, Tab::Instances);
app.on_key(key(KeyCode::Char('2')));
assert_eq!(app.tab, Tab::Services);
app.on_key(key(KeyCode::Char('3')));
assert_eq!(app.tab, Tab::Ports);
app.on_key(key(KeyCode::Char('4')));
assert_eq!(app.tab, Tab::Inbox);
app.on_key(key(KeyCode::Char('1')));
assert_eq!(app.tab, Tab::Instances);
}
#[test]
fn click_tab_title_switches_tabs() {
let mut app = new_app();
let press = |col, row| mouse_at(MouseEventKind::Down(MouseButton::Left), col, row);
let start = |app: &App, tab: Tab| {
super::super::ui::tab_spans(app).into_iter().find(|(t, _, _)| *t == tab).unwrap().2
};
for tab in [Tab::Services, Tab::Ports, Tab::Inbox, Tab::Instances] {
let r = start(&app, tab);
app.on_mouse(&press(r.end - 1, 0), FRAME);
assert_eq!(app.tab, tab);
}
// The divider after a title and the row below hit nothing.
let r = start(&app, Tab::Services);
app.on_mouse(&press(r.end, 0), FRAME);
app.on_mouse(&press(r.start, 1), FRAME);
assert_eq!(app.tab, Tab::Instances);
// Not under the prompt or a modal.
app.on_key(key(KeyCode::Char(':')));
app.on_mouse(&press(r.start, 0), FRAME);
assert_eq!(app.tab, Tab::Instances);
app.on_key(key(KeyCode::Esc));
app.on_key(key(KeyCode::Char('?')));
app.on_mouse(&press(r.start, 0), FRAME);
assert_eq!(app.tab, Tab::Instances);
}
/// No machine: Machines isn't listed, `5` is a no-op and cycling skips
/// it. One machine, whatever its link state: listed last, reached by
/// `5`, `tab`/`S-tab` (wrapping both ways) and a click on its title.
#[test]
fn machines_tab_listed_only_with_a_machine() {
use crate::serve::snapshots::LinkState;
use crate::tui::remote::tests::sm;
let mut app = new_app();
let listed = |app: &App| super::super::ui::tab_spans(app).into_iter().map(|(t, _, _)| t).collect::<Vec<_>>();
assert_eq!(app.tabs(), vec![Tab::Instances, Tab::Services, Tab::Ports, Tab::Inbox]);
assert_eq!(listed(&app), app.tabs());
app.on_key(key(KeyCode::Char('5')));
assert_eq!(app.tab, Tab::Instances);
app.on_key(key(KeyCode::Char('4')));
app.on_key(key(KeyCode::Tab));
assert_eq!(app.tab, Tab::Instances, "wraps past the unlisted tab");
app.on_key(key(KeyCode::BackTab));
assert_eq!(app.tab, Tab::Inbox);
app.set_machines(vec![sm("box", LinkState::Unreachable)]);
assert_eq!(app.tabs(), Tab::ALL.to_vec());
assert_eq!(listed(&app), Tab::ALL.to_vec());
app.on_key(key(KeyCode::Tab));
assert_eq!(app.tab, Tab::Machines);
app.on_key(key(KeyCode::Tab));
assert_eq!(app.tab, Tab::Instances);
app.on_key(key(KeyCode::BackTab));
assert_eq!(app.tab, Tab::Machines);
app.on_key(key(KeyCode::Char('1')));
app.on_key(key(KeyCode::Char('5')));
assert_eq!(app.tab, Tab::Machines);
app.on_key(key(KeyCode::Char('1')));
let r = super::super::ui::tab_spans(&app).into_iter().find(|(t, _, _)| *t == Tab::Machines).unwrap().2;
app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Left), r.end - 1, 0), FRAME);
assert_eq!(app.tab, Tab::Machines);
}
/// The selection clamps as the list shrinks; the last machine gone
/// while the tab is open lands on Instances. Keys of other tabs
/// (`l`, `e`, `t`, `d`, `p`) do nothing here.
#[test]
fn set_machines_clamps_and_leaves_an_emptied_tab() {
use crate::serve::snapshots::LinkState;
use crate::tui::remote::tests::sm;
let mut app = new_app();
app.set_snapshot(snapshot_with_status(1, running()));
app.set_machines(vec![sm("a", LinkState::Connected), sm("b", LinkState::Idle), sm("c", LinkState::Idle)]);
app.on_key(key(KeyCode::Char('5')));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down));
assert_eq!(app.selected(), 2);
for c in ['l', 'e', 'd', 'p'] {
app.on_key(key(KeyCode::Char(c)));
assert!(matches!(app.modal, Modal::None) && app.prompt.is_none(), "{c}");
}
assert!(app.pending_fetch.is_empty() && app.take_pending_unport().is_none());
app.on_key(key(KeyCode::Char('t')));
assert!(app.terms.sessions().is_empty());
assert_eq!(app.status.as_deref(), Some("terminal: not available on the Machines tab"));
app.set_machines(vec![sm("a", LinkState::Connected)]);
assert_eq!(app.selected(), 0);
assert_eq!(app.tab, Tab::Machines);
app.set_machines(Vec::new());
assert_eq!(app.tab, Tab::Instances);
}
#[test]
fn click_tab_unfocuses_a_terminal() {
let mut app = new_app();
open_test_term(&mut app, "web-1", "devsandbox-web-1");
assert_eq!(app.focus, Focus::Terminal);
let r = super::super::ui::tab_spans(&app).into_iter().find(|(t, _, _)| *t == Tab::Ports).unwrap().2;
app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Left), r.start, 0), FRAME);
assert_eq!(app.tab, Tab::Ports);
assert_eq!(app.focus, Focus::Dashboard);
}
#[test]
fn set_ports_reclamps_selection() {
let mut app = new_app();
app.tab = Tab::Ports;
app.set_ports(port_rows(3));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down));
assert_eq!(app.selected(), 2);
app.set_ports(port_rows(1));
assert_eq!(app.selected(), 0);
app.set_ports(port_rows(0));
assert_eq!(app.selected(), 0);
}
#[test]
fn quit_keys() {
let mut app = new_app();
app.on_key(key(KeyCode::Char('q')));
assert!(app.should_quit);
let mut app = new_app();
app.on_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
assert!(app.should_quit);
let mut app = new_app();
app.on_key(key(KeyCode::Char('c')));
assert!(!app.should_quit);
}
}