eclipse-cli 0.13.4

Command-line interface for eclipse
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
//! The two things that make a CLI feel alive: a panel that says what this agent is, and a
//! line under the prompt that says how the last turn went.
//!
//! Both are pure formatting over data the core already has, so they are testable without a
//! terminal and cost nothing when the output is not a TTY (colours off, same layout).
//!
//! What is shown is what is actually known. A server that reports no usage gets `--`, never a
//! made-up number: the whole point of this line is to be trusted at a glance.

use eclipse_core::router::{describe_hops, Hop, RoleRoute, RouteInfo};
use eclipse_core::usage::{TurnUsage, UsageTotals};
use std::time::Instant;

use crate::ui::Style;

/// Everything the status line and the panel render from.
pub struct Status {
    pub model: String,
    /// Where the requests go, trimmed to `host:port` — the scheme and path are noise here.
    pub endpoint: String,
    pub profile: Option<String>,
    pub workspace: String,
    pub session: Option<String>,
    pub budget: usize,
    /// The model's own window when it is known and different from the budget — the rail is
    /// a share of it, and `budget 278k` deserves to say it is 85% of 327k. 0 = unknown.
    pub window: usize,
    /// Turns kept verbatim at the tail by the compaction policy; 0 = not known here, and then
    /// the policy line leaves the clause out rather than inventing one.
    pub keep: usize,
    /// The model's last reported cost for one request.
    pub last: Option<TurnUsage>,
    /// The runtime's estimate of the prompt it assembled last. A fallback for the bar when
    /// the server reports no usage; the server's own count always wins.
    pub context_tokens: Option<usize>,
    pub totals: UsageTotals,
    pub started: Instant,
    /// Whether the next turn answers every tool call itself — `--yes`, `[cli] approval =
    /// "auto"`, or `/yolo on`. Read per turn, because the composer can flip it mid-session.
    pub approvals: bool,
    /// The run budget in turns and the tool gate, as the loop will actually use them (0 =
    /// not known, and then the row is left out rather than guessed).
    pub max_iterations: usize,
    pub concurrency: usize,
    /// The chain a run tries, in order. Shown only when there is something to say: more than
    /// one route, or a pin. A lone `default` route is the ordinary case and stays unmentioned.
    pub routes: Vec<RouteInfo>,
    /// Whether `routes` is a pin (`--route`) rather than a fallback chain.
    pub pinned: bool,
    /// Which route each role uses. Only roles with a route of their own are shown: with `aux`
    /// unset every role uses the selected route, and saying so would be noise.
    pub roles: Vec<RoleRoute>,
    /// What hopped during the last run; empty when nothing did.
    pub last_hops: Vec<Hop>,
    /// The reasoning effort the next request will carry (`#264`). Read from the agent's dial, never
    /// re-derived from `config.toml` — `/reasoning` changes it mid-session, and a front end that
    /// read the file would keep reporting the old level.
    pub effort: Option<eclipse_core::reasoning::InForce>,
    /// `#340`: `[cli] approval = "smart"`, so a call can be settled by the aux route without a
    /// card. Shown on the same row as `/yolo` for the same reason: a mode that decides without
    /// asking has to be visible while it is deciding.
    pub judged: bool,
}

/// `summary → cheap, delegate → big`: the roles that have a route in effect, on one line;
/// `None` when none does. A pinned run shows its roles because the pin, not the config, is
/// what decided them.
pub fn roles_line(roles: &[RoleRoute]) -> Option<String> {
    let set: Vec<String> = roles
        .iter()
        .filter(|r| r.set || r.pinned)
        .map(|r| r.to_string())
        .collect();
    (!set.is_empty()).then(|| set.join(", "))
}

/// `local → big → cloud`, or `local (pinned)`: the chain on one line.
pub fn chain_line(routes: &[RouteInfo], pinned: bool) -> String {
    let names: Vec<&str> = routes.iter().map(|r| r.name.as_str()).collect();
    let line = names.join(" \u{2192} ");
    if pinned {
        format!("{line} (pinned, no fallback)")
    } else {
        line
    }
}

impl Status {
    pub fn new(model: &str, endpoint: &str, budget: usize, workspace: String) -> Self {
        Self {
            model: model.to_string(),
            endpoint: endpoint.to_string(),
            profile: None,
            workspace,
            session: None,
            budget,
            window: 0,
            keep: 0,
            last: None,
            context_tokens: None,
            totals: UsageTotals::default(),
            started: Instant::now(),
            approvals: false,
            max_iterations: 0,
            concurrency: 1,
            routes: Vec::new(),
            pinned: false,
            roles: Vec::new(),
            last_hops: Vec::new(),
            effort: None,
            judged: false,
        }
    }

    /// Record what hopped during a run and point the model and endpoint at the route that
    /// answered, so the line under the prompt names the server the last reply came from. A run
    /// that did not hop puts the first route back only if an earlier one had moved it, which
    /// leaves a model chosen with `/model` alone.
    pub fn record_hops(&mut self, hops: Vec<Hop>) {
        let moved = !self.last_hops.is_empty();
        let answered = match hops.last() {
            Some(h) => self.routes.iter().find(|r| r.name == h.to),
            None if moved => self.routes.first(),
            None => None,
        };
        if let Some(r) = answered {
            self.model = r.model.clone();
            self.endpoint = endpoint_host(&r.endpoint);
        }
        self.last_hops = hops;
    }

