Skip to main content

abstractcore_console/screens/
mod.rs

1//! The shared **Models** and **Engines** screens (contract H) — one
2//! implementation, mounted by both the core console (over
3//! [`CliTransport`](crate::transport::CliTransport)) and the gateway
4//! console (over its own HTTP transport).
5//!
6//! # Shape
7//!
8//! - [`ScreensStore`]: the screens' signals (catalog, installed, engines,
9//!   host profile, the current job, filter state, selections). `Copy`.
10//! - [`ScreensCtx`]: store + the command channel to the screens' OWN
11//!   worker thread + the host label + the URL opener. `Clone`. Built once
12//!   at mount with [`ScreensCtx::new`], which also spawns the worker.
13//! - [`catalog()`] and [`engines()`]: the two screen builders. Each is a
14//!   plain component `fn(Scope, &ScreensCtx) -> View`: mount it as a page
15//!   of your `PageHost`. Entering a screen loads its data once; `r`
16//!   re-reads.
17//! - [`spawn_worker`] + [`schedule_job_poll`]: the worker lane and the
18//!   job-poll helper (a timer thread re-sends [`ScreenCmd::PollJob`], the
19//!   gateway console's `schedule_poll` pattern), exported for hosts that
20//!   want to run the lane themselves.
21//!
22//! Every transport call runs on the worker; results come back as
23//! closures posted through the engine's `WakeHandle` — the UI thread
24//! never blocks.
25//!
26//! # Keys (contract H / G)
27//!
28//! | key | Models | Engines |
29//! |---|---|---|
30//! | `w` | download the selected artifact (downloads run in parallel) | — |
31//! | `d` | delete (confirm; shows blockers) | — |
32//! | `h` | search Hugging Face (Enter on an empty query leaves it) | — |
33//! | `u` | use the installed artifact as the default text model | — |
34//! | `i` | — | install (confirm shows argv, host, sudo/UAC; app engines: where) |
35//! | `s` | — | start / stop the engine's server |
36//! | `a` | — | continue a paused install (administrator step / tools / re-check) |
37//! | `y` | — | copy a paused install's command |
38//! | `o` | — | open the download page |
39//! | `/` | filter | — |
40//! | `t` | cycle the model type (text, thinking, tools, vision, audio, embedding, voice, image, video) | — |
41//! | `f` | toggle fits-only | — |
42//! | `e` | cycle engine filter | — |
43//! | `v` | catalog → installed → downloads | — |
44//! | `r` | refresh | refresh (probes local servers) |
45//! | `c` | cancel the selected/only download (asks first) | cancel the engine's install |
46//!
47//! `h`, `u`, `s`, `a`, the downloads feed and the install location are
48//! OPTIONAL transport verbs ([`TransportCaps`]): a transport without one
49//! gets the verb refused with "not available over this backend", and
50//! the footer ([`catalog::hints`], [`engines::hints`]) says so.
51//!
52//! # Who may change things ([`Access`])
53//!
54//! `w` `d` `u` `c` `i` `s` `a` change the host, so they are the web
55//! console's admin-only verbs. The host hands [`ScreensCtx::new`] a
56//! `Signal<Access>` it keeps current from its signed-in principal (the
57//! gateway console), or a constant [`Access::Admin`] (the core console:
58//! the local operator driving `abstractcore` on their own machine). With
59//! [`Access::ReadOnly`] every such verb is refused with the host's
60//! reason and the footer says "admin only"; browsing stays open.
61//!
62//! # Mounting (host crate)
63//!
64//! ```no_run
65//! use std::sync::Arc;
66//! use abstracttui::prelude::*;
67//! use abstracttui::widgets::PageHost;
68//! use abstractcore_console::screens::{self, ScreensCtx, ScreensOptions};
69//! use abstractcore_console::transport::{CliTransport, ConsoleTransport};
70//!
71//! let mut app = App::new(Size::new(110, 32));
72//! let overlays = app.overlays();
73//! app.mount(move |cx| {
74//!     let transport: Arc<dyn ConsoleTransport> =
75//!         Arc::new(CliTransport::from_env().unwrap_or_else(|| CliTransport::new("abstractcore")));
76//!     // The local operator: every verb (a gateway console derives this
77//!     // signal from its signed-in principal instead).
78//!     let access = cx.signal(screens::Access::Admin);
79//!     let sctx = ScreensCtx::new(cx, transport, overlays.clone(), access, ScreensOptions::default());
80//!     let (a, b) = (sctx.clone(), sctx.clone());
81//!     PageHost::new()
82//!         .page("catalog", "9 Models", move |pcx| screens::catalog(pcx, &a))
83//!         .page("engines", "0 Engines", move |pcx| screens::engines(pcx, &b))
84//!         .view(cx)
85//! })
86//! .unwrap();
87//! ```
88
89pub mod catalog;
90pub mod data;
91pub mod engines;
92mod worker;
93
94use std::cell::RefCell;
95use std::collections::HashMap;
96use std::rc::Rc;
97use std::sync::mpsc::{self, Sender};
98use std::sync::Arc;
99use std::time::{Duration, Instant};
100
101use abstracttui::app::{ChoiceOption, ChoiceOutcome, ChoicePrompt, Modal, Overlays, Toast};
102use abstracttui::prelude::*;
103use abstracttui::widgets::Progress;
104
105pub use catalog::catalog;
106pub use data::{
107    ActiveJobRef, AdminPrompt, ArtifactRow, CatalogData, EngineAction, EngineRow, EnginesData,
108    HostProfile, InstallPlan, InstallPlans, InstalledData, InstalledRow, JobView, LocationPlan,
109    ToolsPrompt, CATEGORIES,
110};
111pub use engines::engines;
112pub use worker::{schedule_job_poll, spawn_worker};
113
114use crate::transport::{
115    ConsoleTransport, InstallLocation, ServerAction, TransportCaps, TransportError,
116};
117use crate::ui::util::{line, span, span_bold};
118
119/// Stable page ids (contract principle 2): "Models" is `catalog`,
120/// "Engines" is `engines` — never `models`/`runtimes`, which the
121/// gateway console already uses for other things.
122pub const CATALOG_ID: &str = "catalog";
123pub const ENGINES_ID: &str = "engines";
124pub const CATALOG_TITLE: &str = "Models";
125pub const ENGINES_TITLE: &str = "Engines";
126
127/// A remote read's honest state.
128#[derive(Clone, Debug, Default, PartialEq)]
129pub enum Remote<T> {
130    #[default]
131    NotAsked,
132    Loading,
133    Ready(T),
134    Failed(TransportError),
135}
136
137impl<T> Remote<T> {
138    pub fn ready(&self) -> Option<&T> {
139        match self {
140            Remote::Ready(t) => Some(t),
141            _ => None,
142        }
143    }
144
145    pub fn is_not_asked(&self) -> bool {
146        matches!(self, Remote::NotAsked)
147    }
148}
149
150/// Which list the Models screen shows.
151///
152/// `#[non_exhaustive]`: 0.3.0 added [`Downloads`](CatalogView::Downloads).
153#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
154#[non_exhaustive]
155pub enum CatalogView {
156    /// Everything downloadable (contract C).
157    #[default]
158    Catalog,
159    /// Everything already on disk (contract D).
160    Installed,
161    /// Every download this console watches, live (the downloads feed).
162    Downloads,
163}
164
165/// May the person at this console change the host?
166///
167/// The web console shows the same verbs disabled for a non-admin, with a
168/// reason ("Only an admin can download models"); these screens refuse
169/// them the same way. The HOST decides and keeps the signal current (see
170/// the module docs): the screens never guess who is signed in.
171///
172/// `#[non_exhaustive]`: a host builds a variant and hands the signal
173/// over; the screens are the only reader, so a later state (say, "the
174/// principal is still being read") arrives without breaking hosts.
175#[derive(Clone, Debug, PartialEq, Eq)]
176#[non_exhaustive]
177pub enum Access {
178    /// Every verb: the local operator (core console) or a signed-in
179    /// administrator (gateway console).
180    Admin,
181    /// Browse only. The string says why, in the host's words — it ends
182    /// every refusal: "only an admin can download models — {reason}"
183    /// (e.g. "signed in as ana, not an admin", "not signed in").
184    ReadOnly(String),
185}
186
187impl Access {
188    pub fn is_admin(&self) -> bool {
189        matches!(self, Access::Admin)
190    }
191}
192
193/// Most finished jobs the store keeps beside the live ones.
194pub const FINISHED_JOBS_KEPT: usize = 12;
195
196/// The screens' signals. `Copy`: every field is a signal handle.
197///
198/// `#[non_exhaustive]`: built by [`ScreensStore::create`] (through
199/// [`ScreensCtx::new`]); each release may add a signal.
200#[derive(Clone, Copy)]
201#[non_exhaustive]
202pub struct ScreensStore {
203    pub host: Signal<Remote<HostProfile>>,
204    pub engines: Signal<Remote<EnginesData>>,
205    pub catalog: Signal<Remote<CatalogData>>,
206    pub installed: Signal<Remote<InstalledData>>,
207    /// The job touched last (running, or the last one to finish) — the
208    /// strip's detail line. Every job lives in [`ScreensStore::jobs`].
209    pub job: Signal<Option<JobView>>,
210    /// Every job this console watches, newest first: all live ones
211    /// (downloads run in PARALLEL; a paused install blocks nothing) plus
212    /// the last [`FINISHED_JOBS_KEPT`] finished.
213    pub jobs: Signal<Vec<JobView>>,
214    /// Hugging Face mode (`h`): the hub query the catalog shows.
215    pub hub: Signal<Option<String>>,
216    /// The configured default text model (`u` marks and sets it).
217    pub text_default: Signal<Remote<Option<(String, String)>>>,
218    /// An app engine's two install plans (`i`), keyed by engine id.
219    pub plans: Signal<HashMap<String, Remote<InstallPlans>>>,
220    /// The downloads feed read (`Ready(n)` = n jobs listed).
221    pub feed: Signal<Remote<usize>>,
222    pub downloads_sel: Signal<usize>,
223    /// Free-text catalog filter (`/`).
224    pub query: Signal<String>,
225    /// Engine filter (`e` cycles through the catalog's providers).
226    pub engine_filter: Signal<Option<String>>,
227    /// `f`: only artifacts whose fit verdict is `fits`/`tight`.
228    pub fits_only: Signal<bool>,
229    /// `t`: only models of this type (a [`CATEGORIES`] id; `None` = all)
230    /// — the web console's capability chips, filtered locally.
231    pub category: Signal<Option<&'static str>>,
232    /// Who may change the host — the HOST's signal (see [`Access`]).
233    pub access: Signal<Access>,
234    pub view: Signal<CatalogView>,
235    pub catalog_sel: Signal<usize>,
236    pub installed_sel: Signal<usize>,
237    pub engine_sel: Signal<usize>,
238    /// Transient one-line notice. With
239    /// [`ScreensOptions::notice`] this IS the host's own notice signal.
240    pub notice: Signal<Option<String>>,
241    /// Bumped on every catalog request; stale answers are dropped.
242    pub catalog_gen: Signal<u64>,
243    /// Engines seen in unfiltered catalog/installed answers — what `e`
244    /// cycles through (a filtered answer only names one engine).
245    pub providers_seen: Signal<Vec<String>>,
246}
247
248impl ScreensStore {
249    /// Fresh signals; `notice` = the host's signal when it has one,
250    /// `access` = the host's (see [`Access`]).
251    pub fn create(
252        cx: Scope,
253        notice: Option<Signal<Option<String>>>,
254        access: Signal<Access>,
255    ) -> ScreensStore {
256        ScreensStore {
257            host: cx.signal(Remote::NotAsked),
258            engines: cx.signal(Remote::NotAsked),
259            catalog: cx.signal(Remote::NotAsked),
260            installed: cx.signal(Remote::NotAsked),
261            job: cx.signal(None),
262            jobs: cx.signal(Vec::new()),
263            hub: cx.signal(None),
264            text_default: cx.signal(Remote::NotAsked),
265            plans: cx.signal(HashMap::new()),
266            feed: cx.signal(Remote::NotAsked),
267            downloads_sel: cx.signal(0),
268            query: cx.signal(String::new()),
269            engine_filter: cx.signal(None),
270            fits_only: cx.signal(false),
271            category: cx.signal(None),
272            access,
273            view: cx.signal(CatalogView::Catalog),
274            catalog_sel: cx.signal(0),
275            installed_sel: cx.signal(0),
276            engine_sel: cx.signal(0),
277            notice: notice.unwrap_or_else(|| cx.signal(None)),
278            catalog_gen: cx.signal(0),
279            providers_seen: cx.signal(Vec::new()),
280        }
281    }
282
283    /// False once the scope that created these signals is disposed.
284    pub fn alive(&self) -> bool {
285        self.job.is_alive() && self.notice.is_alive() && self.catalog.is_alive()
286    }
287
288    /// Any job still WORKING — the one a host's quit should question.
289    /// A paused install is live but waits for a person: it blocks nothing,
290    /// quitting included (it resumes from the Engines screen, or the web
291    /// console, whenever someone continues it).
292    pub fn job_running(&self) -> bool {
293        let working = |j: &JobView| j.is_active() && !j.is_paused();
294        self.jobs.with_untracked(|v| v.iter().any(working))
295            || self.job.with_untracked(|j| j.as_ref().is_some_and(working))
296    }
297
298    /// The live job about this download, if one runs.
299    pub fn active_download(&self, provider: &str, artifact: &str) -> Option<JobView> {
300        self.jobs.with_untracked(|v| {
301            v.iter()
302                .find(|j| {
303                    j.is_active()
304                        && j.kind == "download"
305                        && j.provider.as_deref() == Some(provider)
306                        && j.artifact.as_deref() == Some(artifact)
307                })
308                .cloned()
309        })
310    }
311
312    /// The live install job of this engine (running OR paused).
313    pub fn active_install(&self, engine: &str) -> Option<JobView> {
314        self.jobs.with_untracked(|v| {
315            v.iter()
316                .find(|j| {
317                    j.is_active()
318                        && j.kind == "engine_install"
319                        && j.engine.as_deref() == Some(engine)
320                })
321                .cloned()
322        })
323    }
324
325    /// Download jobs (and "download all" groups), newest first.
326    pub fn download_jobs(&self, tracked: bool) -> Vec<JobView> {
327        let pick = |v: &Vec<JobView>| {
328            v.iter()
329                .filter(|j| matches!(j.kind.as_str(), "download" | "download_group"))
330                .cloned()
331                .collect::<Vec<_>>()
332        };
333        if tracked {
334            self.jobs.with(pick)
335        } else {
336            self.jobs.with_untracked(pick)
337        }
338    }
339}
340
341/// Put one job into the list (UI thread): by id, else in place of its
342/// "starting…" placeholder (same subject, no id yet), else first. Keeps
343/// every live job and the newest [`FINISHED_JOBS_KEPT`] finished ones;
344/// `job` becomes this one.
345pub fn upsert_job(s: &ScreensStore, view: JobView) {
346    s.jobs.update(|v| {
347        let at = v
348            .iter()
349            .position(|j| !view.job_id.is_empty() && j.job_id == view.job_id)
350            .or_else(|| {
351                v.iter()
352                    .position(|j| j.job_id.is_empty() && j.same_subject(&view))
353            });
354        match at {
355            Some(i) => v[i] = view.clone(),
356            None => v.insert(0, view.clone()),
357        }
358        let mut finished = 0;
359        v.retain(|j| {
360            if j.is_active() {
361                return true;
362            }
363            finished += 1;
364            finished <= FINISHED_JOBS_KEPT
365        });
366    });
367    s.job.set(Some(view));
368}
369
370/// Drop a placeholder that never became a job (the verb was refused).
371pub fn drop_placeholder(s: &ScreensStore, like: &JobView) {
372    s.jobs
373        .update(|v| v.retain(|j| !(j.job_id.is_empty() && j.same_subject(like))));
374    if s.job
375        .with_untracked(|j| j.as_ref().is_some_and(|j| j.job_id.is_empty()))
376    {
377        s.job.set(None);
378    }
379}
380
381/// Opens a URL on the machine running the console (`o`).
382pub type Opener = Rc<dyn Fn(&str) -> Result<(), OpenError>>;
383
384/// Why an [`Opener`] did not open a URL.
385///
386/// `NoDisplay` is the one a host must act on: this machine has no screen a
387/// browser could appear on (an SSH session, or Linux/BSD with neither
388/// `DISPLAY` nor `WAYLAND_DISPLAY`), NOTHING was launched, and the person
389/// needs the URL itself — [`ScreensCtx::open_url`] says so in its notice,
390/// and a host (the gateway console's Apps → Open) shows the link instead.
391#[derive(Clone, Debug, PartialEq, Eq)]
392#[non_exhaustive]
393pub enum OpenError {
394    /// No display here; `why` in plain words. Nothing was launched.
395    NoDisplay { why: String },
396    /// Refused before anything ran (only http(s) links are opened).
397    Refused(String),
398    /// The system opener could not be started.
399    Failed(String),
400}
401
402impl std::fmt::Display for OpenError {
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        match self {
405            OpenError::NoDisplay { why } => write!(f, "no display on this machine ({why})"),
406            OpenError::Refused(why) | OpenError::Failed(why) => f.write_str(why),
407        }
408    }
409}
410
411impl std::error::Error for OpenError {}
412
413/// Knobs for [`ScreensCtx::new`].
414#[derive(Clone)]
415pub struct ScreensOptions {
416    /// Gap between job polls (default 1.5 s, the web console's cadence).
417    pub poll_interval: Duration,
418    /// How long the screens WATCH a job before handing it back (the job
419    /// itself keeps running; default 60 min).
420    pub poll_limit: Duration,
421    /// Share the host's notice signal (its footer + toast already render
422    /// it). `None` = the screens own one and toast it themselves.
423    pub notice: Option<Signal<Option<String>>>,
424    /// `o` opener; `None` = the system opener (`open` / `xdg-open` /
425    /// `explorer`).
426    pub opener: Option<Opener>,
427}
428
429impl Default for ScreensOptions {
430    fn default() -> Self {
431        ScreensOptions {
432            poll_interval: Duration::from_millis(1500),
433            poll_limit: Duration::from_secs(60 * 60),
434            notice: None,
435            opener: None,
436        }
437    }
438}
439
440/// Commands for the screens' worker lane.
441///
442/// `#[non_exhaustive]`, and so is every struct variant: a verb gains a
443/// command, a command gains a field. The lane is driven through the
444/// [`ScreensCtx`] methods (one per command); a host reads commands (logs,
445/// tests) and never builds one.
446#[derive(Clone, Debug)]
447#[non_exhaustive]
448pub enum ScreenCmd {
449    LoadHost,
450    #[non_exhaustive]
451    LoadEngines {
452        probe: bool,
453    },
454    #[non_exhaustive]
455    LoadCatalog {
456        q: String,
457        engine: Option<String>,
458        fits_only: bool,
459        generation: u64,
460        /// Hugging Face mode: `q` is a hub query.
461        hub: bool,
462    },
463    LoadInstalled,
464    /// The downloads feed: adopt live jobs this console is not watching.
465    LoadDownloads,
466    LoadTextDefault,
467    #[non_exhaustive]
468    SetTextDefault {
469        provider: String,
470        model: String,
471    },
472    /// Both install plans of an app engine (two dry runs).
473    #[non_exhaustive]
474    LoadPlans {
475        engine: String,
476    },
477    /// Watch a job learned from elsewhere (an engine row's `active_job`).
478    #[non_exhaustive]
479    Adopt {
480        job_id: String,
481    },
482    #[non_exhaustive]
483    Continue {
484        job_id: String,
485        action: Option<String>,
486    },
487    #[non_exhaustive]
488    Server {
489        engine: String,
490        action: ServerAction,
491    },
492    #[non_exhaustive]
493    Download {
494        provider: String,
495        artifact: String,
496        /// The catalog's vouched size ([`ArtifactRow::expected_bytes`]).
497        expected_bytes: Option<u64>,
498    },
499    #[non_exhaustive]
500    Delete {
501        provider: String,
502        artifact: String,
503        force: bool,
504    },
505    #[non_exhaustive]
506    Install {
507        engine: String,
508        dry_run: bool,
509        location: InstallLocation,
510    },
511    PollJob(JobPoll),
512    #[non_exhaustive]
513    Cancel {
514        job_id: String,
515        /// A model download / "download all" group: cancelled on the
516        /// download route ([`ConsoleTransport::cancel_download`]).
517        download: bool,
518    },
519}
520
521/// One job watch, carried across polls.
522///
523/// `#[non_exhaustive]`: build it with [`JobPoll::new`].
524#[derive(Clone, Debug)]
525#[non_exhaustive]
526pub struct JobPoll {
527    pub job_id: String,
528    /// A model download or "download all" group: polled on the download
529    /// route ([`ConsoleTransport::download_job`]), else the job route.
530    pub download: bool,
531    /// When the watch began (the poll limit counts from here).
532    pub since: Instant,
533    /// Consecutive failed polls (three in a row end the watch).
534    pub errors: u32,
535}
536
537impl JobPoll {
538    /// A fresh watch of `job_id`, starting now.
539    pub fn new(job_id: impl Into<String>, download: bool) -> JobPoll {
540        JobPoll {
541            job_id: job_id.into(),
542            download,
543            since: Instant::now(),
544            errors: 0,
545        }
546    }
547}
548
549/// Is this job kind polled/cancelled on the download route?
550pub(crate) fn is_download_kind(kind: &str) -> bool {
551    matches!(kind, "download" | "download_group")
552}
553
554/// Everything a screen needs: store, worker lane, host label, opener.
555#[derive(Clone)]
556pub struct ScreensCtx {
557    pub store: ScreensStore,
558    pub tx: Sender<ScreenCmd>,
559    pub overlays: Overlays,
560    /// Where installs/deletes run ("this machine (mbp)", "gateway.lan").
561    pub host_label: Rc<str>,
562    /// The transport's optional verbs (asked once, at mount).
563    pub caps: TransportCaps,
564    opener: Opener,
565    modal: Rc<RefCell<Option<Modal>>>,
566}
567
568impl ScreensCtx {
569    /// Create the store, spawn the worker over `transport`, and (without
570    /// a shared notice signal) install the toast effect. Call once, in
571    /// the mount scope, on the UI thread.
572    ///
573    /// `access` is the HOST's signal saying who may change the host
574    /// ([`Access`]); the host keeps it current (a sign-in, a sign-out, a
575    /// new gateway). A required argument on purpose: the admin-only
576    /// verbs have no default audience.
577    pub fn new(
578        cx: Scope,
579        transport: Arc<dyn ConsoleTransport>,
580        overlays: Overlays,
581        access: Signal<Access>,
582        options: ScreensOptions,
583    ) -> ScreensCtx {
584        let own_notice = options.notice.is_none();
585        let store = ScreensStore::create(cx, options.notice, access);
586        let (tx, rx) = mpsc::channel::<ScreenCmd>();
587        let host_label: Rc<str> = Rc::from(transport.host_label());
588        let caps = transport.capabilities();
589        let wake = abstracttui::reactive::wake_handle();
590        let _worker = spawn_worker(
591            transport,
592            store,
593            wake,
594            tx.clone(),
595            rx,
596            worker::WorkerOptions {
597                poll_interval: options.poll_interval,
598                poll_limit: options.poll_limit,
599            },
600        );
601        if own_notice {
602            let overlays = overlays.clone();
603            cx.effect(move || {
604                if let Some(n) = store.notice.get() {
605                    let viewport = abstracttui::app::use_viewport(cx).get_untracked();
606                    Toast::show(&overlays, cx, viewport, n, Duration::from_secs(4));
607                }
608            });
609        }
610        ScreensCtx {
611            store,
612            tx,
613            overlays,
614            host_label,
615            caps,
616            opener: options.opener.unwrap_or_else(|| Rc::new(system_open)),
617            modal: Rc::new(RefCell::new(None)),
618        }
619    }
620
621    pub fn send(&self, cmd: ScreenCmd) {
622        let _ = self.tx.send(cmd);
623    }
624
625    fn notice(&self, msg: impl Into<String>) {
626        self.store.notice.set(Some(msg.into()));
627    }
628
629    /// The admin gate every host-changing verb passes FIRST — before any
630    /// capability, selection or state check, so a read-only person always
631    /// hears the one answer that applies to them (`what` = "download
632    /// models", "install engines"…). `false` = refused, with the web
633    /// console's sentence plus the host's reason as the notice.
634    pub fn require_admin(&self, what: &str) -> bool {
635        match self.store.access.get_untracked() {
636            Access::Admin => true,
637            Access::ReadOnly(why) => {
638                self.notice(format!("only an admin can {what} — {why}"));
639                false
640            }
641        }
642    }
643
644    /// Load the Models screen's data if it was never asked for.
645    pub fn ensure_catalog(&self) {
646        let s = self.store;
647        if s.host.with_untracked(Remote::is_not_asked) {
648            s.host.set(Remote::Loading);
649            self.send(ScreenCmd::LoadHost);
650        }
651        if s.catalog.with_untracked(Remote::is_not_asked) {
652            self.reload_catalog();
653        }
654        if s.installed.with_untracked(Remote::is_not_asked) {
655            s.installed.set(Remote::Loading);
656            self.send(ScreenCmd::LoadInstalled);
657        }
658        if self.caps.downloads_feed && s.feed.with_untracked(Remote::is_not_asked) {
659            self.load_downloads();
660        }
661        if self.caps.text_default && s.text_default.with_untracked(Remote::is_not_asked) {
662            s.text_default.set(Remote::Loading);
663            self.send(ScreenCmd::LoadTextDefault);
664        }
665    }
666
667    /// Re-read the downloads feed (re-attaches to live downloads).
668    pub fn load_downloads(&self) {
669        if !self.caps.downloads_feed {
670            return;
671        }
672        self.store.feed.set(Remote::Loading);
673        self.send(ScreenCmd::LoadDownloads);
674    }
675
676    /// Load the Engines screen's data if it was never asked for.
677    pub fn ensure_engines(&self) {
678        let s = self.store;
679        if s.engines.with_untracked(Remote::is_not_asked) {
680            s.engines.set(Remote::Loading);
681            self.send(ScreenCmd::LoadEngines { probe: false });
682        }
683        if s.host.with_untracked(Remote::is_not_asked) {
684            s.host.set(Remote::Loading);
685            self.send(ScreenCmd::LoadHost);
686        }
687    }
688
689    /// Re-query the catalog with the current filters.
690    pub fn reload_catalog(&self) {
691        let s = self.store;
692        let generation = s.catalog_gen.get_untracked() + 1;
693        s.catalog_gen.set(generation);
694        s.catalog.set(Remote::Loading);
695        let hub = s.hub.get_untracked();
696        self.send(ScreenCmd::LoadCatalog {
697            q: hub.clone().unwrap_or_else(|| s.query.get_untracked()),
698            engine: s.engine_filter.get_untracked(),
699            fits_only: s.fits_only.get_untracked(),
700            generation,
701            hub: hub.is_some(),
702        });
703    }
704
705    /// `h`: search Hugging Face for `q` (empty = back to the catalog).
706    pub fn hub_search(&self, q: &str) {
707        let q = q.trim();
708        if q.is_empty() {
709            if self.store.hub.get_untracked().is_some() {
710                self.store.hub.set(None);
711                self.store.catalog_sel.set(0);
712                self.reload_catalog();
713                self.notice("back to the catalog");
714            }
715            return;
716        }
717        if !self.caps.hub_search {
718            self.notice(format!(
719                "Hugging Face search is not available over {}",
720                self.host_label
721            ));
722            return;
723        }
724        self.store.hub.set(Some(q.to_string()));
725        self.store.catalog_sel.set(0);
726        self.store.view.set(CatalogView::Catalog);
727        self.reload_catalog();
728        self.notice(format!("searching Hugging Face for \"{q}\"…"));
729    }
730
731    /// `r` on Models: host profile, catalog and installed list.
732    pub fn refresh_catalog(&self) {
733        self.store.host.set(Remote::Loading);
734        self.send(ScreenCmd::LoadHost);
735        self.reload_catalog();
736        self.store.installed.set(Remote::Loading);
737        self.send(ScreenCmd::LoadInstalled);
738        self.load_downloads();
739        if self.caps.text_default {
740            self.store.text_default.set(Remote::Loading);
741            self.send(ScreenCmd::LoadTextDefault);
742        }
743    }
744
745    /// `r` on Engines: a PROBING status read (contacts local servers).
746    pub fn refresh_engines(&self) {
747        self.store.engines.set(Remote::Loading);
748        self.send(ScreenCmd::LoadEngines { probe: true });
749    }
750
751    /// Mark a verb as started (the list shows it before the backend
752    /// answers) and send it.
753    fn start(&self, placeholder: JobView, cmd: ScreenCmd) {
754        upsert_job(&self.store, placeholder);
755        self.send(cmd);
756    }
757
758    /// `w`: start downloading one artifact. Downloads run in PARALLEL
759    /// (the web console's behaviour); only the SAME artifact twice is
760    /// refused here — the backend would join it anyway. `expected_bytes`
761    /// = [`ArtifactRow::expected_bytes`] (the backend's disk pre-check).
762    pub fn download(&self, provider: &str, artifact: &str, expected_bytes: Option<u64>) {
763        if !self.require_admin("download models") {
764            return;
765        }
766        if let Some(j) = self.store.active_download(provider, artifact) {
767            self.notice(format!(
768                "{provider} {artifact} is already downloading{} — c cancels it",
769                j.percent.map(|p| format!(" ({p:.0}%)")).unwrap_or_default()
770            ));
771            return;
772        }
773        self.start(
774            JobView {
775                kind: "download".into(),
776                status: "queued".into(),
777                provider: Some(provider.into()),
778                artifact: Some(artifact.into()),
779                message: Some("starting…".into()),
780                ..JobView::default()
781            },
782            ScreenCmd::Download {
783                provider: provider.into(),
784                artifact: artifact.into(),
785                expected_bytes,
786            },
787        );
788    }
789
790    /// `d` (after the confirm): delete one artifact — refused while that
791    /// same artifact is still downloading.
792    pub fn delete(&self, provider: &str, artifact: &str, force: bool) {
793        if !self.require_admin("delete models") {
794            return;
795        }
796        if self.store.active_download(provider, artifact).is_some() {
797            self.notice(format!(
798                "{provider} {artifact} is still downloading — cancel it (c) before deleting"
799            ));
800            return;
801        }
802        self.start(
803            JobView {
804                kind: "delete".into(),
805                status: "queued".into(),
806                provider: Some(provider.into()),
807                artifact: Some(artifact.into()),
808                message: Some("deleting…".into()),
809                ..JobView::default()
810            },
811            ScreenCmd::Delete {
812                provider: provider.into(),
813                artifact: artifact.into(),
814                force,
815            },
816        );
817    }
818
819    /// `i` (after the confirm): install an engine, or dry-run it.
820    pub fn install(&self, engine: &str, dry_run: bool) {
821        self.install_at(engine, dry_run, InstallLocation::Auto);
822    }
823
824    /// `i` with a location (app engines). Refused while THIS engine has a
825    /// live install (a paused one says how to continue); another
826    /// engine's install is the backend's call (it answers 409 "busy").
827    pub fn install_at(&self, engine: &str, dry_run: bool, location: InstallLocation) {
828        if !self.require_admin("install engines") {
829            return;
830        }
831        if location != InstallLocation::Auto && !self.caps.install_location {
832            self.notice(format!(
833                "choosing where an engine goes is not available over {}",
834                self.host_label
835            ));
836            return;
837        }
838        if let Some(j) = self.store.active_install(engine).filter(|_| !dry_run) {
839            self.notice(if j.is_paused() {
840                format!(
841                    "the {engine} install is waiting ({}) — a continues it, c cancels it",
842                    j.paused_label().unwrap_or("paused")
843                )
844            } else {
845                format!("the {engine} install is still running — c cancels it")
846            });
847            return;
848        }
849        self.start(
850            JobView {
851                kind: "engine_install".into(),
852                status: "queued".into(),
853                engine: Some(engine.into()),
854                dry_run,
855                message: Some(if dry_run {
856                    "asking what would run…".into()
857                } else {
858                    "starting the installer…".into()
859                }),
860                ..JobView::default()
861            },
862            ScreenCmd::Install {
863                engine: engine.into(),
864                dry_run,
865                location,
866            },
867        );
868    }
869
870    /// Ask for an app engine's two install plans (just me / everyone).
871    pub fn load_plans(&self, engine: &str) {
872        self.store.plans.update(|m| {
873            m.insert(engine.to_string(), Remote::Loading);
874        });
875        self.send(ScreenCmd::LoadPlans {
876            engine: engine.into(),
877        });
878    }
879
880    /// `a`: continue a paused install with one of its `continue_actions`.
881    pub fn continue_job(&self, job: &JobView, action: Option<&str>) {
882        if !self.require_admin("continue an install") {
883            return;
884        }
885        if !self.caps.engine_continue {
886            self.notice(format!(
887                "continuing a paused install is not available over {}",
888                self.host_label
889            ));
890            return;
891        }
892        if !job.is_paused() || job.job_id.is_empty() {
893            self.notice(format!(
894                "{} {} is not waiting for anything",
895                job.verb(),
896                job.subject()
897            ));
898            return;
899        }
900        self.notice(match action {
901            Some("approve_admin") => format!(
902                "asking for the administrator password on {}…",
903                self.host_label
904            ),
905            Some("install_tools") => "opening Apple's tools installer on the host…".to_string(),
906            _ => format!("re-checking {}…", job.subject()),
907        });
908        self.send(ScreenCmd::Continue {
909            job_id: job.job_id.clone(),
910            action: action.map(str::to_string),
911        });
912    }
913
914    /// `s`: start or stop an engine's server.
915    pub fn server(&self, engine: &str, action: ServerAction) {
916        if !self.require_admin("start or stop engines") {
917            return;
918        }
919        if !self.caps.engine_server {
920            self.notice(format!(
921                "starting or stopping engine servers is not available over {}",
922                self.host_label
923            ));
924            return;
925        }
926        self.notice(format!(
927            "{} {engine}…",
928            match action {
929                ServerAction::Start => "starting",
930                ServerAction::Stop => "stopping",
931            }
932        ));
933        self.send(ScreenCmd::Server {
934            engine: engine.into(),
935            action,
936        });
937    }
938
939    /// `u`: make an installed artifact the default text model (the route
940    /// stores the SERVED id — see [`data::served_model_id`]).
941    pub fn set_text_default(&self, provider: &str, artifact: &str) {
942        if !self.require_admin("change the default model") {
943            return;
944        }
945        if !self.caps.text_default {
946            self.notice(format!(
947                "changing the default text model is not available over {}",
948                self.host_label
949            ));
950            return;
951        }
952        let model = data::served_model_id(provider, artifact);
953        self.notice(format!(
954            "saving {provider} · {model} as the default text model…"
955        ));
956        self.send(ScreenCmd::SetTextDefault {
957            provider: provider.into(),
958            model,
959        });
960    }
961
962    /// Cancel one job (`c` picks which).
963    pub fn cancel_job(&self, j: &JobView) {
964        if !self.require_admin("cancel jobs") {
965            return;
966        }
967        if !j.is_active() {
968            self.notice(format!("{} {} is not running", j.verb(), j.subject()));
969        } else if j.job_id.is_empty() {
970            self.notice("the job has not started yet — press c again in a moment");
971        } else {
972            self.notice(format!("cancelling {} {}…", j.verb(), j.subject()));
973            self.send(ScreenCmd::Cancel {
974                job_id: j.job_id.clone(),
975                download: is_download_kind(&j.kind),
976            });
977        }
978    }
979
980    /// `c` with no screen-specific target: the one live job, or say
981    /// which ones run.
982    pub fn cancel(&self) {
983        let live: Vec<JobView> = self
984            .store
985            .jobs
986            .with_untracked(|v| v.iter().filter(|j| j.is_active()).cloned().collect());
987        match live.as_slice() {
988            [] => self.notice("no job is running"),
989            [one] => self.cancel_job(one),
990            many => self.notice(format!(
991                "{} jobs are running — select the one to cancel (v shows the downloads)",
992                many.len()
993            )),
994        }
995    }
996
997    /// `o`: open a URL with the configured opener, and say what happened.
998    ///
999    /// The outcome is returned so a host can act on it: on
1000    /// [`OpenError::NoDisplay`] nothing was launched and the person needs
1001    /// the link itself (the notice already prints it).
1002    pub fn open_url(&self, url: &str) -> Result<(), OpenError> {
1003        let outcome = (self.opener)(url);
1004        match &outcome {
1005            Ok(()) => self.notice(format!("opened {url}")),
1006            // The URL LEADS: a narrow terminal clips the tail, never the link.
1007            Err(OpenError::NoDisplay { why }) => self.notice(format!(
1008                "open {url} on your computer — no display on this machine ({why})"
1009            )),
1010            Err(e) => self.notice(format!("could not open {url}: {e} — open it yourself")),
1011        }
1012        outcome
1013    }
1014
1015    /// Close the one modal these screens may hold (the filter input).
1016    fn close_modal(&self) {
1017        if let Some(m) = self.modal.borrow_mut().take() {
1018            m.close();
1019        }
1020    }
1021}
1022
1023/// Is there a display a browser could open on, here? `Err(why)` when not.
1024///
1025/// Reads the real environment; [`display_from`] is the rule.
1026pub fn display_available() -> Result<(), String> {
1027    let os = if cfg!(target_os = "macos") {
1028        "macos"
1029    } else if cfg!(target_os = "windows") {
1030        "windows"
1031    } else {
1032        "unix"
1033    };
1034    display_from(os, &|key| std::env::var_os(key))
1035}
1036
1037/// The display rule, for `os` = `macos` | `windows` | `unix` (Linux, BSD)
1038/// and an environment lookup:
1039///
1040/// - an SSH session (`SSH_CONNECTION`, `SSH_CLIENT` or `SSH_TTY` set) has no
1041///   display of the person's own: `open`/`xdg-open` would put a browser on
1042///   the REMOTE machine's screen, or fail — on every OS;
1043/// - on `unix`, a graphical session sets `DISPLAY` (X11) or
1044///   `WAYLAND_DISPLAY`; with neither, there is no screen at all (a headless
1045///   server, a container, a text console).
1046pub fn display_from(
1047    os: &str,
1048    env: &dyn Fn(&str) -> Option<std::ffi::OsString>,
1049) -> Result<(), String> {
1050    let set = |key: &str| env(key).is_some_and(|v| !v.is_empty());
1051    if ["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY"]
1052        .iter()
1053        .any(|k| set(k))
1054    {
1055        return Err(
1056            "this is an SSH session: a browser would open on the remote machine, not yours".into(),
1057        );
1058    }
1059    if os == "unix" && !set("DISPLAY") && !set("WAYLAND_DISPLAY") {
1060        return Err("no graphical session: DISPLAY and WAYLAND_DISPLAY are unset".into());
1061    }
1062    Ok(())
1063}
1064
1065/// The system opener: fixed argv, the URL as ONE argument, never a shell.
1066/// Never launches anything without a display ([`display_available`]):
1067/// that is [`OpenError::NoDisplay`], and the host shows the URL instead.
1068pub fn system_open(url: &str) -> Result<(), OpenError> {
1069    open_gated(url, display_available(), launch)
1070}
1071
1072/// The gate order, testable without a real opener: refuse non-http(s),
1073/// then refuse without a display — `launch` runs only past both.
1074fn open_gated(
1075    url: &str,
1076    display: Result<(), String>,
1077    launch: impl FnOnce(&str) -> Result<(), OpenError>,
1078) -> Result<(), OpenError> {
1079    if !(url.starts_with("https://") || url.starts_with("http://")) {
1080        return Err(OpenError::Refused("only http(s) links are opened".into()));
1081    }
1082    display.map_err(|why| OpenError::NoDisplay { why })?;
1083    launch(url)
1084}
1085
1086/// `open` / `explorer` / `xdg-open` with the URL as ONE argument.
1087fn launch(url: &str) -> Result<(), OpenError> {
1088    let (prog, args): (&str, Vec<&str>) = if cfg!(target_os = "macos") {
1089        ("open", vec![url])
1090    } else if cfg!(target_os = "windows") {
1091        ("explorer", vec![url])
1092    } else {
1093        ("xdg-open", vec![url])
1094    };
1095    std::process::Command::new(prog)
1096        .args(args)
1097        .stdin(std::process::Stdio::null())
1098        .stdout(std::process::Stdio::null())
1099        .stderr(std::process::Stdio::null())
1100        .spawn()
1101        .map(|_| ())
1102        .map_err(|e| OpenError::Failed(format!("{prog}: {e}")))
1103}
1104
1105// ---------------------------------------------------------------------
1106// Shared UI pieces
1107// ---------------------------------------------------------------------
1108
1109type ThemeSig = Signal<&'static abstracttui::theme::Theme>;
1110
1111/// Most live jobs the strip lists one per row (the rest are counted).
1112pub const STRIP_JOBS: usize = 3;
1113
1114/// One job as a strip row: bar, glyph, verb + subject, facts.
1115fn job_row(t: &TokenSet, j: &JobView) -> View {
1116    let (glyph, ink) = match j.status.as_str() {
1117        "completed" => ("✓", t.ok),
1118        "failed" => ("✗", t.error),
1119        "cancelled" => ("⊘", t.warn),
1120        _ if j.is_paused() => ("⏸", t.warn),
1121        _ => ("⟳", t.info),
1122    };
1123    let mut facts = vec![span_bold(
1124        format!(" {glyph} {} {} ", j.verb(), j.subject()),
1125        ink,
1126    )];
1127    let mut info = Vec::new();
1128    if let Some(p) = j.percent {
1129        info.push(format!("{p:.0}%"));
1130    }
1131    if let (Some(d), Some(tot)) = (j.downloaded_bytes, j.total_bytes) {
1132        info.push(format!(
1133            "{} / {}",
1134            data::bytes_label(Some(d)),
1135            data::bytes_label(Some(tot))
1136        ));
1137    }
1138    if let Some(bps) = j.bytes_per_second.filter(|b| *b > 0.0 && j.is_active()) {
1139        info.push(format!("{}/s", data::bytes_label(Some(bps as u64))));
1140    }
1141    match j.paused_label() {
1142        Some(p) if j.is_active() => info.push(p.to_string()),
1143        _ => info.push(j.status.clone()),
1144    }
1145    facts.push(span(info.join(" · "), t.text_muted));
1146    let bar = match j.fraction().filter(|_| !j.is_paused()) {
1147        Some(fr) => Progress::new(fr)
1148            .layout(LayoutStyle::default().w(24).h(1).shrink(0.0))
1149            .element(t)
1150            .build(),
1151        None => Element::new()
1152            .style(LayoutStyle::default().w(0).h(1))
1153            .build(),
1154    };
1155    Element::new()
1156        .style(LayoutStyle::row().gap(1).h(1).shrink(0.0))
1157        .child(bar)
1158        .child(line(facts))
1159        .build()
1160}
1161
1162/// The job strip: one row per LIVE job (up to [`STRIP_JOBS`], the rest
1163/// counted), else the last finished job; then one detail row for the
1164/// job touched last (its error / log line / CLI equivalent). Zero rows
1165/// when nothing ever ran.
1166pub fn job_strip(sctx: &ScreensCtx, theme: ThemeSig) -> View {
1167    let store = sctx.store;
1168    dyn_view(LayoutStyle::column().shrink(0.0), move || {
1169        let t = theme.get().tokens;
1170        let jobs = store.jobs.get();
1171        let last = store.job.get();
1172        let live: Vec<&JobView> = jobs.iter().filter(|j| j.is_active()).collect();
1173        let mut col = Element::new().style(LayoutStyle::column().shrink(0.0));
1174        if live.is_empty() {
1175            let Some(j) = last.as_ref() else {
1176                return Element::new().style(LayoutStyle::default().h(0)).build();
1177            };
1178            col = col.child(job_row(&t, j));
1179        } else {
1180            for j in live.iter().take(STRIP_JOBS) {
1181                col = col.child(job_row(&t, j));
1182            }
1183        }
1184        let Some(j) = last.as_ref().or(live.first().copied()) else {
1185            return col.build();
1186        };
1187        let detail = if let Some(e) = j.error.as_ref().filter(|_| j.status == "failed") {
1188            span(format!("   {e}"), t.error)
1189        } else if j.is_paused() {
1190            span(
1191                format!(
1192                    "   {} — the Engines screen (0) shows what to run; a continues",
1193                    j.message.as_deref().unwrap_or("waiting for a person")
1194                ),
1195                t.warn,
1196            )
1197        } else if let Some(l) = j.log_tail.last().or(j.message.as_ref()) {
1198            span(format!("   {l}"), t.text_faint)
1199        } else if let Some(c) = &j.cli_equivalent {
1200            span(format!("   same as: {c}"), t.text_faint)
1201        } else {
1202            span(String::new(), t.text_faint)
1203        };
1204        let mut second = vec![detail];
1205        if live.len() > STRIP_JOBS {
1206            second.push(span(
1207                format!("  · +{} more running", live.len() - STRIP_JOBS),
1208                t.text_muted,
1209            ));
1210        }
1211        if !live.is_empty() {
1212            second.push(span("  · c cancels", t.text_faint));
1213        }
1214        col.child(line(second)).build()
1215    })
1216}
1217
1218/// `c` on a download: the web console's two-step cancel — a question
1219/// whose default KEEPS the download, "Stop download" danger-tinted.
1220pub fn confirm_cancel_download(cx: Scope, sctx: &ScreensCtx, job: JobView) {
1221    if !sctx.require_admin("cancel downloads") {
1222        return;
1223    }
1224    let s = sctx.clone();
1225    let what = match job.kind.as_str() {
1226        "download_group" => "every download of this group".to_string(),
1227        _ => job.subject(),
1228    };
1229    ChoicePrompt::new(format!("Stop downloading {what}?"))
1230        .option("keep", "Keep downloading")
1231        .option_with(ChoiceOption::new("stop", "Stop download").danger(true))
1232        .initial("keep")
1233        .on_resolve(move |outcome| {
1234            if let ChoiceOutcome::Answered(ans) = outcome {
1235                if ans.selected.iter().any(|x| x == "stop") {
1236                    s.cancel_job(&job);
1237                    return;
1238                }
1239            }
1240            s.notice(format!("still downloading {}", job.subject()));
1241        })
1242        .open(cx);
1243}
1244
1245/// A table slot's stand-in (empty list, loading, failed read) that still
1246/// OWNS FOCUS. The page's verbs are shortcuts on the page element, and a
1247/// key only reaches them through the focus path: when the table that held
1248/// focus is replaced by a one-line placeholder, nothing is focused and
1249/// every key goes to the root — `v` could not leave an empty installed
1250/// list, `o` could not open a download page after a failed engines read.
1251pub fn focus_holder(view: View) -> View {
1252    Element::new()
1253        .style(LayoutStyle::column().grow(1.0))
1254        .focusable()
1255        .autofocus()
1256        .child(view)
1257        .build()
1258}
1259
1260/// One honest line for a remote read that is not ready.
1261pub fn remote_line<T>(t: &TokenSet, what: &str, r: &Remote<T>) -> Option<View> {
1262    match r {
1263        Remote::Ready(_) => None,
1264        Remote::NotAsked => Some(line(vec![span(
1265            format!(" {what}: not read yet"),
1266            t.text_muted,
1267        )])),
1268        Remote::Loading => Some(line(vec![span(format!(" ⟳ reading {what}…"), t.info)])),
1269        Remote::Failed(e) => Some(line(vec![
1270            span_bold(format!(" {what} {}: ", e.headline()), t.error),
1271            span(e.message.clone(), t.text),
1272        ])),
1273    }
1274}
1275
1276/// `d`'s confirm. Blockers change the question: `loaded` and
1277/// `shared_cache:*` can be overridden (force, danger-tinted), a
1278/// `remote_engine` cannot be deleted from here at all.
1279pub fn confirm_delete(
1280    cx: Scope,
1281    sctx: &ScreensCtx,
1282    provider: &str,
1283    artifact: &str,
1284    size: Option<u64>,
1285    blockers: Vec<String>,
1286) {
1287    if !sctx.require_admin("delete models") {
1288        return;
1289    }
1290    if blockers.iter().any(|b| b == "remote_engine") {
1291        sctx.notice(format!(
1292            "{provider} {artifact} lives on a remote engine — delete it on that host"
1293        ));
1294        return;
1295    }
1296    let size = data::bytes_label(size);
1297    let mut body_lines: Vec<(String, bool)> = vec![
1298        (format!("provider  {provider}"), false),
1299        (format!("artifact  {artifact}"), false),
1300        (format!("frees     {size}"), false),
1301        (format!("runs on   {}", sctx.host_label), false),
1302    ];
1303    let forced = !blockers.is_empty();
1304    for b in &blockers {
1305        body_lines.push((format!("blocked   {}", blocker_text(b)), true));
1306    }
1307    let question = if forced {
1308        format!("Delete {artifact}? It is blocked — deleting anyway forces it.")
1309    } else {
1310        format!("Delete {artifact} from {provider}? This removes the files from disk.")
1311    };
1312    let label = if forced {
1313        "Delete anyway (force)"
1314    } else {
1315        "Delete"
1316    };
1317    let rows = body_lines.len() as i32;
1318    let theme = use_theme(cx);
1319    let prompt = ChoicePrompt::new(question)
1320        .body(move |_mcx| {
1321            let t = theme.get_untracked().tokens;
1322            let mut col = Element::new().style(LayoutStyle::column());
1323            for (l, warn) in body_lines {
1324                col = col.child(line(vec![span(l, if warn { t.warn } else { t.text })]));
1325            }
1326            col.build()
1327        })
1328        .body_rows(rows)
1329        .option_with(ChoiceOption::new("delete", label).danger(true))
1330        .option("keep", "Keep it")
1331        .initial("keep");
1332    let sctx2 = sctx.clone();
1333    let (p, a) = (provider.to_string(), artifact.to_string());
1334    prompt
1335        .on_resolve(move |outcome| {
1336            if let ChoiceOutcome::Answered(ans) = outcome {
1337                if ans.selected.iter().any(|s| s == "delete") {
1338                    sctx2.delete(&p, &a, forced);
1339                    return;
1340                }
1341            }
1342            sctx2.notice(format!("kept {a}"));
1343        })
1344        .open(cx);
1345}
1346
1347fn blocker_text(b: &str) -> String {
1348    if b == "loaded" {
1349        return "loaded in memory right now (unload it, or force)".to_string();
1350    }
1351    if let Some(rest) = b.strip_prefix("shared_cache:") {
1352        return format!("shared cache — the same files serve {rest}");
1353    }
1354    b.to_string()
1355}
1356
1357/// The host-safety notes the install confirm prints (principle 4).
1358pub fn install_notes(engine: &EngineRow, host_os: Option<&str>) -> Vec<String> {
1359    let mut out = Vec::new();
1360    let method = engine.install.method.as_deref().unwrap_or("");
1361    let argv0 = engine
1362        .install
1363        .argv
1364        .first()
1365        .map(String::as_str)
1366        .unwrap_or("");
1367    let script_like = engine.install.argv.iter().any(|a| a.ends_with(".sh"));
1368    if argv0 == "sudo" || (method == "script" && host_os != Some("windows")) || script_like {
1369        out.push(
1370            "needs administrator rights (sudo): the installer may stop to ask for a password — \
1371             if it fails, run the command above yourself in a terminal"
1372                .to_string(),
1373        );
1374    }
1375    if method == "winget" || host_os == Some("windows") {
1376        out.push("Windows may show a UAC prompt on the host — approve it there".to_string());
1377    }
1378    match method {
1379        "brew" => out.push("Homebrew install — no sudo needed".to_string()),
1380        "pip" => out.push(
1381            "installs into the Python environment abstractcore runs from (no sudo)".to_string(),
1382        ),
1383        _ => {}
1384    }
1385    if engine.install.needs_admin == Some(true) {
1386        out.push(
1387            engine
1388                .install
1389                .admin_reason
1390                .clone()
1391                .unwrap_or_else(|| "one step needs an administrator; you are asked first".into()),
1392        );
1393    }
1394    if let Some(n) = &engine.install.notes {
1395        out.push(n.clone());
1396    }
1397    if let Some(b) = engine.install.estimated_bytes {
1398        out.push(format!("downloads about {}", data::bytes_label(Some(b))));
1399    }
1400    out
1401}
1402
1403/// `i`'s confirm: shows the exact argv, the host it runs on and the
1404/// sudo/UAC notes; offers Install, a dry run, or cancel (default).
1405pub fn confirm_install(cx: Scope, sctx: &ScreensCtx, engine: &EngineRow, host_os: Option<&str>) {
1406    if !sctx.require_admin("install engines") {
1407        return;
1408    }
1409    let command = engine.install.argv.join(" ");
1410    let mut body_lines: Vec<(String, bool)> = vec![
1411        (format!("command   {command}"), false),
1412        (format!("runs on   {}", sctx.host_label), false),
1413        (
1414            format!(
1415                "method    {}",
1416                engine.install.method.as_deref().unwrap_or("unknown")
1417            ),
1418            false,
1419        ),
1420    ];
1421    for n in install_notes(engine, host_os) {
1422        body_lines.push((format!("note      {n}"), true));
1423    }
1424    if !engine.install.steps.is_empty() {
1425        body_lines.push((
1426            format!("steps     {}", engine.install.steps.join(" · ")),
1427            false,
1428        ));
1429    }
1430    let width = body_lines
1431        .iter()
1432        .map(|(l, _)| abstracttui::text::width(l) as i32)
1433        .max()
1434        .unwrap_or(40)
1435        .min(100);
1436    let rows = body_lines.len() as i32;
1437    let theme = use_theme(cx);
1438    let prompt = ChoicePrompt::new(format!("Install {} on {}?", engine.name, sctx.host_label))
1439        .body(move |_mcx| {
1440            let t = theme.get_untracked().tokens;
1441            let mut col = Element::new().style(LayoutStyle::column());
1442            for (l, warn) in body_lines {
1443                col = col.child(line(vec![span(l, if warn { t.warn } else { t.text })]));
1444            }
1445            col.build()
1446        })
1447        .body_rows(rows)
1448        .body_width(width + 2)
1449        .option_with(ChoiceOption::new("install", format!("Install {}", engine.name)).danger(true))
1450        .option("dry", "Dry run — show what would run")
1451        .option("cancel", "Cancel")
1452        .initial("cancel");
1453    let sctx2 = sctx.clone();
1454    let id = engine.id.clone();
1455    prompt
1456        .on_resolve(move |outcome| {
1457            if let ChoiceOutcome::Answered(ans) = outcome {
1458                match ans.selected.first().map(String::as_str) {
1459                    Some("install") => sctx2.install(&id, false),
1460                    Some("dry") => sctx2.install(&id, true),
1461                    _ => sctx2.notice("install cancelled — nothing ran"),
1462                }
1463            }
1464        })
1465        .open(cx);
1466}
1467
1468/// `i` on an APP engine (Ollama / LM Studio on macOS) over a backend
1469/// that can choose the location: the web console's two real choices.
1470/// The two plans are asked for (two dry runs, nothing runs) while the
1471/// question is open, and the body says where each lands and whether an
1472/// administrator is needed — before anything is picked. Default: cancel.
1473pub fn confirm_install_location(cx: Scope, sctx: &ScreensCtx, engine: &EngineRow) {
1474    if !sctx.require_admin("install engines") {
1475        return;
1476    }
1477    sctx.load_plans(&engine.id);
1478    let store = sctx.store;
1479    let theme = use_theme(cx);
1480    let id = engine.id.clone();
1481    let name = engine.name.clone();
1482    let body_id = id.clone();
1483    let body_name = name.clone();
1484    let host = sctx.host_label.clone();
1485    let prompt = ChoicePrompt::new(format!("Install {name} on {host}?"))
1486        .body(move |_mcx| {
1487            let (id, name) = (body_id.clone(), body_name.clone());
1488            dyn_view(LayoutStyle::column(), move || {
1489                let t = theme.get().tokens;
1490                let plans = store.plans.with(|m| m.get(&id).cloned());
1491                let mut col = Element::new().style(LayoutStyle::column());
1492                match plans {
1493                    Some(Remote::Ready(p)) => {
1494                        let user = p.user.target.clone().unwrap_or_else(|| "~/Applications".into());
1495                        let sys = p.system.target.clone().unwrap_or_else(|| "/Applications".into());
1496                        col = col
1497                            .child(line(vec![
1498                                span_bold("just for you  ", t.text),
1499                                span(user, t.text),
1500                            ]))
1501                            .child(line(vec![span(
1502                                if p.user.needs_admin {
1503                                    "              an administrator is needed".to_string()
1504                                } else {
1505                                    "              only your account sees it, no password".to_string()
1506                                },
1507                                if p.user.needs_admin { t.warn } else { t.text_muted },
1508                            )]))
1509                            .child(line(vec![
1510                                span_bold("all users     ", t.text),
1511                                span(sys, t.text),
1512                            ]))
1513                            .child(line(vec![span(
1514                                if p.system.needs_admin {
1515                                    format!(
1516                                        "              administrator: {}",
1517                                        p.system.admin_reason.clone().unwrap_or_else(|| {
1518                                            "this account cannot write there; a password is asked first".into()
1519                                        })
1520                                    )
1521                                } else {
1522                                    "              no password needed".to_string()
1523                                },
1524                                if p.system.needs_admin { t.warn } else { t.text_muted },
1525                            )]));
1526                    }
1527                    Some(Remote::Failed(e)) => {
1528                        col = col
1529                            .child(line(vec![span(
1530                                format!("could not check the install locations: {}", e.message),
1531                                t.warn,
1532                            )]))
1533                            .child(line(vec![span(
1534                                "\"Let the host decide\" still works: /Applications when writable, else ~/Applications",
1535                                t.text_muted,
1536                            )]));
1537                    }
1538                    _ => {
1539                        col = col.child(line(vec![span(
1540                            format!("⟳ checking where {name} can go on this host…"),
1541                            t.info,
1542                        )]));
1543                    }
1544                }
1545                col.build()
1546            })
1547        })
1548        .body_rows(4)
1549        .body_width(90)
1550        .option_with(ChoiceOption::new("user", "Install just for you"))
1551        .option_with(ChoiceOption::new("system", "Install for all users").danger(true))
1552        .option("auto", "Let the host decide")
1553        .option("cancel", "Cancel")
1554        .initial("cancel");
1555    let s = sctx.clone();
1556    prompt
1557        .on_resolve(move |outcome| {
1558            if let ChoiceOutcome::Answered(ans) = outcome {
1559                let at = match ans.selected.first().map(String::as_str) {
1560                    Some("user") => Some(InstallLocation::User),
1561                    Some("system") => Some(InstallLocation::System),
1562                    Some("auto") => Some(InstallLocation::Auto),
1563                    _ => None,
1564                };
1565                if let Some(loc) = at {
1566                    s.install_at(&id, false, loc);
1567                    return;
1568                }
1569            }
1570            s.notice("install cancelled — nothing ran");
1571        })
1572        .open(cx);
1573}
1574
1575/// `/`: a one-field modal; Enter applies (empty clears), Esc keeps.
1576pub fn open_filter(cx: Scope, sctx: &ScreensCtx) {
1577    sctx.close_modal();
1578    let viewport = abstracttui::app::use_viewport(cx).get_untracked();
1579    let value = cx.signal(sctx.store.query.get_untracked());
1580    let theme = use_theme(cx);
1581    let slot = sctx.modal.clone();
1582    let apply_ctx = sctx.clone();
1583    let esc_ctx = sctx.clone();
1584    let size = Size::new(56.min(viewport.w - 4).max(20), 5);
1585    let modal = Modal::open(&sctx.overlays, cx, viewport, size, move |mcx| {
1586        let t = theme.get_untracked().tokens;
1587        let apply = Rc::new(move || {
1588            let q = value.get_untracked().trim().to_string();
1589            apply_ctx.close_modal();
1590            apply_ctx.store.query.set(q.clone());
1591            apply_ctx.store.catalog_sel.set(0);
1592            apply_ctx.store.installed_sel.set(0);
1593            apply_ctx.reload_catalog();
1594            apply_ctx.notice(if q.is_empty() {
1595                "filter cleared".to_string()
1596            } else {
1597                format!("filter: {q}")
1598            });
1599        });
1600        Element::new()
1601            .style(LayoutStyle::column().grow(1.0))
1602            .shortcut(KeyChord::plain(Key::Escape), move |_| esc_ctx.close_modal())
1603            .child(line(vec![span_bold(" Filter models", t.accent)]))
1604            .child(
1605                TextInput::new()
1606                    .layout(LayoutStyle::default().grow(1.0).h(1))
1607                    .value(value)
1608                    .placeholder("name, family, tag or artifact — empty clears")
1609                    .on_submit(move |_| apply())
1610                    .view(mcx),
1611            )
1612            .child(line(vec![span(
1613                " Enter applies · Esc keeps the current filter",
1614                t.text_faint,
1615            )]))
1616            .build()
1617    });
1618    *slot.borrow_mut() = Some(modal);
1619}
1620
1621/// Did the viewer's last refusal carry reasons? One line for a toast.
1622pub fn error_notice(verb: &str, subject: &str, e: &TransportError) -> String {
1623    let reasons = e.reasons();
1624    if reasons.is_empty() {
1625        format!("✗ {verb} {subject} {}: {}", e.headline(), e.message)
1626    } else {
1627        format!(
1628            "✗ {verb} {subject} {}: {} ({})",
1629            e.headline(),
1630            e.message,
1631            reasons.join(", ")
1632        )
1633    }
1634}
1635
1636#[cfg(test)]
1637mod display_tests {
1638    use super::display_from;
1639    use std::ffi::OsString;
1640
1641    fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<OsString> {
1642        move |k| {
1643            pairs
1644                .iter()
1645                .find(|(key, _)| *key == k)
1646                .map(|(_, v)| OsString::from(*v))
1647        }
1648    }
1649
1650    #[test]
1651    fn linux_without_display_or_wayland_has_no_display() {
1652        let why = display_from("unix", &env(&[])).unwrap_err();
1653        assert!(
1654            why.contains("DISPLAY and WAYLAND_DISPLAY are unset"),
1655            "{why}"
1656        );
1657        assert!(
1658            display_from("unix", &env(&[("DISPLAY", "")])).is_err(),
1659            "empty is unset"
1660        );
1661        assert!(display_from("unix", &env(&[("DISPLAY", ":0")])).is_ok());
1662        assert!(display_from("unix", &env(&[("WAYLAND_DISPLAY", "wayland-0")])).is_ok());
1663    }
1664
1665    #[test]
1666    fn an_ssh_session_has_no_display_on_every_os() {
1667        for os in ["macos", "windows", "unix"] {
1668            for key in ["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY"] {
1669                let pairs: &'static [(&'static str, &'static str)] = match key {
1670                    "SSH_CONNECTION" => &[
1671                        ("SSH_CONNECTION", "1.2.3.4 5 6.7.8.9 22"),
1672                        ("DISPLAY", ":0"),
1673                    ],
1674                    "SSH_CLIENT" => &[("SSH_CLIENT", "1.2.3.4 5 22"), ("DISPLAY", ":0")],
1675                    _ => &[("SSH_TTY", "/dev/ttys001"), ("DISPLAY", ":0")],
1676                };
1677                let why = display_from(os, &env(pairs)).unwrap_err();
1678                assert!(why.contains("SSH session"), "{os} {key}: {why}");
1679            }
1680        }
1681    }
1682
1683    #[test]
1684    fn a_local_mac_or_windows_desktop_has_one() {
1685        assert!(display_from("macos", &env(&[])).is_ok());
1686        assert!(display_from("windows", &env(&[])).is_ok());
1687    }
1688
1689    #[test]
1690    fn nothing_is_launched_without_a_display() {
1691        let launched = std::cell::Cell::new(false);
1692        let out = super::open_gated("https://example.org", Err("SSH".into()), |_| {
1693            launched.set(true);
1694            Ok(())
1695        });
1696        assert_eq!(out, Err(super::OpenError::NoDisplay { why: "SSH".into() }));
1697        assert!(!launched.get());
1698        let out = super::open_gated("https://example.org", Ok(()), |u| {
1699            assert_eq!(u, "https://example.org");
1700            launched.set(true);
1701            Ok(())
1702        });
1703        assert!(out.is_ok() && launched.get());
1704    }
1705
1706    #[test]
1707    fn system_open_refuses_non_http_before_anything_else() {
1708        assert!(matches!(
1709            super::system_open("file:///etc/passwd"),
1710            Err(super::OpenError::Refused(_))
1711        ));
1712    }
1713}