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