abstractcore-console 0.8.1

A terminal console for AbstractCore: configure models, providers and capability routes, browse, download and delete local models, and install local engines (Ollama, LM Studio, MLX, llama.cpp). Also a library of the shared Models/Engines screens, rendered by AbstractTUI.
Documentation
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
//! The section screens: one field TABLE per page (section · field ·
//! value · state), Enter/e opens the right editor for the selected
//! row, x clears optional fields. In wizard mode the table filters to
//! the step's focused section so each phase reads as one purposeful
//! form. Corrupt/missing/unreadable render their honest states.

use abstracttui::prelude::*;
use abstracttui::widgets::Table;
use serde_json::json;

use crate::config::{FieldState, FileState, Snapshot};
use crate::schema::FieldKind;
use crate::store::Loadable;
use crate::worker::Cmd;
use crate::writes;

use super::editors::open_field_editor;
use super::util::{error_panel, line, span, span_bold, switch_spans, SpanSpec, Switch};
use super::widths;
use super::Ctx;

/// Render `f` over the current snapshot, with honest states for every
/// other file condition. A MISSING file renders the fold of an empty
/// object — exactly the in-memory defaults Python runs with
/// (manager.py:529-530) — so the section pages still teach what the
/// defaults ARE (and the wizard can configure a fresh machine).
/// Corrupt/unreadable refuse with the reason.
pub fn with_snapshot(
    t: &TokenSet,
    store: &crate::store::Store,
    f: impl FnOnce(&Snapshot, bool) -> View,
) -> View {
    match store.cfg.get() {
        Loadable::NotAsked => line(vec![span("— not loaded yet (r reloads)", t.text_muted)]),
        Loadable::Loading => line(vec![span("⟳ reading config…", t.info)]),
        Loadable::Failed(e) => error_panel(t, &e),
        Loadable::Ready(m) => match &m.state {
            FileState::Ready(snap) => f(snap, false),
            FileState::Missing => f(&crate::config::fold(&json!({}), 0, None, None), true),
            FileState::Corrupt { error, backups } => corrupt_panel(t, error, backups),
            FileState::Unreadable { error } => Element::new()
                .style(LayoutStyle::column())
                .child(line(vec![span_bold("✗ config file unreadable", t.error)]))
                .child(line(vec![span(format!("  {error}"), t.text)]))
                .child(line(vec![span(
                    "  fix the path or its permissions, then press r",
                    t.text_muted,
                )]))
                .build(),
        },
    }
}

/// The corrupt-file refusal: the error, the recovery artifacts, and
/// the one rule that prevents the known data-loss incident. The
/// headline rows are PINNED — under height pressure the artifact list
/// yields, never the refusal itself (the safety copy is the point).
pub fn corrupt_panel(t: &TokenSet, error: &str, backups: &[String]) -> View {
    let head = Element::new()
        .style(LayoutStyle::column().shrink(0.0))
        .child(line(vec![span_bold(
            "✗ config file corrupt — this console will NOT write until it is fixed",
            t.error,
        )]))
        .child(line(vec![span(format!("  parse error: {error}"), t.text)]))
        .child(line(vec![span(
            "  (a Python-side save from this state would reset it to defaults — fix first)",
            t.warn,
        )]))
        .build();
    let mut rest = Element::new().style(LayoutStyle::column());
    if backups.is_empty() {
        rest = rest.child(line(vec![span(
            "  no backups found beside it — repair the JSON by hand, then press r",
            t.text_muted,
        )]));
    } else {
        rest = rest.child(line(vec![span(
            "  recovery artifacts beside it (newest first):",
            t.text_muted,
        )]));
        for b in backups.iter().take(5) {
            rest = rest.child(line(vec![span(format!("    {b}"), t.text)]));
        }
        rest = rest.child(line(vec![span(
            "  compare/restore one by hand, then press r",
            t.text_muted,
        )]));
    }
    Element::new()
        .style(LayoutStyle::column().grow(1.0))
        .child(head)
        .child(rest.build())
        .build()
}

/// The rows a page shows: (section, key) pairs in schema order,
/// filtered to the wizard's focused section when one is set.
fn page_rows(
    snap: &Snapshot,
    section_names: &'static [&'static str],
    focus: Option<&'static str>,
) -> Vec<(&'static str, &'static str)> {
    let mut out = Vec::new();
    for sv in &snap.sections {
        if !section_names.contains(&sv.spec.name) {
            continue;
        }
        if let Some(f) = focus {
            if sv.spec.name != f {
                continue;
            }
        }
        for fv in &sv.fields {
            out.push((sv.spec.name, fv.key));
        }
    }
    out
}

