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