    /// Whether the chain is worth a row: a pin, or more than one route.
    fn shows_routes(&self) -> bool {
        self.pinned || self.routes.len() > 1
    }

    /// Fold in one request's cost.
    pub fn record(&mut self, usage: TurnUsage) {
        self.totals.add(&usage);
        self.last = Some(usage);
    }

    /// Fold in one request, adopting the runtime's own view of the prompt size and budget —
    /// those are measured after trimming, so they are better than anything the CLI can guess.
    /// The prompt size to show: the server's own count when it reported one, else the
    /// runtime's estimate. Never zero-filled — a missing figure stays missing.
    pub fn context_used(&self) -> Option<usize> {
        self.last
            .as_ref()
            .and_then(|u| u.prompt_tokens)
            .map(|t| t as usize)
            .or(self.context_tokens)
            .filter(|t| *t > 0)
    }

    pub fn record_with_context(
        &mut self,
        usage: TurnUsage,
        context_tokens: usize,
        budget_tokens: usize,
    ) {
        self.context_tokens = (context_tokens > 0).then_some(context_tokens);
        if budget_tokens > 0 {
            self.budget = budget_tokens;
        }
        self.record(usage);
    }

    /// The bar's denominator: the model's own window when anyone stated one, else the
    /// configured rail, which is all that is known then. 0 = nothing known to be a share of.
    pub fn denominator(&self) -> usize {
        if self.window > 0 {
            self.window
        } else {
            self.budget
        }
    }

    /// The bar as `eclipse_core::contextbar` reads it: what was used, out of what, and where the
    /// tripwire is. One shape for three surfaces.
    pub fn reading(&self) -> eclipse_core::contextbar::Reading {
        eclipse_core::contextbar::Reading::new(
            self.context_used().map(|c| c as u64),
            self.denominator(),
            self.marker_share(),
        )
    }

    /// Where compaction begins, as a share of the window — or `None` when there is no window
    /// to be a share of, when the threshold is off, or when it sits at the hard limit.
    pub fn marker_share(&self) -> Option<f64> {
        if self.window == 0 || self.budget == 0 || self.budget >= self.window {
            return None;
        }
        Some(self.budget as f64 / self.window as f64)
    }
}

/// `10 turns · tools one at a time`: the loop's two numbers, in the same words everywhere
/// they are shown (the panel, `/status`), so the CLI never says two things about one run.
pub fn loop_line(turns: usize, concurrency: usize) -> String {
    format!(
        "{turns} turn{} · tools {}",
        if turns == 1 { "" } else { "s" },
        match concurrency {
            0 | 1 => "one at a time".to_string(),
            n => format!("{n} at a time"),
        }
    )
}

/// Session ids are long; the tail is the part that differs between two sessions started in the
/// same second, so that is the part worth the columns.
pub fn short_session(id: &str) -> String {
    let tail: String = id
        .chars()
        .rev()
        .take(8)
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    if id.chars().count() > 8 {
        format!("…{tail}")
    } else {
        id.to_string()
    }
}

/// `budget 279K of 328K window · compacts at 85% · keeps last 20 turns verbatim`, the one line
/// the panel, `/status` and the banner share so no two surfaces describe one run differently.
///
/// `0` budget with a known window means the threshold is off (`compact_at = 0`), which is a
/// policy worth naming rather than an absence to hide behind "no budget set".
pub fn budget_line(budget: usize, window: usize, keep: usize) -> String {
    let tail = match keep {
        0 => String::new(),
        1 => " · keeps the newest turn verbatim".to_string(),
        n => format!(" · keeps last {n} turns verbatim"),
    };
    match (budget, window) {
        (0, 0) => "no budget set".to_string(),
        (0, w) => format!("window {} · compaction off", short_tokens(w as u64)),
        (b, w) if w > b => format!(
            "budget {} of {} window · compacts at {:.0}%{tail}",
            short_tokens(b as u64),
            short_tokens(w as u64),
            b as f64 / w as f64 * 100.0
        ),
        (b, 0) => format!("budget {} · window unknown", short_tokens(b as u64)),
        (b, w) => format!(
            "budget {} of {} window",
            short_tokens(b as u64),
            short_tokens(w as u64)
        ),
    }
}

/// The bar's arithmetic is `eclipse_core::contextbar`'s, and so is the wording of the read-out:
/// the terminal, the full-screen interface and the dashboard all draw one shape, so a percentage
/// means the same thing on every screen. What stays here is the colouring, because a `Style` is
/// this crate's idea and not the core's.
pub use eclipse_core::contextbar::{bar_marked, short_tokens, MARKER};