/// A section screen: the field table + editing verbs.
pub fn page(
    cx: Scope,
    ctx: &Ctx,
    theme: Signal<&'static abstracttui::theme::Theme>,
    section_names: &'static [&'static str],
    sel: Signal<usize>,
) -> View {
    let store = ctx.store;
    let ui = ctx.ui;
    let ctx_edit = ctx.clone();
    let ctx_clear = ctx.clone();
    let ctx_table = ctx.clone();

    let body = dyn_view_scoped(LayoutStyle::default().grow(1.0), move |gcx| {
        let t = theme.get().tokens;
        let focus = ui.focus_section.get().filter(|_| ui.wizard.get());
        with_snapshot(&t, &store, |snap, defaults_only| {
            let mut col = Element::new().style(LayoutStyle::column());
            if defaults_only {
                col = col.child(line(vec![span(
                    " no config file yet — these are the built-in defaults; saving a field creates it",
                    t.info,
                )]));
            }
            // Section-level warnings ride above the table (unknown
            // keys would be dropped by a Python save).
            for sv in &snap.sections {
                if section_names.contains(&sv.spec.name) && !sv.unknown_keys.is_empty() {
                    col = col.child(line(vec![
                        span_bold(format!(" ⚠ {} unknown keys: ", sv.spec.name), t.warn),
                        span(sv.unknown_keys.join(", "), t.text),
                        span("  — a Python-side save DROPS these", t.text_muted),
                    ]));
                }
            }
            col = col.child(fields_table(
                gcx,
                cx,
                &ctx_table,
                &t,
                snap,
                section_names,
                focus,
                sel,
            ));
            col.build()
        })
    });

    // Selected-row truth line: the table's note/broken cells truncate
    // at narrow widths — the full state and note of the SELECTED field
    // always have one uncramped row.
    let detail = dyn_view(LayoutStyle::line(1).shrink(0.0), move || {
        let t = theme.get().tokens;
        let focus = ui.focus_section.get().filter(|_| ui.wizard.get());
        let pair = store.cfg.with(|c| {
            c.ready().and_then(|m| match &m.state {
                FileState::Ready(snap) => {
                    let rows = page_rows(snap, section_names, focus);
                    rows.get(sel.get()).map(|(s, k)| {
                        let sv = snap.sections.iter().find(|x| x.spec.name == *s)?;
                        let fv = sv.fields.iter().find(|f| f.key == *k)?;
                        Some(((*s).to_string(), (*k).to_string(), fv.clone()))
                    })?
                }
                _ => None,
            })
        });
        match pair {
            Some((section, key, fv)) => {
                let mut spans = vec![span_bold(format!(" {section}.{key} "), t.accent)];
                spans.extend(value_spans(&t, &section, &key, &fv.display));
                spans.push(span("  ", t.text));
                spans.extend(super::util::state_spans(&t, &fv.state));
                if let Some(n) = &fv.note {
                    spans.push(span(format!("  {n}"), t.text_faint));
                }
                line(spans)
            }
            None => line(vec![span(String::new(), t.text)]),
        }
    });

    Element::new()
        .style(LayoutStyle::column().grow(1.0))
        .shortcut(KeyChord::plain(Key::Char('e')), move |_| {
            activate_selected(cx, &ctx_edit, section_names, sel);
        })
        .shortcut(KeyChord::plain(Key::Char('x')), move |_| {
            clear_selected(cx, &ctx_clear, section_names, sel);
        })
        .child(body)
        .child(detail)
        .build()
}

/// Is `section.key` a persistent on/off setting (a switch)?
pub fn is_switch(section: &str, key: &str) -> bool {
    crate::schema::section(section)
        .and_then(|s| s.fields.iter().find(|f| f.key == key))
        .is_some_and(|f| matches!(f.kind, FieldKind::Bool))
}

/// The switch state of a bool field's display (`true` / `false`); None
/// for anything else (a broken value keeps its own words).
fn switch_of(section: &str, key: &str, display: &str) -> Option<Switch> {
    if !is_switch(section, key) {
        return None;
    }
    match display {
        "true" => Some(Switch::On),
        "false" => Some(Switch::Off),
        _ => None,
    }
}

