use std::sync::{Arc, Mutex};
pub use bigtext::ai::config::{resolve_key, AiConfig, KeyStatus, ProviderConf, STEPS_MAX};
use bigtext::ai::chat::{Effort, Message, Request, ToolSpec};
use bigtext::ai::keys::{self, KeyStore};
use bigtext::ai::privacy;
use bigtext::ai::{preset, AiError, Provider, PRESETS};
use bigtext::jobs::{self, CancelToken};
use super::i18n::{tr, trf};
use super::BigTextApp;
#[derive(Default)]
struct Reports {
key: Option<KeyStatus>,
key_msg: Option<String>,
models: Option<Result<Vec<String>, String>>,
test: Option<Result<String, String>>,
}
#[derive(Default)]
pub struct SettingsUi {
pub open: bool,
key_input: String,
passphrase: String,
key_for: String,
key: Option<KeyStatus>,
key_msg: Option<String>,
models: Vec<String>,
models_for: String,
busy_models: bool,
test: Option<Result<String, String>>,
busy_test: bool,
reports: Arc<Mutex<Reports>>,
}
fn test_provider(p: &Provider) -> Result<String, String> {
let cancel = CancelToken::new();
let msgs = [Message::user("Call the ping tool.")];
let tool = [ToolSpec {
name: "ping".into(),
description: "Answers pong. Call it when asked.".into(),
schema: serde_json::json!({"type": "object", "properties": {}, "additionalProperties": false}),
}];
let req = Request {
model: "",
system: "You are a connection test.",
messages: &msgs,
tools: &tool,
max_tokens: 1024,
json: None,
effort: Some(Effort::Low),
};
let model = p.model.trim().to_string();
match p.send(&req, &cancel, &mut |_| {}) {
Ok(r) if !r.message().tool_uses().is_empty() => Ok(trf(
"Connected to {model}. Tool calling works: questions can take several steps.",
&[("model", &model)],
)),
Ok(_) => Ok(trf(
"Connected to {model}, but it did not call the test tool: turn tool calling off to plan one step in JSON.",
&[("model", &model)],
)),
Err(AiError::Status { code: 400 | 404 | 422, .. }) => {
let plain = Request {
tools: &[],
messages: &[Message::user("Reply with OK.")],
..req
};
p.send(&plain, &cancel, &mut |_| {})
.map(|_| {
trf(
"Connected to {model}, but it does not take tools: turn tool calling off to plan one step in JSON.",
&[("model", &model)],
)
})
.map_err(|e| e.user_text())
}
Err(e) => Err(e.user_text()),
}
}
impl BigTextApp {
pub(crate) fn open_ai_settings(&mut self) {
self.ai.settings.open = true;
self.ai.settings.key = None;
self.ai.settings.key_for.clear();
}
fn ai_check_key(&mut self) {
let Some(p) = preset(&self.ai.cfg.provider) else {
return;
};
let s = &mut self.ai.settings;
s.key_for = p.id.to_string();
s.key = None;
let (store, reports, waker) =
(self.ai.store.clone(), s.reports.clone(), self.waker.clone());
jobs::spawn("ai-key", move || {
let (_, status) = resolve_key(&store, p);
reports.lock().unwrap().key = Some(status);
waker();
});
}
fn ai_take_reports(&mut self) {
let s = &mut self.ai.settings;
let mut r = s.reports.lock().unwrap();
if let Some(k) = r.key.take() {
s.key = Some(k);
}
if let Some(m) = r.key_msg.take() {
s.key_msg = Some(m);
}
if let Some(m) = r.models.take() {
s.busy_models = false;
match m {
Ok(list) => {
s.models = list;
if s.models.is_empty() {
s.test = Some(Err(tr("The provider lists no models.").into()));
}
}
Err(e) => s.test = Some(Err(e)),
}
}
if let Some(t) = r.test.take() {
s.busy_test = false;
s.test = Some(t);
}
}
fn ai_worker_provider(&self) -> Option<(Provider, KeyStore, String)> {
let p = self.ai.cfg.provider()?;
Some((
p,
self.ai.store.clone(),
self.ai.settings.key_input.trim().to_string(),
))
}
pub(super) fn ai_settings_window(&mut self, ctx: &egui::Context) {
if !self.ai.settings.open {
return;
}
self.ai_take_reports();
if self.ai.cfg.enabled() && self.ai.settings.key_for != self.ai.cfg.provider {
self.ai_check_key();
}
let mut open = true;
let mut changed = false;
let mut act: Option<&'static str> = None;
egui::Window::new(tr("AI settings"))
.open(&mut open)
.resizable(true)
.default_width(520.0)
.show(ctx, |ui| {
egui::ScrollArea::vertical().show(ui, |ui| {
ui.label(tr("The assistant turns a request into BigText's own searches and filters, runs them on this computer and sends the model only short results, never the file."));
ui.add_space(6.0);
let cfg = &mut self.ai.cfg;
let current = preset(&cfg.provider).map(|p| p.name).unwrap_or_else(|| tr("Off"));
egui::Grid::new("ai-provider").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| {
ui.label(tr("Provider"));
egui::ComboBox::from_id_salt("ai-preset")
.selected_text(current)
.width(300.0)
.show_ui(ui, |ui| {
if ui.selectable_label(cfg.provider.is_empty(), tr("Off")).clicked() {
cfg.provider.clear();
changed = true;
}
for p in PRESETS {
if ui.selectable_label(cfg.provider == p.id, p.name).clicked() {
cfg.provider = p.id.into();
changed = true;
}
}
});
ui.end_row();
let Some(p) = preset(&cfg.provider) else {
return;
};
let mut c = cfg.conf(p.id).unwrap_or_else(|| ProviderConf::from_preset(p));
ui.label(tr("Address"));
let r = ui.add(egui::TextEdit::singleline(&mut c.url).desired_width(300.0));
changed |= r.changed();
ui.end_row();
ui.label(tr("Model"));
ui.horizontal(|ui| {
changed |= ui.add(egui::TextEdit::singleline(&mut c.model).desired_width(200.0).hint_text(tr("choose from the list"))).changed();
let models = &self.ai.settings.models;
if !models.is_empty() && self.ai.settings.models_for == p.id {
egui::ComboBox::from_id_salt("ai-models").selected_text("▾").width(30.0).show_ui(ui, |ui| {
for m in models {
if ui.selectable_label(c.model == *m, m).clicked() {
c.model = m.clone();
changed = true;
}
}
});
}
if ui.add_enabled(!self.ai.settings.busy_models, egui::Button::new(tr("Load models"))).clicked() {
act = Some("models");
}
});
ui.end_row();
if p.needs_key || p.id == "custom" {
ui.label(tr("API key"));
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.ai.settings.key_input).password(true).desired_width(200.0).hint_text(tr("paste the key")));
if ui.add_enabled(!self.ai.settings.key_input.trim().is_empty(), egui::Button::new(tr("Save key"))).clicked() {
act = Some("save_key");
}
if ui.button(tr("Remove")).on_hover_text(tr("Remove the stored key")).clicked() {
act = Some("delete_key");
}
});
ui.end_row();
ui.label("");
let status = match &self.ai.settings.key {
None => tr("Looking for the key…").to_string(),
Some(KeyStatus::Env(v)) => trf("From the environment variable {var}.", &[("var", v)]),
Some(KeyStatus::Keychain) => tr("Stored in the system keychain.").into(),
Some(KeyStatus::File(f)) => trf("Stored in the encrypted key file {file}.", &[("file", f)]),
Some(KeyStatus::Missing) => tr("No key yet. Keys stay in the system keychain, never in the settings.").into(),
Some(KeyStatus::Locked) => tr("The key file is locked with a passphrase.").into(),
Some(KeyStatus::Failed(e)) => e.clone(),
Some(KeyStatus::NotNeeded) => tr("No key needed.").into(),
};
ui.label(egui::RichText::new(status).weak());
ui.end_row();
if let Some(m) = &self.ai.settings.key_msg {
ui.label("");
ui.label(egui::RichText::new(m).weak());
ui.end_row();
}
}
if p.protocol == bigtext::ai::Protocol::Anthropic {
ui.label(tr("Workspace ID"));
changed |= ui
.add(egui::TextEdit::singleline(&mut c.workspace).desired_width(300.0).hint_text(tr("only for an organization key")))
.on_hover_text(tr("Needed only when the API key is not scoped to a workspace: the workspace's ID from the Console (Settings → Workspaces). Empty: ANTHROPIC_WORKSPACE_ID, if it is set."))
.changed();
ui.end_row();
}
let local = bigtext::ai::http::is_local(&c.url);
ui.label("");
ui.label(egui::RichText::new(if local {
tr("Local: nothing leaves this computer.")
} else {
tr("Cloud: short results are sent to this provider.")
}).weak());
ui.end_row();
ui.label(tr("Tool calling"));
changed |= ui.checkbox(&mut c.tools, tr("The model calls tools itself (several steps)")).on_hover_text(tr("Off: the model plans one step as JSON, which small local models manage more often")).changed();
ui.end_row();
if p.protocol == bigtext::ai::Protocol::Anthropic {
ui.label(tr("Thinking"));
ui.horizontal(|ui| {
for (e, label) in [(Effort::Low, tr("Fast")), (Effort::Medium, tr("Balanced")), (Effort::High, tr("Thorough"))] {
changed |= ui.radio_value(&mut cfg.effort, e, label).changed();
}
});
ui.end_row();
}
if c != cfg.conf(p.id).unwrap_or_else(|| ProviderConf::from_preset(p)) {
cfg.set_conf(c);
}
});
if self.ai.cfg.enabled() {
ui.horizontal(|ui| {
if ui.add_enabled(!self.ai.settings.busy_test, egui::Button::new(tr("Test connection"))).clicked() {
act = Some("test");
}
if self.ai.settings.busy_test || self.ai.settings.busy_models {
ui.spinner();
}
});
match &self.ai.settings.test {
Some(Ok(m)) => {
ui.label(egui::RichText::new(m).color(super::theme::ok_text(ui)));
}
Some(Err(e)) => {
ui.colored_label(ui.visuals().error_fg_color, e);
}
None => {}
}
}
if let keys::Kind::File(path) = &self.ai.store.kind {
ui.add_space(4.0);
ui.label(egui::RichText::new(trf("Portable copy: keys are kept encrypted in {file}.", &[("file", &path.display().to_string())])).weak());
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.ai.settings.passphrase).password(true).desired_width(160.0).hint_text(tr("passphrase")));
if ui.button(tr("Unlock")).on_hover_text(tr("Use this passphrase to read the key file")).clicked() {
act = Some("unlock");
}
if ui.button(tr("Set passphrase")).on_hover_text(tr("Encrypt the key file with this passphrase instead of a key file next to it (empty: go back to the key file)")).clicked() {
act = Some("passphrase");
}
});
}
ui.separator();
ui.heading(tr("How it works"));
let cfg = &mut self.ai.cfg;
ui.horizontal(|ui| {
ui.label(tr("Steps per question"));
changed |= ui.add(egui::Slider::new(&mut cfg.steps, 1..=STEPS_MAX)).on_hover_text(tr("1: the model plans one step; more: it can investigate (histogram, patterns, context…)")).changed();
});
changed |= ui.checkbox(&mut cfg.explain, tr("Explain the results (one more request)")).changed();
changed |= ui.checkbox(&mut cfg.auto_local, tr("Run steps that only read without asking (local provider)")).changed();
changed |= ui.checkbox(&mut cfg.auto_cloud, tr("Run steps that only read without asking (cloud provider)")).changed();
changed |= ui.checkbox(&mut cfg.writes, tr("Offer changes to the file (each one shown and confirmed first)")).changed();
ui.separator();
ui.heading(tr("Privacy"));
changed |= ui.checkbox(&mut cfg.privacy.redact, tr("Hide secrets in lines sent to a cloud provider (as Share safely does)")).changed();
ui.add_enabled_ui(cfg.privacy.redact || cfg.redact_local, |ui| {
changed |= ui.checkbox(&mut cfg.privacy.ips, tr("Hide IP addresses too")).changed();
});
changed |= ui.checkbox(&mut cfg.redact_local, tr("Hide secrets for a local provider too")).changed();
ui.horizontal(|ui| {
ui.label(tr("File text sent per question, at most"));
let mut kb = (cfg.privacy.limit / 1024) as u32;
if ui.add(egui::DragValue::new(&mut kb).range((privacy::LIMIT_MIN / 1024) as u32..=(privacy::LIMIT_MAX / 1024) as u32).suffix(" KB")).changed() {
cfg.privacy.limit = kb as usize * 1024;
changed = true;
}
});
ui.horizontal(|ui| {
changed |= ui.checkbox(&mut cfg.privacy.journal, tr("Keep a journal of what was sent, on this computer")).changed();
if let Some(p) = privacy::journal_path().filter(|p| p.exists()) {
if ui.small_button(tr("Open")).clicked() {
act = Some("journal");
let _ = p;
}
}
});
if !cfg.asked.is_empty() && ui.button(tr("Show what is sent before the first request again")).clicked() {
cfg.asked.clear();
changed = true;
}
});
});
if !open {
self.ai.settings.open = false;
}
if changed {
self.ai.settings.test = None;
self.ai.on_config_changed();
self.persist_state();
}
match act {
Some("models") => {
if let Some((mut p, store, typed)) = self.ai_worker_provider() {
let s = &mut self.ai.settings;
s.busy_models = true;
s.models_for = p.id.clone();
let (reports, waker) = (s.reports.clone(), self.waker.clone());
jobs::spawn("ai-models", move || {
p.key = if typed.is_empty() {
preset(&p.id).and_then(|pr| resolve_key(&store, pr).0)
} else {
Some(typed)
};
reports.lock().unwrap().models =
Some(p.models().map_err(|e| e.user_text()));
waker();
});
}
}
Some("test") => {
if let Some((mut p, store, typed)) = self.ai_worker_provider() {
let s = &mut self.ai.settings;
s.busy_test = true;
s.test = None;
let (reports, waker) = (s.reports.clone(), self.waker.clone());
jobs::spawn("ai-test", move || {
p.key = if typed.is_empty() {
preset(&p.id).and_then(|pr| resolve_key(&store, pr).0)
} else {
Some(typed)
};
reports.lock().unwrap().test = Some(test_provider(&p));
waker();
});
}
}
Some("save_key") => {
let key = std::mem::take(&mut self.ai.settings.key_input);
let id = self.ai.cfg.provider.clone();
let (store, reports, waker) = (
self.ai.store.clone(),
self.ai.settings.reports.clone(),
self.waker.clone(),
);
self.ai.provider = None;
jobs::spawn("ai-save-key", move || {
let msg = match store.set(&id, key.trim()) {
Ok(keys::Kind::Keychain) => tr("The key is stored in the system keychain.").to_string(),
Ok(keys::Kind::File(f)) => trf("The keychain could not be used; the key is stored in the encrypted file {file}.", &[("file", &f.display().to_string())]),
Err(e) => e.to_string(),
};
let status = preset(&id).map(|p| resolve_key(&store, p).1);
let mut r = reports.lock().unwrap();
r.key_msg = Some(msg);
r.key = status;
drop(r);
waker();
});
}
Some("delete_key") => {
let id = self.ai.cfg.provider.clone();
let (store, reports, waker) = (
self.ai.store.clone(),
self.ai.settings.reports.clone(),
self.waker.clone(),
);
self.ai.provider = None;
jobs::spawn("ai-delete-key", move || {
let msg = match store.delete(&id) {
Ok(()) => tr("The stored key is removed.").to_string(),
Err(e) => e.to_string(),
};
let status = preset(&id).map(|p| resolve_key(&store, p).1);
let mut r = reports.lock().unwrap();
r.key_msg = Some(msg);
r.key = status;
drop(r);
waker();
});
}
Some("unlock") => {
self.ai.store.passphrase =
Some(self.ai.settings.passphrase.clone()).filter(|p| !p.is_empty());
self.ai.provider = None;
self.ai_check_key();
}
Some("passphrase") => {
let pw = Some(self.ai.settings.passphrase.clone()).filter(|p| !p.is_empty());
let msg = match self.ai.store.set_passphrase(pw) {
Ok(()) => tr("The key file is encrypted again.").to_string(),
Err(e) => e.to_string(),
};
self.ai.settings.key_msg = Some(msg);
self.ai.provider = None;
}
Some("journal") => {
if let Some(p) = privacy::journal_path() {
self.open_path(p);
}
}
_ => {}
}
}
}