/// The marked bar with the tripwire painted apart from the fill. `status` returns text, so the
/// caller owns colour — here and in the TUI, so both surfaces colour it the same way.
fn marked_bar(style: &Style, share: f64, marker: f64, width: usize) -> String {
    let bar = bar_marked(share, marker, width);
    let mut out = String::new();
    for (i, piece) in bar.split(MARKER).enumerate() {
        if i > 0 {
            out.push_str(&style.red(&MARKER.to_string()));
        }
        out.push_str(&style.amber(piece));
    }
    out
}

/// `8330` → `8.3s`, `95_000` → `1m35s`, `3_600_000` → `1h00m`.
pub fn short_duration(ms: u64) -> String {
    match ms {
        0..=9_999 => format!("{:.1}s", ms as f64 / 1000.0),
        10_000..=59_999 => format!("{:.0}s", ms as f64 / 1000.0),
        60_000..=3_599_999 => {
            let secs = ms / 1000;
            format!("{}m{:02}s", secs / 60, secs % 60)
        }
        _ => {
            let mins = ms / 60_000;
            format!("{}h{:02}m", mins / 60, mins % 60)
        }
    }
}

fn opt<T: std::fmt::Display>(v: Option<T>) -> String {
    v.map(|x| x.to_string()).unwrap_or_else(|| "--".to_string())
}

impl Status {
    /// The line above the prompt: identity, context fill, and what the last request cost.
    pub fn line(&self, style: &Style) -> String {
        let mut parts: Vec<String> = Vec::new();
        parts.push(style.bold(&self.model));

        // Context fill: the last assembled prompt as a share of the model's window, with the
        // compaction threshold marked. The bar's end is the model's limit, not the rail. The
        // numbers, the bar and the percentage are `contextbar`'s; the colour is this surface's.
        let reading = self.reading();
        let piece = reading.pieces(12);
        let mut ctx = format!("ctx {}", style.dim(&piece.numbers));
        if !piece.bar.is_empty() {
            ctx.push(' ');
            ctx.push_str(&marked_bar(
                style,
                reading.share().unwrap_or(0.0),
                reading.marker.unwrap_or(0.0),
                12,
            ));
        }
        if let Some(percent) = &piece.percent {
            ctx.push(' ');
            ctx.push_str(&style.dim(percent));
        }
        // No `· no budget` here. This line is reprinted under every prompt, and the case it
        // explains is the plain `ctx --` of a session with nothing configured — `--` is already
        // the truth, and `/status` and the dashboard say the rest in words.
        if reading.passed() {
            ctx.push_str(&style.dim(&format!(
                " · compacts at {:.0}%",
                reading.marker.unwrap_or(0.0) * 100.0
            )));
        }
        parts.push(ctx);

        // The effort the next request will carry, every frame (#264). Before this, a session
        // could have `/reasoning high` in force with nothing on screen saying so once the note
        // had scrolled away — the one knob whose state is invisible until the bill arrives.
        if let Some(effort) = &self.effort {
            // Amber only while the session is the reason: the ordinary case is the file's level,
            // and a read-out that shouts every frame says nothing.
            parts.push(if effort.session {
                style.amber(&format!("effort {}", effort.label))
            } else {
                style.dim(&format!("effort {}", effort.label))
            });
        }

        if let Some(last) = &self.last {
            if let Some(ms) = last.ttft_ms {
                parts.push(style.dim(&format!("first {}", short_duration(ms))));
            }
            parts.push(style.dim(&short_duration(last.latency_ms)));
            if let Some(tps) = last.tokens_per_sec() {
                parts.push(style.dim(&format!("↑{:.0} t/s", tps)));
            }
            // Cache: the tokens the server did not have to prefill.
            match (last.cached_tokens, last.prompt_tokens) {
                (Some(c), Some(p)) if p > 0 => parts.push(style.dim(&format!(
                    "⚡{} ({:.0}%)",
                    short_tokens(c),
                    c as f64 / p as f64 * 100.0
                ))),
                (Some(c), _) => parts.push(style.dim(&format!("⚡{}", short_tokens(c)))),
                _ => {}
            }
        }

        if self.totals.turns > 1 {
            parts.push(style.dim(&format!(
                "Σ ↑{} · ↓{}",
                short_tokens(self.totals.prompt_tokens),
                short_tokens(self.totals.completion_tokens)
            )));
        }
        parts.push(style.dim(&short_duration(self.started.elapsed().as_millis() as u64)));
        // Only while it is on: the readout's job is to say what is unusual about this session,
        // and `ask` is the ordinary answer the config already gave.
        if self.approvals {
            parts.push(style.amber("approvals: auto"));
        }
        parts.push(style.dim(&self.workspace_short()));
        parts.join(&style.dim(" · "))
    }

    fn workspace_short(&self) -> String {
        match std::env::var_os("HOME").and_then(|h| h.into_string().ok()) {
            Some(home) if !home.is_empty() && self.workspace.starts_with(&home) => {
                format!("~{}", &self.workspace[home.len()..])
            }
            _ => self.workspace.clone(),
        }
    }

