bigtext 0.19.1

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! AI → AI settings: the provider, its address, model and key, how the assistant works and what
//! it may send. The choices are kept in the settings file as `ai_*` lines; keys go to the
//! system keychain (or the encrypted key file), never there.

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;

/// What a worker reports back to the settings window.
#[derive(Default)]
struct Reports {
    key: Option<KeyStatus>,
    key_msg: Option<String>,
    models: Option<Result<Vec<String>, String>>,
    test: Option<Result<String, String>>,
}

/// The settings window's state.
#[derive(Default)]
pub struct SettingsUi {
    pub open: bool,
    key_input: String,
    passphrase: String,
    /// The provider the key status is about.
    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>>,
}

/// Tries the provider: a plain request, then one with a tool to call.
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();
    }

    /// Looks up where the active provider's key is, on a worker (a keychain may ask the user).
    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);
        }
    }

    /// The provider with its key, for a worker: the typed key when there is one.
    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);
                }
            }
            _ => {}
        }
    }
}