/// The table's value cell: `[x] on` / `[ ] off` for a switch (one ink
/// per table row, so the marker carries the state), else the value.
pub fn value_cell(section: &str, key: &str, display: &str) -> String {
    match switch_of(section, key, display) {
        Some(st) => format!(
            "{} {}",
            st.marker(),
            if st == Switch::On { "on" } else { "off" }
        ),
        None => display.to_string(),
    }
}

/// The selected-row line's value: a switch is highlighted when ON
/// (accent + bold), plain when OFF.
fn value_spans(t: &TokenSet, section: &str, key: &str, display: &str) -> Vec<SpanSpec> {
    match switch_of(section, key, display) {
        Some(st) => {
            let mut v = switch_spans(t, if st == Switch::On { "on" } else { "off" }, &st);
            v.push(span("  space switches", t.text_faint));
            v
        }
        None => vec![span(display.to_string(), t.text)],
    }
}

/// `gcx` builds the table (viewport + element); `page_cx` is the scope
/// activation opens its modal on. They are NOT interchangeable: `gcx`
/// belongs to the snapshot dyn and is DISPOSED whenever the config
/// re-renders (a reload, a write completing), which would take an open
/// form down with it. Modals belong to the page.
#[allow(clippy::too_many_arguments)]
fn fields_table(
    gcx: Scope,
    page_cx: Scope,
    ctx: &Ctx,
    t: &TokenSet,
    snap: &Snapshot,
    section_names: &'static [&'static str],
    focus: Option<&'static str>,
    sel: Signal<usize>,
) -> View {
    let pairs = page_rows(snap, section_names, focus);
    let w = abstracttui::app::use_viewport(gcx).get().w;
    let mut rows: Vec<Vec<String>> = Vec::new();
    for (section, key) in &pairs {
        let sv = snap
            .sections
            .iter()
            .find(|s| s.spec.name == *section)
            .expect("section exists");
        let fv = sv
            .fields
            .iter()
            .find(|f| f.key == *key)
            .expect("field exists");
        let state = match &fv.state {
            FieldState::Default => "· default".to_string(),
            FieldState::Set => "● set".to_string(),
            // The reason is prose and the column is the elastic one here
            // — `ui::widths` cuts it to whatever the row can spare, so a
            // wide terminal gets the whole sentence.
            FieldState::Broken(r) => format!("✗ {r}"),
        };
        let mut row = vec![(*section).to_string(), (*key).to_string()];
        // The FULL value: a model id or a path is exactly the sort of
        // string a 38-char cap turned into its neighbour's twin. An
        // on/off setting reads as the switch it is.
        row.push(value_cell(section, key, &fv.display));
        row.push(state);
        if w >= 100 {
            row.push(fv.note.clone().unwrap_or_default());
        }
        rows.push(row);
    }
    // Values are identifiers (model ids, URLs, paths) and cut in the
    // middle; section/field names and the state/note prose read from the
    // left.
    let mut rules = vec![
        widths::ColRule::head("section", 12),
        widths::ColRule::head("field", 16),
        widths::ColRule::tail("value", 20),
        widths::ColRule::head("state", 12),
    ];
    if w >= 100 {
        rules.push(widths::ColRule::head("note", 14));
    }
    let cols = widths::columns(&rules, &mut rows, w);
    let ctx = ctx.clone();
    let pairs2 = pairs.clone();
    Table::new(cols)
        .rows(rows)
        .selection(sel)
        // Enter, Space and double-click all land here — the same
        // guarded door the `e` verb opens (open_field_editor owns the
        // write-route split and posts its own refusals), so keyboard
        // and mouse can never drift apart.
        .on_activate(move |i| {
            if let Some((section, key)) = pairs2.get(i) {
                open_field_editor(page_cx, &ctx, section, key);
            }
        })
        .layout(LayoutStyle::default().grow(1.0))
        .element(gcx, t)
        .autofocus()
        .build()
}

/// The selected (section, key) resolved from live state — shared by
/// the e and x verbs.
fn selected_pair(
    ctx: &Ctx,
    section_names: &'static [&'static str],
    sel: Signal<usize>,
) -> Option<(&'static str, &'static str)> {
    let focus = ctx
        .ui
        .focus_section
        .get_untracked()
        .filter(|_| ctx.ui.wizard.get_untracked());
    ctx.store.cfg.with_untracked(|c| {
        c.ready().and_then(|m| match &m.state {
            FileState::Ready(snap) => page_rows(snap, section_names, focus)
                .get(sel.get_untracked())
                .copied(),
            FileState::Missing => {
                let snap = crate::config::fold(&json!({}), 0, None, None);
                page_rows(&snap, section_names, focus)
                    .get(sel.get_untracked())
                    .copied()
            }
            _ => None,
        })
    })
}

