capri-memory: add ui module
This commit is contained in:
1 file changed
+360
@@ -0,0 +1,360 @@
|
||||
//! Plain egui pages for memory settings: saved memory, Brain and private memory.
|
||||
//! Slow work runs on the Tokio runtime; results land in `UiState` and trigger a repaint.
|
||||
use std::sync::Arc;
|
||||
|
||||
use capri_core::SettingsStore;
|
||||
|
||||
use crate::brain::BrainRow;
|
||||
use crate::private::PrivateNote;
|
||||
use crate::saved::{matches, SavedMemory};
|
||||
use crate::{MemoryHandle, MemoryService, MemorySettings};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct UiState {
|
||||
saved: Option<SavedMemory>,
|
||||
saved_search: String,
|
||||
new_memory: String,
|
||||
saved_status: String,
|
||||
confirm_clear: bool,
|
||||
clear_status: String,
|
||||
brain_query: String,
|
||||
brain_results: Option<Vec<BrainRow>>,
|
||||
brain_message: String,
|
||||
add_document: String,
|
||||
password: String,
|
||||
new_password: String,
|
||||
private_note: String,
|
||||
private_message: String,
|
||||
private_reply: String,
|
||||
private_status: String,
|
||||
private_notes: Vec<PrivateNote>,
|
||||
private_busy: bool,
|
||||
}
|
||||
|
||||
impl UiState {
|
||||
pub(crate) fn wipe_private(&mut self) {
|
||||
for field in [&mut self.password, &mut self.new_password, &mut self.private_note, &mut self.private_message, &mut self.private_reply, &mut self.private_status] {
|
||||
field.clear();
|
||||
}
|
||||
self.private_notes.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `work` in the background, then applies its result to the UI state and repaints.
|
||||
fn spawn<T: Send + 'static>(ui: &egui::Ui, memory: &MemoryHandle, work: impl FnOnce(&MemoryService) -> T + Send + 'static, apply: impl FnOnce(&mut UiState, T) + Send + 'static) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let memory = memory.clone();
|
||||
memory.runtime.clone().spawn_blocking(move || {
|
||||
let result = work(&memory);
|
||||
apply(&mut memory.ui.lock(), result);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
}
|
||||
|
||||
pub fn settings_ui(ui: &mut egui::Ui, store: &SettingsStore, memory: &MemoryHandle) {
|
||||
let mut settings: MemorySettings = store.section();
|
||||
let before = settings.clone();
|
||||
ui.heading("Memory");
|
||||
ui.checkbox(&mut settings.remember_across_conversations, "Remember across conversations");
|
||||
saved_memory(ui, memory);
|
||||
ui.separator();
|
||||
ui.heading("Brain");
|
||||
ui.checkbox(&mut settings.brain_enabled, "Use local knowledge");
|
||||
ui.checkbox(&mut settings.brain_share_with_api, "Allow relevant Brain excerpts to be sent to an external API");
|
||||
brain(ui, memory, settings.brain_enabled);
|
||||
ui.separator();
|
||||
ui.heading("Private memory");
|
||||
private_memory(ui, store, memory);
|
||||
if settings != before {
|
||||
if let Err(e) = store.set_section(&settings) {
|
||||
memory.ui.lock().clear_status = format!("{e:#}");
|
||||
}
|
||||
if settings.remember_across_conversations != before.remember_across_conversations {
|
||||
memory.request_sync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn saved_memory(ui: &mut egui::Ui, memory: &MemoryHandle) {
|
||||
let mut state = memory.ui.lock();
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("View saved memories").clicked() || state.saved.is_none() {
|
||||
state.saved = Some(memory.saved_memory());
|
||||
}
|
||||
if ui.button("Refresh").clicked() {
|
||||
state.saved = Some(memory.saved_memory());
|
||||
}
|
||||
});
|
||||
ui.label("Add a memory");
|
||||
ui.add(egui::TextEdit::multiline(&mut state.new_memory).char_limit(1200).hint_text("A fact you want Capri to remember…"));
|
||||
if ui.button("Save fact").clicked() && !state.new_memory.trim().is_empty() {
|
||||
let text = state.new_memory.trim().to_string();
|
||||
state.saved_status = match memory.save_note(&text) {
|
||||
Ok(_) => {
|
||||
state.new_memory.clear();
|
||||
state.saved = Some(memory.saved_memory());
|
||||
"Memory saved and verified.".into()
|
||||
}
|
||||
Err(_) => "The memory could not be verified.".into(),
|
||||
};
|
||||
}
|
||||
if !state.saved_status.is_empty() {
|
||||
ui.label(state.saved_status.clone());
|
||||
}
|
||||
ui.add(egui::TextEdit::singleline(&mut state.saved_search).char_limit(200).hint_text("Search"));
|
||||
if let Some(saved) = &state.saved {
|
||||
let shown: Vec<_> = saved.items.iter().filter(|i| matches(i, &state.saved_search)).collect();
|
||||
let status = if saved.unavailable && saved.items.is_empty() {
|
||||
"Memory files are unavailable.".to_string()
|
||||
} else if saved.items.is_empty() {
|
||||
"No saved memories yet.".to_string()
|
||||
} else if shown.is_empty() {
|
||||
"No matching memories.".to_string()
|
||||
} else if shown.len() != saved.items.len() {
|
||||
format!("{} of {} memories", shown.len(), saved.items.len())
|
||||
} else {
|
||||
format!("{} saved memories", saved.items.len())
|
||||
};
|
||||
ui.label(status);
|
||||
if saved.truncated {
|
||||
ui.label("Showing a limited list. Some notes could not be displayed.");
|
||||
}
|
||||
egui::ScrollArea::vertical().id_salt("saved-memory").max_height(240.0).show(ui, |ui| {
|
||||
for item in shown {
|
||||
ui.group(|ui| {
|
||||
ui.label(&item.text);
|
||||
ui.small(match &item.date {
|
||||
Some(d) => format!("{} · {d}", item.source),
|
||||
None => item.source.clone(),
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
if !state.confirm_clear {
|
||||
if ui.button("Clear long-term memory").clicked() {
|
||||
state.confirm_clear = true;
|
||||
}
|
||||
} else {
|
||||
ui.label("Delete saved notes about you? USER.md, MEMORY.md and notes in memory will be cleared. Conversation archives remain separate. This cannot be undone.");
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Clear").clicked() {
|
||||
state.clear_status = match memory.clear_long_term_memory() {
|
||||
Ok(()) => String::new(),
|
||||
Err(e) => format!("{e:#}"),
|
||||
};
|
||||
state.saved = Some(memory.saved_memory());
|
||||
state.confirm_clear = false;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
state.confirm_clear = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
if !state.clear_status.is_empty() {
|
||||
ui.label(state.clear_status.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn brain(ui: &mut egui::Ui, memory: &MemoryHandle, enabled: bool) {
|
||||
let status = memory.brain.status();
|
||||
ui.label(if status.busy { "Indexing documents…".to_string() } else { format!("Documents indexed: {} · Skipped: {}", status.indexed, status.skipped) });
|
||||
let folder = memory.brain.folder.clone();
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Open Brain folder").clicked() {
|
||||
let _ = std::process::Command::new("xdg-open").arg(&folder).spawn();
|
||||
}
|
||||
if ui.add_enabled(enabled && !status.busy, egui::Button::new("Refresh index")).clicked() {
|
||||
spawn(ui, memory, |m| m.brain.refresh().map(|_| ()), |s, r: anyhow::Result<()>| s.brain_message = r.err().map(|e| format!("{e:#}")).unwrap_or_default());
|
||||
}
|
||||
});
|
||||
let mut state = memory.ui.lock();
|
||||
let mut documents: Vec<String> = std::fs::read_dir(&folder).into_iter().flatten().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
|
||||
documents.sort();
|
||||
for name in documents {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(&name);
|
||||
if ui.small_button("Remove").clicked() {
|
||||
state.brain_message = match std::fs::remove_file(folder.join(&name)) {
|
||||
Ok(()) => String::new(),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut state.add_document).hint_text("Path of a .txt, .md, .pdf, .docx or .odt file"));
|
||||
if ui.button("Add document").clicked() {
|
||||
let source = std::path::PathBuf::from(state.add_document.trim());
|
||||
state.brain_message = match source.file_name() {
|
||||
Some(name) if source.is_file() => match std::fs::copy(&source, folder.join(name)) {
|
||||
Ok(_) => {
|
||||
state.add_document.clear();
|
||||
String::new()
|
||||
}
|
||||
Err(e) => e.to_string(),
|
||||
},
|
||||
_ => "Choose an existing document file.".into(),
|
||||
};
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut state.brain_query).char_limit(500).hint_text("Test search"));
|
||||
if ui.button("Search").clicked() {
|
||||
state.brain_results = Some(if enabled { memory.brain.search(&state.brain_query) } else { vec![] });
|
||||
}
|
||||
});
|
||||
if let Some(rows) = &state.brain_results {
|
||||
if rows.is_empty() {
|
||||
ui.label("No matching knowledge found.");
|
||||
}
|
||||
for row in rows {
|
||||
ui.group(|ui| {
|
||||
ui.small(format!("{} · {}", row.source, row.page));
|
||||
ui.label(&row.content);
|
||||
});
|
||||
}
|
||||
}
|
||||
if !state.brain_message.is_empty() {
|
||||
ui.label(state.brain_message.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn private_memory(ui: &mut egui::Ui, store: &SettingsStore, memory: &MemoryHandle) {
|
||||
let status = memory.vault.status();
|
||||
let mut state = memory.ui.lock();
|
||||
ui.label(if status.unlocked { "Private memory is unlocked. It locks after five minutes of inactivity." } else { "Private memory is locked." });
|
||||
if !status.unlocked {
|
||||
state.private_notes.clear();
|
||||
ui.add(egui::TextEdit::singleline(&mut state.password).password(true).char_limit(256).hint_text("Password"));
|
||||
let label = if status.exists { "Unlock" } else { "Create private memory" };
|
||||
if ui.add_enabled(!state.private_busy, egui::Button::new(label)).clicked() {
|
||||
let password = std::mem::take(&mut state.password);
|
||||
let create = !status.exists;
|
||||
state.private_busy = true;
|
||||
spawn(ui, memory, move |m| m.vault.unlock(&password, create).and_then(|_| m.vault.list()), |s, r| {
|
||||
s.private_busy = false;
|
||||
match r {
|
||||
Ok(notes) => {
|
||||
s.private_notes = notes;
|
||||
s.private_status.clear();
|
||||
}
|
||||
Err(e) => s.private_status = e.to_string(),
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if state.private_notes.is_empty() {
|
||||
state.private_notes = memory.vault.list().unwrap_or_default();
|
||||
}
|
||||
if ui.button("Lock now").clicked() {
|
||||
memory.vault.lock();
|
||||
state.wipe_private();
|
||||
return;
|
||||
}
|
||||
ui.add(egui::TextEdit::multiline(&mut state.private_note).char_limit(1200).hint_text("Private note"));
|
||||
if ui.button("Save").clicked() {
|
||||
match memory.vault.add(&state.private_note) {
|
||||
Ok(notes) => {
|
||||
state.private_notes = notes;
|
||||
state.private_note.clear();
|
||||
}
|
||||
Err(e) => state.private_status = e.to_string(),
|
||||
}
|
||||
}
|
||||
let mut removed = None;
|
||||
for note in &state.private_notes {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(¬e.text);
|
||||
if ui.small_button("Remove").clicked() {
|
||||
removed = Some(note.id.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(id) = removed {
|
||||
match memory.vault.remove(&id) {
|
||||
Ok(notes) => state.private_notes = notes,
|
||||
Err(e) => state.private_status = e.to_string(),
|
||||
}
|
||||
}
|
||||
ui.add(egui::TextEdit::multiline(&mut state.private_message).char_limit(2000).hint_text("Private message"));
|
||||
if ui.add_enabled(!state.private_busy, egui::Button::new("Send privately")).clicked() {
|
||||
let text = state.private_message.clone();
|
||||
let settings = store.get();
|
||||
let mut options = serde_json::json!({"num_ctx": settings.context_tokens});
|
||||
if settings.acceleration == "cpu" {
|
||||
options["num_gpu"] = 0.into();
|
||||
}
|
||||
if let Some(t) = settings.cpu_threads {
|
||||
options["num_thread"] = t.into();
|
||||
}
|
||||
state.private_busy = true;
|
||||
state.private_reply = "Thinking".into();
|
||||
let (ctx, memory2) = (ui.ctx().clone(), Arc::clone(memory));
|
||||
memory.runtime.spawn(async move {
|
||||
let vault = memory2.vault.clone();
|
||||
let message = text.clone();
|
||||
let reply = vault
|
||||
.chat(&text, |notes, history| async move {
|
||||
crate::private::private_reply(&settings.ollama_base_url(), &settings.model, options, &message, ¬es, &history).await
|
||||
})
|
||||
.await;
|
||||
let mut s = memory2.ui.lock();
|
||||
s.private_busy = false;
|
||||
match reply {
|
||||
Ok(answer) => {
|
||||
s.private_reply = answer;
|
||||
s.private_message.clear();
|
||||
}
|
||||
Err(e) => {
|
||||
s.private_reply.clear();
|
||||
s.private_status = e.to_string();
|
||||
}
|
||||
}
|
||||
ctx.request_repaint();
|
||||
});
|
||||
}
|
||||
if !state.private_reply.is_empty() {
|
||||
ui.label(state.private_reply.clone());
|
||||
}
|
||||
ui.collapsing("Change password", |ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut state.password).password(true).hint_text("Current password"));
|
||||
ui.add(egui::TextEdit::singleline(&mut state.new_password).password(true).hint_text("New password"));
|
||||
if ui.add_enabled(!state.private_busy, egui::Button::new("Change password")).clicked() {
|
||||
let (old, new) = (std::mem::take(&mut state.password), std::mem::take(&mut state.new_password));
|
||||
state.private_busy = true;
|
||||
spawn(ui, memory, move |m| m.vault.change_password(&old, &new).map(|_| ()), |s, r| {
|
||||
s.private_busy = false;
|
||||
s.private_status = r.err().map(|e| e.to_string()).unwrap_or_default();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
if !state.private_status.is_empty() {
|
||||
ui.label(state.private_status.clone());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use capri_core::{Paths, Settings};
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn pages_render_headless() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let paths = Paths::under(dir.path().to_path_buf());
|
||||
paths.ensure().unwrap();
|
||||
let store = SettingsStore::new(paths, Settings { ollama_url: Some("http://127.0.0.1:9".into()), ..Default::default() });
|
||||
let memory = MemoryService::start(store.clone()).unwrap();
|
||||
memory.save_note("my test color is teal").unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
egui::ScrollArea::vertical().show(ui, |ui| settings_ui(ui, &store, &memory));
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
assert_eq!(memory.ui.lock().saved.as_ref().unwrap().items.len(), 1);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user