1pub 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
119pub 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#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
154#[non_exhaustive]
155pub enum CatalogView {
156 #[default]
158 Catalog,
159 Installed,
161 Downloads,
163}
164
165#[derive(Clone, Debug, PartialEq, Eq)]
176#[non_exhaustive]
177pub enum Access {
178 Admin,
181 ReadOnly(String),
185}
186
187impl Access {
188 pub fn is_admin(&self) -> bool {
189 matches!(self, Access::Admin)
190 }
191}
192
193pub const FINISHED_JOBS_KEPT: usize = 12;
195
196#[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 pub job: Signal<Option<JobView>>,
210 pub jobs: Signal<Vec<JobView>>,
214 pub hub: Signal<Option<String>>,
216 pub text_default: Signal<Remote<Option<(String, String)>>>,
218 pub plans: Signal<HashMap<String, Remote<InstallPlans>>>,
220 pub feed: Signal<Remote<usize>>,
222 pub downloads_sel: Signal<usize>,
223 pub query: Signal<String>,
225 pub engine_filter: Signal<Option<String>>,
227 pub fits_only: Signal<bool>,
229 pub category: Signal<Option<&'static str>>,
232 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 pub notice: Signal<Option<String>>,
241 pub catalog_gen: Signal<u64>,
243 pub providers_seen: Signal<Vec<String>>,
246}
247
248impl ScreensStore {
249 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 pub fn alive(&self) -> bool {
285 self.job.is_alive() && self.notice.is_alive() && self.catalog.is_alive()
286 }
287
288 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 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 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 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
341pub 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
370pub 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
381pub type Opener = Rc<dyn Fn(&str) -> Result<(), OpenError>>;
383
384#[derive(Clone, Debug, PartialEq, Eq)]
392#[non_exhaustive]
393pub enum OpenError {
394 NoDisplay { why: String },
396 Refused(String),
398 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#[derive(Clone)]
415pub struct ScreensOptions {
416 pub poll_interval: Duration,
418 pub poll_limit: Duration,
421 pub notice: Option<Signal<Option<String>>>,
424 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#[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 hub: bool,
462 },
463 LoadInstalled,
464 LoadDownloads,
466 LoadTextDefault,
467 #[non_exhaustive]
468 SetTextDefault {
469 provider: String,
470 model: String,
471 },
472 #[non_exhaustive]
474 LoadPlans {
475 engine: String,
476 },
477 #[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 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 download: bool,
518 },
519}
520
521#[derive(Clone, Debug)]
525#[non_exhaustive]
526pub struct JobPoll {
527 pub job_id: String,
528 pub download: bool,
531 pub since: Instant,
533 pub errors: u32,
535}
536
537impl JobPoll {
538 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
549pub(crate) fn is_download_kind(kind: &str) -> bool {
551 matches!(kind, "download" | "download_group")
552}
553
554#[derive(Clone)]
556pub struct ScreensCtx {
557 pub store: ScreensStore,
558 pub tx: Sender<ScreenCmd>,
559 pub overlays: Overlays,
560 pub host_label: Rc<str>,
562 pub caps: TransportCaps,
564 opener: Opener,
565 modal: Rc<RefCell<Option<Modal>>>,
566}
567
568impl ScreensCtx {
569 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 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 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 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 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 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 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 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 pub fn refresh_engines(&self) {
747 self.store.engines.set(Remote::Loading);
748 self.send(ScreenCmd::LoadEngines { probe: true });
749 }
750
751 fn start(&self, placeholder: JobView, cmd: ScreenCmd) {
754 upsert_job(&self.store, placeholder);
755 self.send(cmd);
756 }
757
758 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 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 pub fn install(&self, engine: &str, dry_run: bool) {
821 self.install_at(engine, dry_run, InstallLocation::Auto);
822 }
823
824 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 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 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 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 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 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 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 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 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 fn close_modal(&self) {
1017 if let Some(m) = self.modal.borrow_mut().take() {
1018 m.close();
1019 }
1020 }
1021}
1022
1023pub 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
1037pub 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
1065pub fn system_open(url: &str) -> Result<(), OpenError> {
1069 open_gated(url, display_available(), launch)
1070}
1071
1072fn 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
1086fn 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
1105type ThemeSig = Signal<&'static abstracttui::theme::Theme>;
1110
1111pub const STRIP_JOBS: usize = 3;
1113
1114fn 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
1162pub 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
1218pub 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
1245pub 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
1260pub 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
1276pub 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
1357pub 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
1403pub 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
1468pub 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
1575pub 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
1621pub 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}