Skip to main content

abstractcore_console/
lib.rs

1//! abstractcore-console: the AbstractCore configuration console.
2//!
3//! Architecture (the proven gateway-console shape): the UI thread owns
4//! all signals; one worker thread owns every file read and every
5//! `abstractcore` subprocess. Commands cross via mpsc, results come
6//! back as closures posted through `WakeHandle` (the engine's
7//! live-data law).
8
9pub mod cli;
10pub mod config;
11pub mod models;
12pub mod probes;
13pub mod schema;
14pub mod screens;
15pub mod store;
16pub mod transport;
17pub mod ui;
18pub mod worker;
19pub mod writes;
20
21pub use screens::{
22    catalog, engines, schedule_job_poll, spawn_worker, Access, JobPoll, Remote, ScreenCmd,
23    ScreensCtx, ScreensOptions, ScreensStore,
24};
25pub use transport::{
26    CliTransport, ConsoleTransport, InstallLocation, ServerAction, TransportCaps, TransportError,
27    TransportErrorKind,
28};
29
30use std::cell::RefCell;
31use std::rc::Rc;
32use std::sync::mpsc;
33
34use abstracttui::prelude::*;
35
36use store::Store;
37use ui::{Ctx, UiState};
38
39pub const ENGINE_VERSION: &str = "0.3.6";
40
41const HELP: &str = "\
42abstractcore-console — configure AbstractCore from the terminal
43
44USAGE:
45  abstractcore-console [--wizard|--browse] [--theme ID]
46
47The console mirrors ~/.abstractcore/config/abstractcore.json (honoring
48ABSTRACTCORE_CONFIG_FILE / ABSTRACTCORE_CONFIG_DIR) and drives the
49abstractcore CLI ($ABSTRACTCORE_CLI, PATH, ~/.local/bin, or ./.venv).
50Writes go through the CLI setters (coupled fields) or a direct
51unknown-key-preserving rewrite (CLI-less fields), and every write is
52verified by re-reading.
53
54OPTIONS:
55  --wizard       start in the guided wizard (default when no config
56                 file exists yet)
57  --browse       start in browse mode (default with an existing config)
58  --theme ID     abstracttui theme id (also $ABSTRACTTUI_THEME)
59  -h, --help     this help
60  --version      print the version
61
62KEYS: 1-9, 0 screens (browse) · Ctrl+N/P next/prev · Tab focus ·
63      Enter/e edit · x clear · k set key · w wizard · f finish wizard ·
64      r reload · Ctrl+L repaint · q (browse) / Ctrl+C quit
65      on Capability routes: a applies the recommended routes ·
66      w downloads the selected route's weights
67      on Models (9): w download · d delete · / filter · t type ·
68      f fits only · e engine · v catalog/installed/downloads ·
69      h Hugging Face · u use as default text model · r refresh ·
70      c cancel a download
71      on Engines (0): i install (confirmed, shows the command) ·
72      o open the download page · r probe · c cancel the install
73
74MOUSE: click selects a row · DOUBLE-CLICK opens its editor, the same
75       door Enter opens (and refuses for the same reasons).
76";
77
78struct Args {
79    theme: Option<String>,
80    /// None = adaptive (wizard on a fresh machine, browse otherwise).
81    wizard: Option<bool>,
82}
83
84fn parse_args(argv: &[String]) -> Result<Option<Args>, String> {
85    let mut theme = None;
86    let mut wizard = None;
87    let mut it = argv.iter();
88    while let Some(a) = it.next() {
89        match a.as_str() {
90            "-h" | "--help" => {
91                println!("{HELP}");
92                return Ok(None);
93            }
94            "--version" => {
95                println!("abstractcore-console {}", env!("CARGO_PKG_VERSION"));
96                return Ok(None);
97            }
98            "--wizard" => wizard = Some(true),
99            "--browse" => wizard = Some(false),
100            "--theme" => theme = Some(it.next().cloned().ok_or("--theme needs a value")?),
101            other => return Err(format!("unknown argument: {other} (see --help)")),
102        }
103    }
104    Ok(Some(Args { theme, wizard }))
105}
106
107/// CLI entry — returns the process exit code.
108pub fn run_cli(argv: &[String]) -> i32 {
109    let args = match parse_args(argv) {
110        Ok(Some(a)) => a,
111        Ok(None) => return 0,
112        Err(e) => {
113            eprintln!("abstractcore-console: {e}");
114            return 2;
115        }
116    };
117
118    // Headless guard (CI / piped runs): skip cleanly, exit 0.
119    if !abstracttui::term::have_tty() {
120        println!("abstractcore-console: needs an interactive terminal — skipping cleanly");
121        return 0;
122    }
123
124    if let Some(id) = args
125        .theme
126        .or_else(|| std::env::var("ABSTRACTTUI_THEME").ok())
127    {
128        set_theme_by_id(&id);
129    }
130
131    // Resolve the two identities BEFORE mount (cheap: env + PATH scan +
132    // existence checks) so the first paint can already name them.
133    let config_path = config::resolve_config_path_from_env();
134    let cli_info = cli::resolve_bin_from_env();
135
136    // Adaptive mode default: a machine with no config file gets the
137    // wizard (the definition-of-done scenario); an existing config
138    // opens in browse. Flags override.
139    let start_wizard = args
140        .wizard
141        .unwrap_or_else(|| matches!(config::load(&config_path.path), config::FileState::Missing));
142
143    let mut app = App::new(Size::new(110, 32));
144    let overlays = app.overlays();
145    let quitter = app.quitter();
146    let (tx, rx) = mpsc::channel::<worker::Cmd>();
147
148    // Ctrl+L as a GLOBAL ACTION, not a root shortcut: global actions
149    // resolve last in the key path, so the repaint works even inside a
150    // focus-trapped modal (a root shortcut is not on a modal's focus
151    // path — the repaint key an app owes its users must never go dead
152    // behind a form).
153    app.actions().register(
154        "repaint (full redraw)",
155        Some(KeyChord::new(Mods::CTRL, Key::Char('l'))),
156        abstracttui::app::request_full_redraw,
157    );
158
159    let store_slot: Rc<RefCell<Option<Store>>> = Rc::new(RefCell::new(None));
160    let store_out = store_slot.clone();
161    let ui_slot: Rc<RefCell<Option<UiState>>> = Rc::new(RefCell::new(None));
162    let ui_out = ui_slot.clone();
163
164    let tx_mount = tx.clone();
165    let cli_for_store = cli_info.clone();
166    // The shared Models/Engines screens talk to the same abstractcore
167    // binary the rest of the console drives. A missing binary still gets
168    // a transport: its reads fail as "unavailable" with the spawn error,
169    // which is exactly what those screens should say.
170    let screens_bin = cli_info
171        .as_ref()
172        .map(|i| i.bin.clone())
173        .unwrap_or_else(|| std::path::PathBuf::from("abstractcore"));
174    let overlays_screens = overlays.clone();
175    if let Err(e) = app.mount(move |cx| {
176        let store = Store::create(cx);
177        store.cli.set(cli_for_store.clone());
178        *store_out.borrow_mut() = Some(store);
179        let ui_state = UiState::create(cx);
180        ui_state.wizard.set(start_wizard);
181        *ui_out.borrow_mut() = Some(ui_state);
182        let transport: std::sync::Arc<dyn ConsoleTransport> =
183            std::sync::Arc::new(CliTransport::new(screens_bin.clone()));
184        // The core console drives `abstractcore` on the operator's own
185        // machine: the person at this terminal IS the local operator, so
186        // every Models/Engines verb is theirs (the gateway console derives
187        // this from its signed-in principal instead).
188        let access = cx.signal(screens::Access::Admin);
189        let screens_ctx = ScreensCtx::new(
190            cx,
191            transport,
192            overlays_screens.clone(),
193            access,
194            ScreensOptions {
195                notice: Some(store.notice),
196                ..ScreensOptions::default()
197            },
198        );
199        let ctx = Ctx {
200            tx: tx_mount.clone(),
201            overlays: overlays.clone(),
202            quitter: quitter.clone(),
203            store,
204            ui: ui_state,
205            modal: Rc::new(RefCell::new(None)),
206            screens: screens_ctx,
207        };
208        if start_wizard {
209            ui::wizard::apply_step(&ctx, 0);
210        }
211        ui::root(cx, ctx)
212    }) {
213        eprintln!("abstractcore-console: mount failed: {e}");
214        return 1;
215    }
216
217    // Worker thread: owns file reads/writes + subprocesses; posts
218    // results back. The done sink marshals write completions to the
219    // one open form through the UI signal.
220    let wake = abstracttui::reactive::wake_handle();
221    let store = store_slot.borrow().expect("store created");
222    let ui_state = ui_slot.borrow().expect("ui state created");
223    let done_sink: worker::DoneSink = {
224        let wake = wake.clone();
225        Box::new(move |form_id, outcome| {
226            let ui = ui_state;
227            wake.post(move || ui.write_done.set(Some((form_id, outcome.clone()))));
228        })
229    };
230    let core_cli = cli_info.map(|i| cli::CoreCli::new(i.bin));
231    let worker_handle = worker::spawn(store, wake, rx, config_path, core_cli, done_sink);
232
233    // Boot load: zero-keystroke first paint of real state.
234    store.cfg.set(store::Loadable::Loading);
235    store.routes.set(store::Loadable::Loading);
236    store.profiles.set(store::Loadable::Loading);
237    store.availability.set(store::Loadable::Loading);
238    let _ = tx.send(worker::Cmd::LoadConfig);
239    let _ = tx.send(worker::Cmd::LoadRoutes);
240    let _ = tx.send(worker::Cmd::LoadProfiles);
241    // Weights last: it is the slowest read (it talks to LM Studio and
242    // Ollama) and the only one nothing else waits on.
243    let _ = tx.send(worker::Cmd::LoadAvailability);
244
245    // hover_ink (0.3.0) arms motion reporting with no button held, so the
246    // hover visuals the engine has always DRAWN finally receive the
247    // events that trigger them: every Button, the Select/Combobox popup
248    // rows, Checkbox and the ThemeSwitcher glyph. Table has no hover
249    // state in the engine — the section/route tables stay inert by
250    // design, not by bug. Spread-constructed so the next posture flag
251    // costs this call site nothing (the 0.2.27-yank lesson).
252    let result = app.run_with(RunConfig {
253        hover_ink: true,
254        ..RunConfig::default()
255    });
256    // Drop the sender so an idle worker unblocks and ends. Deliberately
257    // NO join: a worker mid-subprocess would hang quit with the
258    // terminal already restored — process exit reaps the thread. The
259    // q key refuses while a write is in flight (the honest guard);
260    // Ctrl+C remains the force-quit, abandoning at most one write
261    // whose setter completes Python-side unverified.
262    drop(tx);
263    drop(worker_handle);
264
265    match result {
266        Ok(()) => 0,
267        Err(e) => {
268            eprintln!("abstractcore-console: {e}");
269            1
270        }
271    }
272}