fn activate_selected(
    cx: Scope,
    ctx: &Ctx,
    section_names: &'static [&'static str],
    sel: Signal<usize>,
) {
    match selected_pair(ctx, section_names, sel) {
        Some((section, key)) => open_field_editor(cx, ctx, section, key),
        None => ctx
            .store
            .notice
            .set(Some("no field selected — nothing to edit".into())),
    }
}

fn clear_selected(
    cx: Scope,
    ctx: &Ctx,
    section_names: &'static [&'static str],
    sel: Signal<usize>,
) {
    let Some((section, key)) = selected_pair(ctx, section_names, sel) else {
        ctx.store
            .notice
            .set(Some("no field selected — nothing to clear".into()));
        return;
    };
    // A missing config file holds nothing to clear — resetting a
    // default would only mint an empty `{}` file the operator never
    // asked for (M2 review P3-8).
    let missing = ctx
        .store
        .cfg
        .with_untracked(|c| matches!(c.ready().map(|m| &m.state), Some(FileState::Missing)));
    if missing {
        ctx.store.notice.set(Some(
            "no config file yet — everything is already at its default".into(),
        ));
        return;
    }
    // Refusals BEFORE confirms — confirming a reset and then being
    // told "use its editor" is backwards (M2 review P3-12).
    if matches!(
        writes::field_route(section, key),
        writes::FieldRoute::VisionStrategy
    ) {
        ctx.store.notice.set(Some(
            "vision.strategy resets through its own editor (Enter) — the disabled default \
             also clears the caption pair and chain"
                .into(),
        ));
        return;
    }
    if !ctx.writable_now() {
        return;
    }
    // audio.strategy's TRUE default state is value-removed + explicit
    // flag cleared — the CLI setter would set the flag and freeze the
    // smart default (M2 review P2-4).
    if section == "audio" && key == "strategy" {
        let ctx2 = ctx.clone();
        super::forms::confirm_danger(
            cx,
            ctx.ui,
            "Reset audio.strategy to the smart default? (also clears the explicit flag)".into(),
            "Reset it",
            "Keep it",
            move || {
                let spec = writes::reset_audio_strategy(ctx2.write_base(), None);
                ctx2.send(Cmd::Write(Box::new(spec)));
            },
        );
        return;
    }
    // Clear = reset to default. Only meaningful for fields that can
    // differ; pair/secret fields clear through their own editors.
    let spec = crate::schema::section(section).and_then(|s| s.fields.iter().find(|f| f.key == key));
    let Some(fs) = spec else { return };
    match writes::field_route(section, key) {
        writes::FieldRoute::Secret => {
            super::editors::open_field_editor(cx, ctx, section, key);
        }
        writes::FieldRoute::Pair if section == "default_models" => {
            let ctx2 = ctx.clone();
            super::forms::confirm_danger(
                cx,
                ctx.ui,
                "Clear the global default model? (also clears route input.text)".into(),
                "Clear it",
                "Keep it",
                move || {
                    let spec = writes::clear_global_default(ctx2.write_base(), None);
                    ctx2.send(Cmd::Write(Box::new(spec)));
                },
            );
        }
        writes::FieldRoute::Pair => {
            ctx.store.notice.set(Some(format!(
                "{section}.{key} is pair-coupled — set a new pair with Enter"
            )));
        }
        _ => {
            let nullable = matches!(
                fs.kind,
                FieldKind::OptStr
                    | FieldKind::OptPath
                    | FieldKind::OptInt { .. }
                    | FieldKind::OptEnum(_)
            );
            let ctx2 = ctx.clone();
            let label = if nullable {
                format!("Clear {section}.{key}?")
            } else {
                format!(
                    "Reset {section}.{key} to its default ({})?",
                    fs.default.render()
                )
            };
            let default = fs.default;
            super::forms::confirm_danger(cx, ctx.ui, label, "Reset it", "Keep it", move || {
                let spec = if nullable {
                    writes::clear_scalar(section, key, ctx2.write_base(), None)
                } else {
                    // Non-nullable fields reset by WRITING the
                    // default (absent ≡ default anyway, but the
                    // CLI setter keeps coupled flags honest).
                    let v = match default {
                        crate::schema::Dv::S(s) => json!(s),
                        crate::schema::Dv::B(b) => json!(b),
                        crate::schema::Dv::I(i) => json!(i),
                        crate::schema::Dv::F(f) => json!(f),
                        _ => json!(null),
                    };
                    if v.is_null() {
                        writes::clear_scalar(section, key, ctx2.write_base(), None)
                    } else {
                        writes::set_scalar(section, key, v, ctx2.write_base(), None)
                    }
                };
                match spec {
                    Ok(spec) => ctx2.send(Cmd::Write(Box::new(spec))),
                    Err(e) => ctx2.store.notice.set(Some(e)),
                }
            });
        }
    }
}