    /// The `/status` read-out: everything known, nothing repeated from the line above.
    pub fn detail(&self, style: &Style) -> String {
        let mut out = String::new();
        let mut row = |k: &str, v: String| {
            if !out.is_empty() {
                out.push('\n');
            }
            out.push_str(&format!("  {} {v}", style.dim(&format!("{k:<13}"))));
        };
        row("model", style.bold(&self.model));
        row("endpoint", self.endpoint.clone());
        if self.shows_routes() {
            row("routes", chain_line(&self.routes, self.pinned));
            for r in &self.routes {
                row(
                    "",
                    format!("{}: {} @ {}", r.name, r.model, endpoint_host(&r.endpoint)),
                );
            }
        }
        if let Some(roles) = roles_line(&self.roles) {
            row("roles", roles);
        }
        if let Some(hops) = describe_hops(&self.last_hops) {
            row("last hop", hops.trim_start_matches("route: ").to_string());
        }
        row(
            "profile",
            self.profile.clone().unwrap_or_else(|| "default".into()),
        );
        row("context", budget_line(self.budget, self.window, self.keep));
        // `#264`: what the *next* request will ask for, and what that becomes on the route in
        // force. The long form is the point — `high (this session; config.toml says low)` is the
        // sentence a person needs when the level they set is not the level the file names.
        if let Some(effort) = &self.effort {
            row("reasoning", effort.sentence());
        }
        if self.max_iterations > 0 {
            row("loop", loop_line(self.max_iterations, self.concurrency));
        }
        row(
            "session",
            self.session.clone().unwrap_or_else(|| "new".into()),
        );
        row("workspace", self.workspace.clone());
        let t = &self.totals;
        row(
            "this process",
            format!(
                "{} request(s) · ↑{} prompt · ↓{} generated{}",
                t.turns,
                short_tokens(t.prompt_tokens),
                short_tokens(t.completion_tokens),
                match t.cache_ratio() {
                    Some(r) => format!(" · cache {:.0}%", r * 100.0),
                    None => String::new(),
                }
            ),
        );
        if let Some(last) = &self.last {
            row(
                "last request",
                format!(
                    "prompt {} ({} cached) · {} generated · {} prefill · {} decode · {} wall{}",
                    opt(last.prompt_tokens),
                    opt(last.cached_tokens),
                    opt(last.completion_tokens),
                    last.prompt_ms
                        .map(short_duration)
                        .unwrap_or_else(|| "--".into()),
                    last.completion_ms
                        .map(short_duration)
                        .unwrap_or_else(|| "--".into()),
                    short_duration(last.latency_ms),
                    match (last.tokens_per_sec(), last.ttft_ms) {
                        (Some(tps), Some(ttft)) => {
                            format!(" · {tps:.1} t/s · first token {}", short_duration(ttft))
                        }
                        (Some(tps), None) => format!(" · {tps:.1} t/s"),
                        _ => String::new(),
                    }
                ),
            );
        }
        out
    }
}

/// `https://host:port/v1` → `host:port`.
fn endpoint_host(url: &str) -> String {
    url.split("://")
        .last()
        .unwrap_or(url)
        .split('/')
        .next()
        .unwrap_or(url)
        .to_string()
}

/// Break `text` on commas into lines of at most `width` characters, so a long tool list
/// stays readable instead of running off the edge of the terminal.
/// One row of the panel: a label column plus a value.
fn emit(out: &mut String, style: &Style, label: &str, value: &str) {
    out.push_str(&format!(
        "  {} {value}\n",
        style.amber(&format!("{label:<10}"))
    ));
}

fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    let mut line = String::new();
    for piece in text.split(", ") {
        if !line.is_empty() && line.chars().count() + 2 + piece.chars().count() > width {
            lines.push(std::mem::take(&mut line));
        }
        if !line.is_empty() {
            line.push_str(", ");
        }
        line.push_str(piece);
    }
    if !line.is_empty() {
        lines.push(line);
    }
    if lines.is_empty() {
        lines.push(String::new());
    }
    lines
}

/// The startup panel: what this process is, what it can do, and where it is pointed.
///
/// Sections are omitted when empty rather than shown as `(none)` — an empty plugin list is
/// not news, and a panel full of empty sections hides the parts that matter.
pub struct Panel {
    pub version: String,
    pub model: String,
    pub endpoint: String,
    pub profile: Option<String>,
    pub workspace: String,
    pub session: Option<String>,
    pub budget: usize,
    /// The model's own window when it is known and different from the budget — the rail is
    /// a share of it, and `budget 278k` deserves to say it is 85% of 327k. 0 = unknown.
    pub window: usize,
    /// Turns kept verbatim at the tail by the compaction policy; 0 = not known here, and then
    /// the policy line leaves the clause out rather than inventing one.
    pub keep: usize,
    /// The loop's own two numbers: how many turns a run gets and how many tool calls may
    /// run at once (0 turns = not known, and the row is omitted).
    pub max_iterations: usize,
    pub concurrency: usize,
    pub stream: bool,
    /// Whether the next turn answers every tool call itself (`--yes`, `[cli] approval = "auto"`,
    /// or `/yolo on`). On the panel because a session that has been answering everything for an
    /// hour must not look like one that has not.
    pub approvals: bool,
    /// The route chain, as [`Status::routes`].
    pub routes: Vec<RouteInfo>,
    pub pinned: bool,
    /// The role table, as [`Status::roles`].
    pub roles: Vec<RoleRoute>,
    pub tools: Vec<String>,
    pub plugins: Vec<String>,
    pub plugin_problems: Vec<String>,
}

