capri-models: add ui module
This commit is contained in:
1 file changed
+890
@@ -0,0 +1,890 @@
|
||||
//! Settings pages (plain egui): Language model, External AI provider,
|
||||
//! Hugging Face, Model device, Startup. Long operations run on the tokio runtime and report
|
||||
//! progress into shared state; every change is saved through `SettingsStore::update`, and the
|
||||
//! app reacts to the broadcast (rebuilds the backend, restarts Ollama for device/context changes).
|
||||
use std::collections::BTreeSet;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{bail, Context as _, Result};
|
||||
use capri_core::{Settings, SettingsStore};
|
||||
use capri_llm::secrets::{api_key_problem, normalize_api_key, valid_hf_token, HF_ACCOUNT, HF_ORIGIN};
|
||||
use capri_llm::{ApiConnection, ApiSection, InferenceSection, ModelEntry, Ollama, OpenAi, RouterSection, SecretStore};
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use crate::catalog::{self, CHOICES, EMBEDDING_ALIAS, EMBEDDING_BASE};
|
||||
use crate::hardware::{self, Hardware};
|
||||
use crate::hf::{self, Hub, Library, Receipt, RepoInfo, SearchRow};
|
||||
use crate::manage::{self, Residency, ResidencyInfo};
|
||||
|
||||
const API_DISCLOSURE: &str = "Optional alternative to the local language model. Your messages, personality, relevant memory and tool results are sent to your chosen provider. Screen images are sent only when you enable vision and use screen features. Provider charges and privacy terms apply. Speech recognition and voice remain local.";
|
||||
const KEY_HELP: &str = "Each connection has its own encrypted key. Keys are never shown again or included in diagnostic reports.";
|
||||
const PASTE_HELP: &str = "Paste the key itself. Copied outer spaces and quotation marks are removed.";
|
||||
const CAPABILITY_HELP: &str = "Image support is required for screen questions. Set the same context limit as the server. Leave tool calls off for chat-only models.";
|
||||
const KEPT: &str = "Capri will reconnect with the prepared model. Your conversation, memory, voice and personal settings will be kept.";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Page {
|
||||
#[default]
|
||||
LanguageModel,
|
||||
ExternalProvider,
|
||||
HuggingFace,
|
||||
ModelDevice,
|
||||
Startup,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
const ALL: [(Page, &'static str); 5] = [
|
||||
(Page::LanguageModel, "Language model"),
|
||||
(Page::ExternalProvider, "External AI provider"),
|
||||
(Page::HuggingFace, "Hugging Face"),
|
||||
(Page::ModelDevice, "Model device"),
|
||||
(Page::Startup, "Startup"),
|
||||
];
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Action {
|
||||
Refresh,
|
||||
Download(&'static str),
|
||||
Apply(&'static str),
|
||||
DeleteModel(&'static str),
|
||||
SaveConnection,
|
||||
TestConnection(String),
|
||||
RemoveConnection(String),
|
||||
UseApi(Option<String>),
|
||||
HfSaveToken,
|
||||
HfRemoveToken,
|
||||
HfSearch,
|
||||
HfInspect(String),
|
||||
HfInstall,
|
||||
HfUse(String),
|
||||
HfRemove(String),
|
||||
SetDevice(String),
|
||||
Cancel,
|
||||
}
|
||||
|
||||
struct Confirm {
|
||||
title: &'static str,
|
||||
detail: String,
|
||||
label: &'static str,
|
||||
action: Action,
|
||||
}
|
||||
|
||||
struct Task {
|
||||
label: String,
|
||||
status: String,
|
||||
completed: u64,
|
||||
total: u64,
|
||||
abort: Option<tokio::task::AbortHandle>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
page: Page,
|
||||
loaded: bool,
|
||||
hardware: Option<Hardware>,
|
||||
inventory: Option<Vec<ModelEntry>>,
|
||||
residency: Option<ResidencyInfo>,
|
||||
task: Option<Task>,
|
||||
message: Option<String>,
|
||||
confirm: Option<Confirm>,
|
||||
secure: bool,
|
||||
keys: BTreeSet<String>,
|
||||
form: ApiConnection,
|
||||
form_key: String,
|
||||
editing: Option<String>,
|
||||
hf_query: String,
|
||||
hf_results: Vec<SearchRow>,
|
||||
hf_info: Option<RepoInfo>,
|
||||
hf_file: Option<String>,
|
||||
hf_projector: Option<String>,
|
||||
hf_installed: Vec<Receipt>,
|
||||
hf_token: String,
|
||||
hf_has_token: bool,
|
||||
}
|
||||
|
||||
/// Shared by the settings window and the background operations it starts.
|
||||
#[derive(Clone)]
|
||||
pub struct ModelsHandle {
|
||||
rt: tokio::runtime::Handle,
|
||||
store: Arc<SettingsStore>,
|
||||
ollama: Ollama,
|
||||
secrets: SecretStore,
|
||||
state: Arc<Mutex<State>>,
|
||||
ctx: Arc<Mutex<Option<egui::Context>>>,
|
||||
}
|
||||
|
||||
impl ModelsHandle {
|
||||
/// `ollama` is the client of the Ollama server Capri owns (`OllamaServer::client`).
|
||||
pub fn new(rt: tokio::runtime::Handle, store: Arc<SettingsStore>, ollama: Ollama, secrets: SecretStore) -> Self {
|
||||
let state = State { form: ApiConnection { model: String::new(), ..Default::default() }, ..Default::default() };
|
||||
Self { rt, store, ollama, secrets, state: Arc::new(Mutex::new(state)), ctx: Default::default() }
|
||||
}
|
||||
|
||||
fn library(&self) -> Library {
|
||||
Library::new(self.store.paths().data.join("huggingface"))
|
||||
}
|
||||
|
||||
fn repaint(ctx: &Mutex<Option<egui::Context>>) {
|
||||
if let Some(ctx) = ctx.lock().as_ref() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one exclusive operation (download, import, save…); its result text is shown.
|
||||
fn run(&self, label: &str, work: impl Future<Output = Result<String>> + Send + 'static) {
|
||||
let mut st = self.state.lock();
|
||||
if st.task.is_some() {
|
||||
st.message = Some("Wait for the model operation to finish.".into());
|
||||
return;
|
||||
}
|
||||
let (state, ctx) = (self.state.clone(), self.ctx.clone());
|
||||
let join = self.rt.spawn(async move {
|
||||
let result = work.await;
|
||||
let mut st = state.lock();
|
||||
st.task = None;
|
||||
st.message = Some(match result {
|
||||
Ok(text) => text,
|
||||
Err(e) => hf::scrub(&e.to_string()),
|
||||
});
|
||||
drop(st);
|
||||
Self::repaint(&ctx);
|
||||
});
|
||||
st.task = Some(Task { label: label.into(), status: String::new(), completed: 0, total: 0, abort: Some(join.abort_handle()) });
|
||||
st.message = None;
|
||||
}
|
||||
|
||||
fn progress(&self) -> impl FnMut(&str, u64, u64) + Send + 'static {
|
||||
let (state, ctx) = (self.state.clone(), self.ctx.clone());
|
||||
move |status: &str, completed: u64, total: u64| {
|
||||
if let Some(task) = state.lock().task.as_mut() {
|
||||
task.status = status.chars().take(160).collect();
|
||||
(task.completed, task.total) = (completed, total);
|
||||
}
|
||||
Self::repaint(&ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reloads hardware, inventory, residency, keys and Hugging Face packages (non-exclusive).
|
||||
pub fn refresh(&self) {
|
||||
let this = self.clone();
|
||||
self.rt.spawn(async move {
|
||||
let settings = this.store.get();
|
||||
let hardware = hardware::probe().await;
|
||||
let inventory = this.ollama.tags().await.ok();
|
||||
let residency = manage::residency(&this.ollama, &settings.model).await;
|
||||
let api: ApiSection = settings.section();
|
||||
let mut keys = BTreeSet::new();
|
||||
for c in &api.connections {
|
||||
if this.secrets.get(&c.id, &c.origin()).await.ok().flatten().is_some() {
|
||||
keys.insert(c.id.clone());
|
||||
}
|
||||
}
|
||||
let hf_has_token = this.secrets.get(HF_ACCOUNT, HF_ORIGIN).await.ok().flatten().is_some();
|
||||
let library = this.library();
|
||||
let installed = tokio::task::spawn_blocking(move || library.list()).await.unwrap_or_default();
|
||||
let mut st = this.state.lock();
|
||||
(st.hardware, st.inventory, st.residency, st.keys, st.hf_has_token, st.hf_installed) = (Some(hardware), inventory, Some(residency), keys, hf_has_token, installed);
|
||||
st.secure = this.secrets.secure();
|
||||
drop(st);
|
||||
Self::repaint(&this.ctx);
|
||||
});
|
||||
}
|
||||
|
||||
fn execute(&self, action: Action) {
|
||||
let (store, ollama, secrets) = (self.store.clone(), self.ollama.clone(), self.secrets.clone());
|
||||
match action {
|
||||
Action::Refresh => self.refresh(),
|
||||
Action::Cancel => {
|
||||
if let Some(task) = self.state.lock().task.take() {
|
||||
task.abort.inspect(|a| a.abort());
|
||||
self.state.lock().message = Some("Model download cancelled".into());
|
||||
}
|
||||
}
|
||||
Action::Download(id) => {
|
||||
let mut progress = self.progress();
|
||||
let this = self.clone();
|
||||
self.run("Downloading", async move {
|
||||
let choice = catalog::choice(id).context("Unknown language model.")?;
|
||||
let settings = store.get();
|
||||
manage::pull_model(&ollama, choice.model, &mut progress).await?;
|
||||
if choice.alias != choice.model {
|
||||
if settings.ollama_url.is_some() {
|
||||
bail!("Native Qwen aliases need the Ollama server Capri owns.");
|
||||
}
|
||||
let alias_settings = Settings { model: choice.alias.into(), upstream_model: choice.model.into(), ..settings.clone() };
|
||||
progress("Preparing the Capri model", 0, 0);
|
||||
manage::ensure_native_alias(&ollama, &alias_settings, &settings.models_dir(store.paths())).await?;
|
||||
}
|
||||
let embedding = settings.section::<InferenceSection>().embedding_model;
|
||||
if embedding == EMBEDDING_ALIAS && !manage::installed(&ollama.tags().await?, EMBEDDING_BASE) {
|
||||
manage::pull_model(&ollama, EMBEDDING_BASE, &mut progress).await?;
|
||||
}
|
||||
manage::ensure_embedding_alias(&ollama, &embedding).await?;
|
||||
this.refresh();
|
||||
Ok(format!("{} is ready.", choice.alias))
|
||||
});
|
||||
}
|
||||
Action::Apply(id) => {
|
||||
let hw = self.state.lock().hardware.clone().unwrap_or_default();
|
||||
let result = catalog::select_model_choice(id, &hw).and_then(|(choice, threads)| {
|
||||
store
|
||||
.update(|s| {
|
||||
catalog::apply_choice(s, choice, threads);
|
||||
let mut api: ApiSection = s.section();
|
||||
api.enabled = false;
|
||||
s.set_section(&api);
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
});
|
||||
self.state.lock().message = Some(result.map_or_else(|e| e, |_| "The model was changed. Capri reconnects before the next reply.".into()));
|
||||
}
|
||||
Action::DeleteModel(id) => {
|
||||
let this = self.clone();
|
||||
self.run("Removing", async move {
|
||||
let choice = catalog::choice(id).context("Unknown language model.")?;
|
||||
let settings = store.get();
|
||||
for name in BTreeSet::from([choice.alias, choice.model]) {
|
||||
manage::delete_model(&ollama, &settings, name).await?;
|
||||
}
|
||||
this.refresh();
|
||||
Ok(format!("{} was removed.", choice.alias))
|
||||
});
|
||||
}
|
||||
Action::SaveConnection => {
|
||||
let (form, key, editing) = {
|
||||
let st = self.state.lock();
|
||||
(st.form.clone(), normalize_api_key(&st.form_key), st.editing.clone())
|
||||
};
|
||||
let this = self.clone();
|
||||
self.run("Saving", async move {
|
||||
let mut connection = form.validated().map_err(anyhow::Error::msg)?;
|
||||
let api: ApiSection = store.section();
|
||||
let previous = editing.as_ref().and_then(|id| api.connections.iter().find(|c| &c.id == id).cloned());
|
||||
match (&editing, &previous) {
|
||||
(Some(_), None) => bail!("API connection was not found."),
|
||||
(None, _) if api.connections.len() >= ApiSection::MAX_CONNECTIONS => bail!("Remove a saved API connection first."),
|
||||
_ => {}
|
||||
}
|
||||
connection.id = previous.as_ref().map_or_else(new_id, |p| p.id.clone());
|
||||
let origin_changed = previous.as_ref().is_some_and(|p| p.origin() != connection.origin());
|
||||
if key.is_empty() {
|
||||
if origin_changed && !connection.is_local() {
|
||||
bail!("Enter a new API key when changing the provider address.");
|
||||
}
|
||||
if previous.is_none() && !connection.is_local() {
|
||||
bail!("Enter a valid API key.");
|
||||
}
|
||||
if origin_changed {
|
||||
secrets.delete(&connection.id).await?;
|
||||
}
|
||||
} else {
|
||||
if let Some(problem) = api_key_problem(&key) {
|
||||
bail!(problem);
|
||||
}
|
||||
secrets.set(&connection.id, &connection.origin(), &key).await.context("Secure credential storage is unavailable. API access was not saved.")?;
|
||||
}
|
||||
store.update(|s| {
|
||||
let mut api: ApiSection = s.section();
|
||||
match api.connections.iter_mut().find(|c| c.id == connection.id) {
|
||||
Some(c) => *c = connection.clone(),
|
||||
None => api.connections.push(connection.clone()),
|
||||
}
|
||||
s.set_section(&api);
|
||||
})?;
|
||||
let mut st = this.state.lock();
|
||||
(st.form_key, st.editing) = (String::new(), None);
|
||||
st.form = ApiConnection::default();
|
||||
drop(st);
|
||||
this.refresh();
|
||||
Ok("API connection saved.".into())
|
||||
});
|
||||
}
|
||||
Action::TestConnection(id) => {
|
||||
self.run("Testing", async move {
|
||||
let api: ApiSection = store.section();
|
||||
let connection = api.connections.into_iter().find(|c| c.id == id).context("API connection was not found.")?;
|
||||
let key = secrets.get(&connection.id, &connection.origin()).await?;
|
||||
let elapsed = OpenAi::new(connection, key).test().await?;
|
||||
Ok(format!("Connected in {} ms.", elapsed.as_millis()))
|
||||
});
|
||||
}
|
||||
Action::RemoveConnection(id) => {
|
||||
let this = self.clone();
|
||||
self.run("Removing", async move {
|
||||
let api: ApiSection = store.section();
|
||||
if api.enabled && api.active.as_deref() == Some(&id) {
|
||||
bail!("Switch to another connection before removing this one.");
|
||||
}
|
||||
secrets.delete(&id).await?;
|
||||
store.update(|s| {
|
||||
let mut api: ApiSection = s.section();
|
||||
api.connections.retain(|c| c.id != id);
|
||||
s.set_section(&api);
|
||||
})?;
|
||||
this.refresh();
|
||||
Ok("API connection removed.".into())
|
||||
});
|
||||
}
|
||||
Action::UseApi(id) => {
|
||||
let result = store.update(|s| {
|
||||
let mut api: ApiSection = s.section();
|
||||
api.enabled = id.is_some();
|
||||
if id.is_some() {
|
||||
api.active = id.clone();
|
||||
}
|
||||
s.set_section(&api);
|
||||
});
|
||||
self.state.lock().message = Some(result.map_or_else(|e| e.to_string(), |_| "Provider changed. Capri reconnects before the next reply.".into()));
|
||||
}
|
||||
Action::HfSaveToken => {
|
||||
let token = std::mem::take(&mut self.state.lock().hf_token).trim().to_string();
|
||||
let this = self.clone();
|
||||
self.run("Saving", async move {
|
||||
if !valid_hf_token(&token) {
|
||||
bail!("Enter a valid Hugging Face read token.");
|
||||
}
|
||||
secrets.set(HF_ACCOUNT, HF_ORIGIN, &token).await.context("Hugging Face access could not be saved securely.")?;
|
||||
this.refresh();
|
||||
Ok("Hugging Face token saved.".into())
|
||||
});
|
||||
}
|
||||
Action::HfRemoveToken => {
|
||||
let this = self.clone();
|
||||
self.run("Removing", async move {
|
||||
secrets.delete(HF_ACCOUNT).await?;
|
||||
this.refresh();
|
||||
Ok("Hugging Face token removed.".into())
|
||||
});
|
||||
}
|
||||
Action::HfSearch => {
|
||||
let query = self.state.lock().hf_query.clone();
|
||||
let this = self.clone();
|
||||
self.run("Searching", async move {
|
||||
let token = secrets.get(HF_ACCOUNT, HF_ORIGIN).await.ok().flatten();
|
||||
let rows = Hub::new(token).search(&query, 20).await?;
|
||||
let n = rows.len();
|
||||
let mut st = this.state.lock();
|
||||
(st.hf_results, st.hf_info) = (rows, None);
|
||||
Ok(format!("{n} models found."))
|
||||
});
|
||||
}
|
||||
Action::HfInspect(repository) => {
|
||||
let this = self.clone();
|
||||
self.run("Checking", async move {
|
||||
let token = secrets.get(HF_ACCOUNT, HF_ORIGIN).await.ok().flatten();
|
||||
let info = Hub::new(token).inspect(&repository, None).await?;
|
||||
let mut st = this.state.lock();
|
||||
let hw = st.hardware.clone().unwrap_or_default();
|
||||
st.hf_file = info.selected_filename.clone().or_else(|| hf::choose_file(&info, &hw));
|
||||
st.hf_projector = info.files.iter().filter(|f| f.kind == "projector").min_by_key(|f| f.bytes).map(|f| f.path.clone());
|
||||
st.hf_info = Some(info);
|
||||
Ok("Choose a GGUF model file.".into())
|
||||
});
|
||||
}
|
||||
Action::HfInstall => {
|
||||
let (info, file, projector) = {
|
||||
let st = self.state.lock();
|
||||
(st.hf_info.clone(), st.hf_file.clone(), st.hf_projector.clone())
|
||||
};
|
||||
let mut progress = self.progress();
|
||||
let (library, this) = (self.library(), self.clone());
|
||||
self.run("Downloading", async move {
|
||||
let (Some(info), Some(file)) = (info, file) else { bail!("Choose a GGUF model file.") };
|
||||
let plan = hf::plan(&info, &file, projector.as_deref(), store.get().context_tokens)?;
|
||||
let token = secrets.get(HF_ACCOUNT, HF_ORIGIN).await.ok().flatten();
|
||||
library.install(&Hub::new(token), &plan, |p| progress(p.status, p.completed, p.total)).await?;
|
||||
progress("importing", 0, 0);
|
||||
let profile = library.import(&ollama, &plan.id).await?;
|
||||
this.refresh();
|
||||
Ok(format!("{} is ready as {}.", profile.family, profile.alias))
|
||||
});
|
||||
}
|
||||
Action::HfUse(id) => {
|
||||
let receipt = self.state.lock().hf_installed.iter().find(|r| r.plan.id == id).cloned();
|
||||
let result = match receipt.and_then(|r| r.profile) {
|
||||
None => Err("Repair this model in the Hugging Face library first.".to_string()),
|
||||
Some(p) => store
|
||||
.update(|s| {
|
||||
s.model = p.alias.clone();
|
||||
s.upstream_model = p.alias.clone();
|
||||
s.context_tokens = p.context_tokens;
|
||||
s.keep_alive = 300;
|
||||
let mut inference: InferenceSection = s.section();
|
||||
inference.model_setup_required = false;
|
||||
inference.resource_profile = Some(p.id.clone());
|
||||
inference.model_capabilities = Some(p.capabilities.clone());
|
||||
inference.model_context_limit = Some(p.context_limit);
|
||||
inference.thinking_default = if p.capabilities.iter().any(|c| c == "thinking") { "low" } else { "off" }.into();
|
||||
s.set_section(&inference);
|
||||
let mut api: ApiSection = s.section();
|
||||
api.enabled = false;
|
||||
s.set_section(&api);
|
||||
})
|
||||
.map_err(|e| e.to_string()),
|
||||
};
|
||||
self.state.lock().message = Some(result.map_or_else(|e| e, |_| "The model was changed. Capri reconnects before the next reply.".into()));
|
||||
}
|
||||
Action::HfRemove(id) => {
|
||||
let (library, this) = (self.library(), self.clone());
|
||||
self.run("Removing", async move {
|
||||
let freed = library.remove(&ollama, &id, &store.get().model).await?;
|
||||
this.refresh();
|
||||
Ok(format!("Removed; {:.1} GB freed.", freed as f64 / 1e9))
|
||||
});
|
||||
}
|
||||
Action::SetDevice(device) => {
|
||||
let result = store.update(|s| {
|
||||
let mut inference: InferenceSection = s.section();
|
||||
s.acceleration = if device == "cpu" { "cpu" } else { "auto" }.into();
|
||||
inference.device = device.clone();
|
||||
s.set_section(&inference);
|
||||
});
|
||||
self.state.lock().message = Some(result.map_or_else(|e| e.to_string(), |_| "Model device saved. Ollama restarts with it.".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn new_id() -> String {
|
||||
let mut bytes = [0u8; 16];
|
||||
let _ = std::fs::File::open("/dev/urandom").and_then(|mut f| std::io::Read::read_exact(&mut f, &mut bytes));
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
let h = hex::encode(bytes);
|
||||
format!("{}-{}-{}-{}-{}", &h[..8], &h[8..12], &h[12..16], &h[16..20], &h[20..])
|
||||
}
|
||||
|
||||
fn gb(bytes: u64) -> String {
|
||||
format!("{:.1} GB", bytes as f64 / 1e9)
|
||||
}
|
||||
|
||||
/// Draws the model settings. `store` is the app's settings store (same as given to the handle).
|
||||
pub fn settings_ui(ui: &mut egui::Ui, store: &SettingsStore, handle: &ModelsHandle) {
|
||||
*handle.ctx.lock() = Some(ui.ctx().clone());
|
||||
let mut actions = Vec::new();
|
||||
{
|
||||
let mut guard = handle.state.lock();
|
||||
let st = &mut *guard;
|
||||
if !st.loaded {
|
||||
st.loaded = true;
|
||||
actions.push(Action::Refresh);
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (page, label) in Page::ALL {
|
||||
ui.selectable_value(&mut st.page, page, label);
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
if let Some(task) = &st.task {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{}… {}", task.label, task.status));
|
||||
if ui.button("Cancel").clicked() {
|
||||
actions.push(Action::Cancel);
|
||||
}
|
||||
});
|
||||
if task.total > 0 {
|
||||
ui.add(egui::ProgressBar::new(task.completed as f32 / task.total as f32).text(format!("{} / {}", gb(task.completed), gb(task.total))));
|
||||
} else {
|
||||
ui.add(egui::ProgressBar::new(0.0).animate(true));
|
||||
}
|
||||
}
|
||||
if let Some(message) = &st.message {
|
||||
ui.label(message);
|
||||
}
|
||||
if let Some(confirm) = &st.confirm {
|
||||
let mut decided = None;
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.strong(confirm.title);
|
||||
ui.label(&confirm.detail);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(confirm.label).clicked() {
|
||||
decided = Some(true);
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
decided = Some(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(yes) = decided {
|
||||
let confirm = st.confirm.take().expect("confirm");
|
||||
if yes {
|
||||
actions.push(confirm.action);
|
||||
}
|
||||
}
|
||||
}
|
||||
let settings = store.get();
|
||||
let busy = st.task.is_some();
|
||||
egui::ScrollArea::vertical().show(ui, |ui| match st.page {
|
||||
Page::LanguageModel => language_model(ui, store, &settings, st, busy, &mut actions),
|
||||
Page::ExternalProvider => external_provider(ui, &settings, st, busy, &mut actions),
|
||||
Page::HuggingFace => hugging_face(ui, &settings, st, busy, &mut actions),
|
||||
Page::ModelDevice => model_device(ui, store, &settings, st, &mut actions),
|
||||
Page::Startup => startup(ui, store, &settings),
|
||||
});
|
||||
}
|
||||
for action in actions {
|
||||
handle.execute(action);
|
||||
}
|
||||
}
|
||||
|
||||
fn save(store: &SettingsStore, change: impl FnOnce(&mut Settings)) {
|
||||
if let Err(e) = store.update(change) {
|
||||
tracing::warn!("settings not saved: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn language_model(ui: &mut egui::Ui, store: &SettingsStore, settings: &Settings, st: &mut State, busy: bool, actions: &mut Vec<Action>) {
|
||||
let api: ApiSection = settings.section();
|
||||
let inference: InferenceSection = settings.section();
|
||||
ui.heading("Language model");
|
||||
ui.label(if api.enabled { "Active: external AI provider. The local model stays installed.".to_string() } else { format!("Active: Local · {}", settings.model) });
|
||||
if let Some(r) = st.residency {
|
||||
let place = match r.status {
|
||||
Residency::Gpu => "on the GPU",
|
||||
Residency::Cpu => "on the CPU",
|
||||
Residency::Partial => "split between GPU and CPU",
|
||||
Residency::Unloaded => "not loaded",
|
||||
Residency::Unknown => "unknown",
|
||||
};
|
||||
ui.weak(format!("Memory: {place}{}", if r.total_bytes > 0 { format!(" ({}, {} on GPU, context {})", gb(r.total_bytes), gb(r.gpu_bytes), r.context_tokens) } else { String::new() }));
|
||||
}
|
||||
let recommendation = st.hardware.as_ref().map(catalog::recommend_profile);
|
||||
if let Some(r) = &recommendation {
|
||||
for reason in &r.reasons {
|
||||
ui.weak(reason);
|
||||
}
|
||||
}
|
||||
let language = settings.language.conversation.clone();
|
||||
let for_language = st.hardware.as_ref().map(|hw| catalog::recommend_models_for_language(&language, hw)).unwrap_or_default();
|
||||
if st.inventory.is_none() {
|
||||
ui.colored_label(ui.visuals().warn_fg_color, "The local model list is unavailable. Is Ollama running?");
|
||||
}
|
||||
let inventory = st.inventory.clone().unwrap_or_default();
|
||||
for choice in &CHOICES {
|
||||
ui.separator();
|
||||
let installed = manage::installed(&inventory, choice.alias) || manage::installed(&inventory, choice.model);
|
||||
let size = inventory.iter().find(|m| manage::tagged(&m.name) == manage::tagged(choice.model)).map(|m| m.size).or_else(|| catalog::download_size(choice.model));
|
||||
let active = !api.enabled && settings.model == choice.alias;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(format!("{} · {}", choice.family, choice.model));
|
||||
if choice.experimental {
|
||||
ui.label("BETA");
|
||||
}
|
||||
if recommendation.as_ref().and_then(|r| r.profile).is_some_and(|p| p.id == choice.id) {
|
||||
ui.label("Recommended");
|
||||
}
|
||||
if for_language.contains(&choice.id) {
|
||||
ui.label("Good for your language");
|
||||
}
|
||||
if active {
|
||||
ui.label("Active");
|
||||
}
|
||||
});
|
||||
ui.label(choice.description);
|
||||
let ram = st.hardware.as_ref().map(|hw| catalog::profile_ram_requirement(choice, hw)).unwrap_or(choice.ram_gib);
|
||||
ui.weak(format!("Needs {ram} GiB RAM{} · {}", if choice.recommended_vram_gib > 0.0 { format!(", {} GiB VRAM recommended", choice.recommended_vram_gib) } else { String::new() }, size.map_or("size unknown".into(), gb)));
|
||||
ui.horizontal(|ui| {
|
||||
if !installed && ui.add_enabled(!busy, egui::Button::new("Download")).clicked() {
|
||||
actions.push(Action::Download(choice.id));
|
||||
}
|
||||
if installed && !active && ui.add_enabled(!busy, egui::Button::new("Use this model")).clicked() {
|
||||
st.confirm = Some(Confirm { title: "Switch language model?", detail: KEPT.into(), label: "Switch model", action: Action::Apply(choice.id) });
|
||||
}
|
||||
if installed && !active && ui.add_enabled(!busy, egui::Button::new("Remove")).clicked() {
|
||||
actions.push(Action::DeleteModel(choice.id));
|
||||
}
|
||||
if installed && choice.alias != choice.model && !manage::installed(&inventory, choice.alias) && ui.add_enabled(!busy, egui::Button::new("Repair")).clicked() {
|
||||
actions.push(Action::Download(choice.id));
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.separator();
|
||||
ui.heading("Response");
|
||||
let choices = catalog::context_choices(&settings.model, inference.model_context_limit);
|
||||
let mut context = settings.context_tokens;
|
||||
egui::ComboBox::from_label("Context window").selected_text(format!("{} K tokens", context / 1024)).show_ui(ui, |ui| {
|
||||
for c in &choices {
|
||||
ui.selectable_value(&mut context, *c, format!("{} K tokens", c / 1024));
|
||||
}
|
||||
});
|
||||
if context != settings.context_tokens {
|
||||
save(store, |s| s.context_tokens = context);
|
||||
}
|
||||
let (mut keep, mut temperature, mut repeat) = (settings.keep_alive, settings.temperature, settings.repeat_last_n);
|
||||
ui.add(egui::DragValue::new(&mut keep).range(-1..=86400).prefix("Keep loaded (s, -1 = always): "));
|
||||
ui.add(egui::Slider::new(&mut temperature, 0.0..=1.5).text("Temperature"));
|
||||
ui.add(egui::Slider::new(&mut repeat, 0..=2048).text("Repetition window (tokens)"));
|
||||
if (keep, temperature, repeat) != (settings.keep_alive, settings.temperature, settings.repeat_last_n) {
|
||||
save(store, |s| (s.keep_alive, s.temperature, s.repeat_last_n) = (keep, temperature, repeat));
|
||||
}
|
||||
if ui.button("Refresh").clicked() {
|
||||
actions.push(Action::Refresh);
|
||||
}
|
||||
}
|
||||
|
||||
fn external_provider(ui: &mut egui::Ui, settings: &Settings, st: &mut State, busy: bool, actions: &mut Vec<Action>) {
|
||||
let api: ApiSection = settings.section();
|
||||
ui.heading("External AI provider");
|
||||
ui.label(API_DISCLOSURE);
|
||||
if !st.secure {
|
||||
ui.colored_label(ui.visuals().warn_fg_color, "No desktop keyring answered (KWallet or GNOME Keyring). Keys are kept in a private file readable only by you.");
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add_enabled(api.enabled && !busy, egui::Button::new("Use the local model")).clicked() {
|
||||
st.confirm = Some(Confirm { title: "Change AI provider?", detail: "Capri will reconnect using your downloaded local language model.".into(), label: "Apply", action: Action::UseApi(None) });
|
||||
}
|
||||
ui.label(if api.enabled { api.active_connection().map_or("API · OFFLINE".into(), ApiConnection::label) } else { format!("Local · {}", settings.model) });
|
||||
});
|
||||
for c in &api.connections {
|
||||
ui.separator();
|
||||
let has_key = st.keys.contains(&c.id);
|
||||
ui.strong(if c.name.is_empty() { c.label() } else { format!("{} · {}", c.name, c.label()) });
|
||||
ui.weak(format!("{} · context {} · tools {} · images {} · reasoning {}{}", c.base_url, c.context_tokens, c.tools, c.vision, c.thinking, if has_key { " · key saved" } else { "" }));
|
||||
ui.horizontal(|ui| {
|
||||
let active = api.enabled && api.active.as_deref() == Some(&c.id);
|
||||
let can_connect = has_key || c.is_local();
|
||||
if !active && ui.add_enabled(can_connect && !busy, egui::Button::new("Use")).clicked() {
|
||||
let detail = if c.is_local() {
|
||||
"Capri will send requests to the selected server on this PC and reconnect.".into()
|
||||
} else {
|
||||
"Your conversation, personality, relevant memory and tool results will be sent to this provider. Images are sent only with enabled vision and screen features. Provider charges may apply. Capri will reconnect.".into()
|
||||
};
|
||||
st.confirm = Some(Confirm { title: "Change AI provider?", detail, label: "Apply", action: Action::UseApi(Some(c.id.clone())) });
|
||||
}
|
||||
if ui.add_enabled(!busy, egui::Button::new("Edit")).clicked() {
|
||||
(st.form, st.form_key, st.editing) = (c.clone(), String::new(), Some(c.id.clone()));
|
||||
}
|
||||
if ui.add_enabled(can_connect && !busy, egui::Button::new("Test")).clicked() {
|
||||
actions.push(Action::TestConnection(c.id.clone()));
|
||||
}
|
||||
if !active && ui.add_enabled(!busy, egui::Button::new("Remove")).clicked() {
|
||||
st.confirm = Some(Confirm { title: "Remove API connection?", detail: "Its saved API key will be removed from this PC.".into(), label: "Remove", action: Action::RemoveConnection(c.id.clone()) });
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.separator();
|
||||
ui.strong(if st.editing.is_some() { "Edit connection" } else { "New connection" });
|
||||
let form = &mut st.form;
|
||||
egui::ComboBox::from_label("Provider").selected_text(capri_llm::openai::PRESETS.iter().find(|(_, url)| *url == form.base_url).map_or("Custom", |(n, _)| n)).show_ui(ui, |ui| {
|
||||
for (name, url) in capri_llm::openai::PRESETS {
|
||||
if ui.selectable_label(form.base_url == *url, *name).clicked() {
|
||||
form.base_url = url.to_string();
|
||||
form.tools = !url.starts_with("http://");
|
||||
if form.is_local() {
|
||||
form.context_tokens = form.context_tokens.max(8192);
|
||||
} else {
|
||||
form.context_tokens = form.context_tokens.max(32768);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Name");
|
||||
ui.text_edit_singleline(&mut form.name);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Base URL");
|
||||
ui.text_edit_singleline(&mut form.base_url);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Model ID");
|
||||
ui.text_edit_singleline(&mut form.model);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("API key");
|
||||
ui.add(egui::TextEdit::singleline(&mut st.form_key).password(true).hint_text(if st.editing.is_some() { "unchanged" } else { "" }));
|
||||
});
|
||||
ui.weak(KEY_HELP);
|
||||
ui.weak(PASTE_HELP);
|
||||
let form = &mut st.form;
|
||||
ui.checkbox(&mut form.tools, "Tool calls");
|
||||
ui.checkbox(&mut form.vision, "Images (vision)");
|
||||
ui.checkbox(&mut form.thinking, "Reasoning control");
|
||||
ui.add(egui::DragValue::new(&mut form.context_tokens).range(8192..=262144).speed(1024).prefix("Context tokens: "));
|
||||
ui.weak(CAPABILITY_HELP);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add_enabled(!busy, egui::Button::new("Save connection")).clicked() {
|
||||
actions.push(Action::SaveConnection);
|
||||
}
|
||||
if st.editing.is_some() && ui.button("New").clicked() {
|
||||
(st.form, st.form_key, st.editing) = (ApiConnection::default(), String::new(), None);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn hugging_face(ui: &mut egui::Ui, settings: &Settings, st: &mut State, busy: bool, actions: &mut Vec<Action>) {
|
||||
ui.heading("Hugging Face");
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(if st.hf_has_token { "Read token saved." } else { "No token: public models only." });
|
||||
ui.add(egui::TextEdit::singleline(&mut st.hf_token).password(true).hint_text("hf_…"));
|
||||
if ui.add_enabled(!busy && !st.hf_token.is_empty(), egui::Button::new("Save token")).clicked() {
|
||||
actions.push(Action::HfSaveToken);
|
||||
}
|
||||
if st.hf_has_token && ui.add_enabled(!busy, egui::Button::new("Remove token")).clicked() {
|
||||
actions.push(Action::HfRemoveToken);
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.text_edit_singleline(&mut st.hf_query);
|
||||
if ui.add_enabled(!busy, egui::Button::new("Search GGUF")).clicked() {
|
||||
actions.push(Action::HfSearch);
|
||||
}
|
||||
});
|
||||
for row in &st.hf_results {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{} · {} downloads{}", row.repository, row.downloads, if row.gated { " · gated" } else { "" }));
|
||||
if ui.add_enabled(!busy, egui::Button::new("Inspect")).clicked() {
|
||||
actions.push(Action::HfInspect(row.repository.clone()));
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(info) = &st.hf_info {
|
||||
ui.separator();
|
||||
ui.strong(format!("{} @ {}", info.repository, &info.revision[..12.min(info.revision.len())]));
|
||||
if let Some(license) = &info.license {
|
||||
ui.weak(format!("License: {license}"));
|
||||
}
|
||||
let size = |path: &str| info.files.iter().find(|f| f.path == path).and_then(|f| f.bytes).map_or("?".into(), gb);
|
||||
egui::ComboBox::from_label("Model file").selected_text(st.hf_file.clone().unwrap_or_default()).show_ui(ui, |ui| {
|
||||
for f in info.files.iter().filter(|f| f.kind == "gguf" && (!f.split || f.path.contains("-00001-of-"))) {
|
||||
ui.selectable_value(&mut st.hf_file, Some(f.path.clone()), format!("{} ({})", f.path, size(&f.path)));
|
||||
}
|
||||
});
|
||||
if info.files.iter().any(|f| f.kind == "projector") {
|
||||
egui::ComboBox::from_label("Vision projector").selected_text(st.hf_projector.clone().unwrap_or_else(|| "None".into())).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut st.hf_projector, None, "None");
|
||||
for f in info.files.iter().filter(|f| f.kind == "projector") {
|
||||
ui.selectable_value(&mut st.hf_projector, Some(f.path.clone()), format!("{} ({})", f.path, size(&f.path)));
|
||||
}
|
||||
});
|
||||
}
|
||||
match st.hf_file.as_deref().map(|f| hf::plan(info, f, st.hf_projector.as_deref(), settings.context_tokens)) {
|
||||
Some(Ok(plan)) => {
|
||||
let gib = plan.total_bytes as f64 / (1u64 << 30) as f64;
|
||||
ui.weak(format!("Download {} · about {:.0} GiB RAM on CPU, {:.0} GiB VRAM on GPU (estimate)", gb(plan.total_bytes), (gib * 1.3 + 4.0).ceil(), (gib + 2.0).ceil()));
|
||||
if ui.add_enabled(!busy, egui::Button::new("Download and import")).clicked() {
|
||||
actions.push(Action::HfInstall);
|
||||
}
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
ui.label(e.to_string());
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
ui.strong("Downloaded models");
|
||||
for r in &st.hf_installed {
|
||||
ui.horizontal(|ui| {
|
||||
let alias = r.profile.as_ref().map(|p| p.alias.clone());
|
||||
ui.label(format!("{} · {}{}", r.plan.repository, gb(r.plan.total_bytes), if alias.as_deref() == Some(settings.model.as_str()) { " · Active" } else { "" }));
|
||||
if alias.as_deref() != Some(settings.model.as_str()) {
|
||||
if r.profile.is_some() && ui.add_enabled(!busy, egui::Button::new("Use")).clicked() {
|
||||
st.confirm = Some(Confirm { title: "Switch language model?", detail: KEPT.into(), label: "Switch model", action: Action::HfUse(r.plan.id.clone()) });
|
||||
}
|
||||
if ui.add_enabled(!busy, egui::Button::new("Remove")).clicked() {
|
||||
st.confirm = Some(Confirm { title: "Remove downloaded model?", detail: "The selected Hugging Face package will be removed from this PC.".into(), label: "Remove", action: Action::HfRemove(r.plan.id.clone()) });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn model_device(ui: &mut egui::Ui, store: &SettingsStore, settings: &Settings, st: &mut State, actions: &mut Vec<Action>) {
|
||||
let inference: InferenceSection = settings.section();
|
||||
ui.heading("Model device");
|
||||
let Some(hw) = &st.hardware else {
|
||||
ui.label("Checking hardware…");
|
||||
return;
|
||||
};
|
||||
ui.label(format!("{} · {} threads · {:.1} GiB RAM ({:.1} GiB available)", hw.cpu, hw.cpu_threads, hw.ram_gib(), hw.available_ram_bytes as f64 / (1u64 << 30) as f64));
|
||||
for w in &hw.warnings {
|
||||
ui.weak(w);
|
||||
}
|
||||
let mut device = inference.device.clone();
|
||||
ui.radio_value(&mut device, "auto".to_string(), "Automatic (Ollama chooses)");
|
||||
ui.radio_value(&mut device, "cpu".to_string(), "CPU only");
|
||||
let mut ordinals = std::collections::HashMap::new();
|
||||
for gpu in &hw.gpus {
|
||||
let n = ordinals.entry(gpu.vendor.clone()).or_insert(0usize);
|
||||
let memory = match (gpu.memory_kind.as_str(), gpu.vram_mib) {
|
||||
("dedicated", Some(v)) => format!("{:.1} GiB VRAM{}", v as f64 / 1024.0, gpu.free_vram_mib.map_or(String::new(), |f| format!(", {:.1} GiB free", f as f64 / 1024.0))),
|
||||
("shared", _) => "shared memory".into(),
|
||||
_ => "VRAM unknown".into(),
|
||||
};
|
||||
match gpu.device_id(*n) {
|
||||
Some(id) => {
|
||||
ui.radio_value(&mut device, id, format!("{} ({memory})", gpu.name));
|
||||
}
|
||||
None => {
|
||||
ui.weak(format!("{} ({memory}): not available to the language model runtime", gpu.name));
|
||||
}
|
||||
}
|
||||
*n += 1;
|
||||
}
|
||||
if device != inference.device {
|
||||
st.confirm = Some(Confirm { title: "Model devices", detail: KEPT.into(), label: "Save and reconnect", action: Action::SetDevice(device) });
|
||||
}
|
||||
let mut auto_threads = settings.cpu_threads.is_none();
|
||||
let mut threads = settings.cpu_threads.unwrap_or(4);
|
||||
ui.checkbox(&mut auto_threads, "Automatic CPU threads");
|
||||
if !auto_threads {
|
||||
ui.add(egui::DragValue::new(&mut threads).range(1..=16).prefix("CPU threads: "));
|
||||
}
|
||||
let wanted = (!auto_threads).then_some(threads);
|
||||
if wanted != settings.cpu_threads {
|
||||
save(store, |s| s.cpu_threads = wanted);
|
||||
}
|
||||
if ui.button("Check hardware again").clicked() {
|
||||
actions.push(Action::Refresh);
|
||||
}
|
||||
}
|
||||
|
||||
fn startup(ui: &mut egui::Ui, store: &SettingsStore, settings: &Settings) {
|
||||
let mut inference: InferenceSection = settings.section();
|
||||
let mut router: RouterSection = settings.section();
|
||||
ui.heading("Startup");
|
||||
ui.checkbox(&mut inference.preload_models, "Load the models when Capri starts");
|
||||
ui.checkbox(&mut inference.skip_local_model_on_api, "With an external AI provider, do not load the local language model");
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Memory embedding model");
|
||||
ui.text_edit_singleline(&mut inference.embedding_model);
|
||||
});
|
||||
ui.checkbox(&mut router.enabled, "Fast replies for small talk (request router)");
|
||||
ui.add_enabled(router.enabled, egui::Slider::new(&mut router.timeout_ms, 25..=250).text("Router time budget (ms)"));
|
||||
ui.weak(format!("Minimum Ollama version: {}", inference.min_ollama_version));
|
||||
if inference != settings.section::<InferenceSection>() || router != settings.section::<RouterSection>() {
|
||||
save(store, |s| {
|
||||
s.set_section(&inference);
|
||||
s.set_section(&router);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ids_and_pages_render_headless() {
|
||||
let id = new_id();
|
||||
assert_eq!(id.len(), 36);
|
||||
assert!(regex::Regex::new("^[a-f0-9-]{36}$").unwrap().is_match(&id));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let paths = capri_core::Paths::under(dir.path().to_path_buf());
|
||||
paths.ensure().unwrap();
|
||||
let store = SettingsStore::new(paths, Settings::default());
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let handle = ModelsHandle::new(rt.handle().clone(), store.clone(), Ollama::new("http://127.0.0.1:9"), SecretStore::file(dir.path().join("s.json")));
|
||||
let ctx = egui::Context::default();
|
||||
for (page, _) in Page::ALL {
|
||||
handle.state.lock().page = page;
|
||||
ctx.run_ui(Default::default(), |ui| settings_ui(ui, &store, &handle)).textures_delta.clear();
|
||||
}
|
||||
handle.execute(Action::SetDevice("cpu".into()));
|
||||
assert_eq!(store.get().acceleration, "cpu");
|
||||
assert_eq!(store.section::<InferenceSection>().device, "cpu");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user