/// The Embeddings screen: the field table + the mirror rule that makes
/// the legacy pair confusing in the wild (reads prefer route
/// embedding.text; setters write both — manager.py:830-848, 1421-1431).
pub fn embeddings_page(
    cx: Scope,
    ctx: &Ctx,
    theme: Signal<&'static abstracttui::theme::Theme>,
) -> View {
    let store = ctx.store;
    let table = page(cx, ctx, theme, &["embeddings"], ctx.ui.embeddings_sel);
    let mirror = dyn_view(LayoutStyle::column().shrink(0.0), move || {
        let t = theme.get().tokens;
        let route_line: Vec<super::util::SpanSpec> = match store.routes.get() {
            Loadable::Ready(r) => match r.rows.iter().find(|row| row.key == "embedding.text") {
                Some(row) if row.configured => {
                    let pair = format!(
                        "{} / {}",
                        row.provider.clone().unwrap_or_else(|| "?".into()),
                        row.model.clone().unwrap_or_else(|| "?".into())
                    );
                    vec![
                        span(" route embedding.text: ", t.text_muted),
                        span_bold(pair, t.text),
                    ]
                }
                _ => vec![span(
                    " route embedding.text: not configured — the legacy pair above applies",
                    t.text_muted,
                )],
            },
            Loadable::Loading => vec![span(" route embedding.text: ⟳ loading…", t.info)],
            Loadable::Failed(_) => vec![span(
                " route embedding.text: unavailable (CLI view failed — see Review)",
                t.warn,
            )],
            Loadable::NotAsked => vec![span(" route embedding.text: not loaded", t.text_muted)],
        };
        Element::new()
            .style(LayoutStyle::column())
            .child(line(route_line))
            .child(line(vec![span(
                " reads prefer the route; setters keep both in sync",
                t.text_faint,
            )]))
            .build()
    });
    Element::new()
        .style(LayoutStyle::column().grow(1.0))
        .child(table)
        .child(mirror)
        .build()
}

/// Legacy read-only renderer kept for the Providers screen's api_keys
/// block (that screen renders keys as rows inside its own Block).
pub fn section_rows(t: &TokenSet, sv: &crate::config::SectionView) -> View {
    let mut col = Element::new().style(LayoutStyle::column());
    for fv in &sv.fields {
        col = col.child(field_row(t, fv));
    }
    if !sv.unknown_keys.is_empty() {
        col = col.child(line(vec![
            span_bold("  ⚠ unknown keys: ", t.warn),
            span(sv.unknown_keys.join(", "), t.text),
            span(
                "  — a Python-side save DROPS these; this console preserves them",
                t.text_muted,
            ),
        ]));
    }
    col.build()
}

/// One field row: key, value (ink by state), state, note. Cell-exact
/// padding — char-count padding misaligns CJK/emoji values.
fn field_row(t: &TokenSet, fv: &crate::config::FieldView) -> View {
    let value_ink = match fv.state {
        FieldState::Set => t.text,
        FieldState::Default => t.text_muted,
        FieldState::Broken(_) => t.error,
    };
    let mut spans = vec![
        span(
            format!(" {}", super::util::pad_cells(fv.key, 22)),
            t.text_muted,
        ),
        span(super::util::pad_cells(&fv.display, 28), value_ink),
        span(" ", t.text),
    ];
    spans.extend(super::util::state_spans(t, &fv.state));
    if let Some(n) = &fv.note {
        spans.push(span(format!("  {n}"), t.text_faint));
    }
    line(spans)
}