impl Panel {
    pub fn render(&self, style: &Style) -> String {
        let rule = style.dim(&"─".repeat(72));
        let mut out = String::new();
        out.push_str(&format!(
            "\n  {} {}\n",
            style.amber("◐"),
            style.bold(&format!("eclipse {}", self.version))
        ));
        out.push_str(&format!(
            "  {}\n\n",
            style.dim(&format!(
                "{} · {} · {}{}",
                self.model,
                self.endpoint,
                if self.stream { "stream" } else { "no stream" },
                match &self.profile {
                    Some(p) => format!(" · profile {p}"),
                    None => String::new(),
                }
            ))
        ));
        out.push_str(&format!("{rule}\n"));

        if self.pinned || self.routes.len() > 1 {
            emit(
                &mut out,
                style,
                "routes",
                &chain_line(&self.routes, self.pinned),
            );
            for r in &self.routes {
                out.push_str(&format!("  {}{}: {}\n", " ".repeat(11), r.name, r.model));
            }
        }
        if let Some(roles) = roles_line(&self.roles) {
            emit(&mut out, style, "roles", &roles);
        }
        if !self.tools.is_empty() {
            let body = format!("({}) {}", self.tools.len(), self.tools.join(", "));
            let mut lines = wrap(&body, 76);
            let head = lines.remove(0);
            emit(&mut out, style, "tools", &head);
            for extra in lines {
                out.push_str(&format!("  {}{extra}\n", " ".repeat(11)));
            }
        }
        if !self.plugins.is_empty() {
            emit(&mut out, style, "plugins", &self.plugins.join(", "));
        }
        for problem in &self.plugin_problems {
            emit(&mut out, style, "", &style.yellow(problem));
        }
        emit(
            &mut out,
            style,
            "context",
            &budget_line(self.budget, self.window, self.keep),
        );
        if self.max_iterations > 0 {
            emit(
                &mut out,
                style,
                "loop",
                &loop_line(self.max_iterations, self.concurrency),
            );
        }
        // Amber while it is on, and the plain word while it is not: the state that skips a
        // dangerous call is the one that has to catch the eye.
        let approvals = if self.approvals {
            style.amber("auto")
        } else {
            "ask".to_string()
        };
        emit(&mut out, style, "approvals", &approvals);
        emit(&mut out, style, "workspace", &self.workspace);
        emit(
            &mut out,
            style,
            "session",
            self.session.as_deref().unwrap_or("new"),
        );
        out.push_str(&format!("{rule}\n"));

        out.push_str(&format!(
            "  {}\n\n",
            style.dim(&format!(
                "{} tools{} · /help for commands · Ctrl-C stops a run, Ctrl-D exits",
                self.tools.len(),
                if self.plugins.is_empty() {
                    String::new()
                } else {
                    format!(" · {} plugins", self.plugins.len())
                }
            ))
        ));
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn plain() -> Style {
        Style::plain()
    }

    /// Labels are padded to a column, so assertions about `label value` pairs collapse runs
    /// of spaces first rather than hard-coding the padding.
    fn flat(s: &str) -> String {
        s.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    fn chain() -> Vec<RouteInfo> {
        ["local", "big", "cloud"]
            .iter()
            .map(|n| RouteInfo {
                name: (*n).to_string(),
                model: format!("{n}-model"),
                endpoint: format!("http://{n}:8080/v1"),
            })
            .collect()
    }

    /// `#264`: the effort the next request carries is on the line, it comes from the dial, and it
    /// shouts only while the session is the reason — a read-out that is always bright says nothing.
    #[test]
    fn the_effort_in_force_is_on_the_line_and_is_read_from_the_dial() {
        use eclipse_core::reasoning::Dial;

        let style = Style::plain();
        let mut s = Status::new("m", "h:1", 1000, "/w".into());
        assert!(
            !s.line(&style).contains("effort"),
            "nothing known, nothing claimed: {}",
            s.line(&style)
        );

        // The file's level: on the line, quiet.
        let dial = Dial::new(Some("low".into()));
        s.effort = Some(dial.in_force_report(None));
        let line = flat(&s.line(&style));
        assert!(line.contains("effort low"), "{line}");

        // `/reasoning high` moves the dial under a running status line, and the line follows — the
        // whole point of reading it here rather than from `[provider] reasoning_effort`.
        dial.set_session(Some("high".into()));
        s.effort = Some(dial.in_force_report(None));
        let line = flat(&s.line(&style));
        assert!(line.contains("effort high"), "{line}");
        assert!(
            s.effort.as_ref().unwrap().session,
            "and the line knows the session is why"
        );

        // `/status` says the same thing in words, including what the file wanted.
        let detail = flat(&s.detail(&style));
        assert!(
            detail.contains("reasoning high (this session; config.toml says low)"),
            "{detail}"
        );
    }

    #[test]
    fn status_shows_the_chain_with_the_model_each_route_serves() {
        let mut s = Status::new("local-model", "local:8080", 1000, "/w".into());
        s.routes = chain();
        let detail = flat(&s.detail(&plain()));
        assert!(
            detail.contains("routes local \u{2192} big \u{2192} cloud"),
            "{detail}"
        );
        assert!(detail.contains("big: big-model @ big:8080"), "{detail}");
    }

    #[test]
    fn status_says_what_hopped_after_a_run_and_nothing_before_one() {
        let mut s = Status::new("m", "h:1", 1000, "/w".into());
        s.routes = chain();
        assert!(!s.detail(&plain()).contains("last hop"));
        s.last_hops = vec![Hop {
            from: "local".into(),
            to: "big".into(),
            reason: "timeout".into(),
        }];
        let detail = flat(&s.detail(&plain()));
        assert!(
            detail.contains("last hop local \u{2192} big (timeout)"),
            "{detail}"
        );
    }

    #[test]
    fn a_lone_default_route_is_not_worth_a_row() {
        let mut s = Status::new("m", "h:1", 1000, "/w".into());
        s.routes = chain().into_iter().take(1).collect();
        assert!(!s.detail(&plain()).contains("routes"));
    }

    #[test]
    fn a_pinned_route_is_shown_as_pinned_with_no_fallback() {
        let mut s = Status::new("m", "h:1", 1000, "/w".into());
        s.routes = chain().into_iter().take(1).collect();
        s.pinned = true;
        let detail = flat(&s.detail(&plain()));
        assert!(
            detail.contains("routes local (pinned, no fallback)"),
            "{detail}"
        );
    }

    fn roles(aux: Option<&str>) -> Vec<RoleRoute> {
        eclipse_core::router::role_table(aux, None, "local", false)
    }

    /// `#226`: the panel is where a `--yes` run admits it, and `ask` is said plainly while `auto`
    /// is the one that catches the eye.
    #[test]
    fn the_panel_names_the_approval_mode_and_the_readout_only_mentions_auto() {
        let mut s = Status::new("m", "h:1", 1000, "/w".into());
        assert!(
            !s.line(&plain()).contains("approvals"),
            "an ordinary session stays as quiet as it was: {}",
            s.line(&plain())
        );
        s.approvals = true;
        assert!(
            s.line(&plain()).contains("approvals: auto"),
            "{}",
            s.line(&plain())
        );
        s.approvals = false;
        assert!(!s.line(&plain()).contains("approvals"));

        let mut panel = Panel {
            version: "0".into(),
            model: "m".into(),
            endpoint: "h:1".into(),
            profile: None,
            workspace: "/w".into(),
            session: None,
            budget: 1000,
            window: 0,
            keep: 0,
            max_iterations: 0,
            concurrency: 0,
            stream: true,
            approvals: true,
            routes: vec![],
            pinned: false,
            roles: vec![],
            tools: vec![],
            plugins: vec![],
            plugin_problems: vec![],
        };
        assert!(
            flat(&panel.render(&plain())).contains("approvals auto"),
            "{}",
            panel.render(&plain())
        );
        // `auto` is the state that skips a dangerous call; amber is how the panel says so. The
        // colour is forced on: a captured stdout is a pipe, and `for_stdout` would drop it.
        let coloured = Style::coloured();
        assert!(
            panel.render(&coloured).contains("\u{1b}[38;5;214mauto"),
            "amber while automatic: {:?}",
            panel.render(&coloured)
        );
        panel.approvals = false;
        let said = panel.render(&plain());
        assert!(flat(&said).contains("approvals ask"), "{said}");
        assert!(!said.contains("\u{1b}[38;5;214mauto"), "{said}");
    }

    #[test]
    fn status_and_the_panel_name_the_roles_that_have_a_route_and_say_nothing_when_none_does() {
        let mut s = Status::new("m", "h:1", 1000, "/w".into());
        s.routes = chain();
        s.roles = roles(Some("cheap"));
        assert!(
            flat(&s.detail(&plain())).contains("roles judgement \u{2192} cheap"),
            "{}",
            s.detail(&plain())
        );
        s.roles = roles(None);
        assert!(!s.detail(&plain()).contains("roles"));

        let mut panel = Panel {
            version: "0".into(),
            model: "m".into(),
            endpoint: "h:1".into(),
            profile: None,
            workspace: "/w".into(),
            session: None,
            budget: 0,
            window: 0,
            keep: 0,
            max_iterations: 10,
            concurrency: 1,
            stream: true,
            approvals: false,
            routes: chain(),
            pinned: false,
            roles: roles(Some("cheap")),
            tools: Vec::new(),
            plugins: Vec::new(),
            plugin_problems: Vec::new(),
        };
        assert!(
            flat(&panel.render(&plain())).contains("roles judgement \u{2192} cheap"),
            "{}",
            panel.render(&plain())
        );
        panel.roles = roles(None);
        assert!(!panel.render(&plain()).contains("roles"));
    }

    #[test]
    fn the_roles_row_lists_only_the_roles_with_a_route_of_their_own() {
        let both = eclipse_core::router::role_table(Some("cheap"), Some("big"), "local", false);
        assert_eq!(
            roles_line(&both).unwrap(),
            "judgement \u{2192} cheap, delegate \u{2192} big"
        );
        let delegate_only = eclipse_core::router::role_table(None, Some("big"), "local", false);
        assert_eq!(roles_line(&delegate_only).unwrap(), "delegate \u{2192} big");
        assert_eq!(roles_line(&roles(None)), None);
    }

    #[test]
    fn a_pinned_run_says_its_roles_are_pinned_rather_than_configured() {
        // The config asks for `cheap` and `big`; `--route local` wins, and the line must say so
        // rather than quietly reporting the routes that were overruled.
        let pinned = eclipse_core::router::role_table(Some("cheap"), Some("big"), "local", true);
        assert_eq!(
            roles_line(&pinned).unwrap(),
            "judgement \u{2192} local (pinned), delegate \u{2192} local (pinned)"
        );
        assert!(pinned.iter().all(|r| !r.set && r.pinned));
    }

    #[test]
    fn the_startup_panel_shows_the_chain_when_there_is_one() {
        let panel = Panel {
            version: "0".into(),
            model: "local-model".into(),
            endpoint: "http://local:8080/v1".into(),
            profile: None,
            workspace: "/w".into(),
            session: None,
            budget: 0,
            window: 0,
            keep: 0,
            max_iterations: 10,
            concurrency: 1,
            stream: true,
            approvals: false,
            routes: chain(),
            pinned: false,
            roles: Vec::new(),
            tools: Vec::new(),
            plugins: Vec::new(),
            plugin_problems: Vec::new(),
        };
        let shown = flat(&panel.render(&plain()));
        assert!(
            shown.contains("routes local \u{2192} big \u{2192} cloud"),
            "{shown}"
        );
        assert!(shown.contains("cloud: cloud-model"), "{shown}");
    }

    #[test]
    fn the_model_follows_the_route_that_answered_and_returns_when_a_run_does_not_hop() {
        let mut s = Status::new("local-model", "local:8080", 1000, "/w".into());
        s.routes = chain();
        s.record_hops(vec![Hop {
            from: "local".into(),
            to: "big".into(),
            reason: "timeout".into(),
        }]);
        assert_eq!(
            (s.model.as_str(), s.endpoint.as_str()),
            ("big-model", "big:8080")
        );
        s.record_hops(Vec::new());
        assert_eq!(
            (s.model.as_str(), s.endpoint.as_str()),
            ("local-model", "local:8080")
        );
        assert!(s.last_hops.is_empty());
    }

    #[test]
    fn the_policy_line_names_the_threshold_and_what_is_kept() {
        assert_eq!(
            budget_line(278_528, 327_680, 20),
            "budget 279K of 328K window · compacts at 85% · keeps last 20 turns verbatim"
        );
        assert_eq!(
            budget_line(0, 327_680, 20),
            "window 328K · compaction off",
            "compact_at = 0 says so rather than hiding behind `no budget set`"
        );
        assert_eq!(budget_line(0, 0, 0), "no budget set");
        assert_eq!(
            budget_line(200_000, 0, 0),
            "budget 200K · window unknown",
            "a rail with no window is stated as such"
        );
        assert_eq!(
            budget_line(131_072, 131_072, 1),
            "budget 131K of 131K window"
        );
    }

    #[test]
    fn durations_read_like_a_person_wrote_them() {
        assert_eq!(short_duration(0), "0.0s");
        assert_eq!(short_duration(8330), "8.3s");
        assert_eq!(short_duration(42_000), "42s");
        assert_eq!(short_duration(95_000), "1m35s");
        assert_eq!(short_duration(3_700_000), "1h01m");
    }

    #[test]
    fn a_fresh_status_admits_it_knows_nothing() {
        let s = Status::new("m", "h/v1", 1000, "/w".into());
        let line = s.line(&plain());
        assert!(line.contains("ctx --/1.0K"), "{line}");
        assert!(!line.contains("t/s"), "no speed before a turn: {line}");
        assert!(!line.contains("⚡"), "no cache claim before a turn: {line}");
    }

    #[test]
    fn the_line_shows_context_fill_speed_and_cache() {
        let mut s = Status::new("inkling-2-mini", "127.0.0.1:18045", 327_680, "/w".into());
        s.record(TurnUsage {
            prompt_tokens: Some(23_100),
            completion_tokens: Some(120),
            total_tokens: Some(23_220),
            cached_tokens: Some(19_000),
            prompt_ms: Some(400),
            completion_ms: Some(8_000),
            latency_ms: 8_400,
            ttft_ms: Some(900),
        });
        let line = s.line(&plain());
        assert!(line.contains("23.1K/328K"), "{line}");
        let percent = format!(
            "{}%",
            (23100.0_f64 / 327_680.0_f64 * 100.0_f64).round() as i64
        );
        assert!(line.contains(&percent), "expected {percent} in {line}");
        assert!(line.contains("8.4s"), "{line}");
        assert!(line.contains("↑15 t/s"), "120 tokens in 8 s: {line}");
        assert!(line.contains("⚡19.0K (82%)"), "{line}");
        assert!(line.contains("first 0.9s"), "{line}");
    }

    #[test]
    fn a_silent_server_shows_dashes_not_zeros() {
        let mut s = Status::new("m", "h", 0, "/w".into());
        s.record(TurnUsage {
            latency_ms: 1200,
            ..Default::default()
        });
        let line = s.line(&plain());
        assert!(line.contains("ctx --"), "{line}");
        assert!(line.contains("1.2s"), "{line}");
        assert!(!line.contains("0 t/s"), "no invented speed: {line}");
    }

    #[test]
    fn totals_appear_once_there_is_more_than_one_turn() {
        let mut s = Status::new("m", "h", 1000, "/w".into());
        let u = TurnUsage {
            prompt_tokens: Some(100),
            completion_tokens: Some(10),
            ..Default::default()
        };
        s.record(u.clone());
        assert!(!s.line(&plain()).contains("Σ"));
        s.record(u);
        let line = s.line(&plain());
        assert!(line.contains("Σ ↑200 · ↓20"), "{line}");
    }

    #[test]
    fn the_panel_lists_tools_plugins_and_problems() {
        let panel = Panel {
            version: "0.1.0".into(),
            model: "m".into(),
            endpoint: "127.0.0.1:18045/v1".into(),
            profile: Some("work".into()),
            workspace: "/w".into(),
            session: None,
            budget: 327_680,
            window: 0,
            keep: 0,
            max_iterations: 10,
            concurrency: 3,
            stream: true,
            approvals: false,
            routes: vec![],
            roles: vec![],
            pinned: false,
            tools: vec!["read_file".into(), "shell".into()],
            plugins: vec!["git-tools 0.1.0".into()],
            plugin_problems: vec!["plugin `broken`: api 99".into()],
        };
        let text = panel.render(&plain());
        assert!(text.contains("eclipse 0.1.0"), "{text}");
        assert!(text.contains("profile work"), "{text}");
        assert!(text.contains("(2) read_file, shell"), "{text}");
        assert!(text.contains("git-tools 0.1.0"), "{text}");
        assert!(
            text.contains("api 99"),
            "problems are shown, not hidden: {text}"
        );
        assert!(flat(&text).contains("budget 328K"), "{text}");
        assert!(flat(&text).contains("session new"), "{text}");
    }

    #[test]
    fn the_panel_omits_empty_sections() {
        let panel = Panel {
            version: "0.1.0".into(),
            model: "m".into(),
            endpoint: "h".into(),
            profile: None,
            workspace: "/w".into(),
            session: Some("s1".into()),
            budget: 0,
            window: 0,
            keep: 0,
            max_iterations: 0,
            concurrency: 1,
            stream: false,
            approvals: false,
            routes: vec![],
            roles: vec![],
            pinned: false,
            tools: vec![],
            plugins: vec![],
            plugin_problems: vec![],
        };
        let text = panel.render(&plain());
        assert!(!text.contains("plugins"), "{text}");
        assert!(text.contains("no stream"), "{text}");
        assert!(text.contains("no budget set"), "{text}");
        assert!(
            !text.contains("loop"),
            "an unknown budget is left out, never invented: {text}"
        );
        assert!(flat(&text).contains("session s1"), "{text}");
    }

    #[test]
    fn the_detail_view_reports_timings_it_actually_has() {
        let mut s = Status::new("m", "h/v1", 1000, "/w".into());
        s.record(TurnUsage {
            prompt_tokens: Some(1000),
            completion_tokens: Some(50),
            total_tokens: Some(1050),
            cached_tokens: Some(900),
            prompt_ms: Some(250),
            completion_ms: Some(2000),
            latency_ms: 2400,
            ttft_ms: Some(300),
        });
        let text = s.detail(&plain());
        assert!(text.contains("prompt 1000 (900 cached)"), "{text}");
        assert!(text.contains("cache 90%"), "session cache ratio: {text}");
        assert!(text.contains("25.0 t/s"), "{text}");
        assert!(text.contains("first token 0.3s"), "{text}");
    }

    #[test]
    fn the_workspace_is_home_relative() {
        let home = std::env::var("HOME").unwrap_or_default();
        let mut s = Status::new("m", "h", 0, format!("{home}/projects/x"));
        s.record(TurnUsage::default());
        if !home.is_empty() {
            assert!(
                s.line(&plain()).contains("~/projects/x"),
                "{}",
                s.line(&plain())
            );
        }
    }

    #[test]
    fn the_loop_line_names_the_budget_and_the_gate() {
        // One wording, used by the panel and `/status`, so the two can never disagree.
        assert_eq!(loop_line(10, 1), "10 turns · tools one at a time");
        assert_eq!(loop_line(1, 4), "1 turn · tools 4 at a time");
        assert_eq!(loop_line(3, 0), "3 turns · tools one at a time");
    }
}