feat: persist LLM/TTS backend choice + reset/repeat context + quick-search + diagnostics

Closes the UX hole I created in 5c72450: voice-swap to Ollama used to vanish
after restart. Plus P0.3 (long-standing roadmap item) and two new packs.

Persistent backend choice (crates/jarvis-core/src/db/structs.rs)
  - Settings struct gains llm_backend + tts_backend fields (both String,
    "" / "auto" = follow env/auto-detect).
  - set("llm_backend", "groq"|"ollama"|"auto") validates input.
  - llm::init_global() reads DB first, then JARVIS_LLM env, then auto-detect.
  - llm::swap_to() now persists the choice via db::save_settings.
  - Voice swap "переключись на локальный" now survives restart.

Shared conversation history (P0.3, crates/jarvis-core/src/llm/mod.rs)
  - HISTORY: Lazy<RwLock<Option<ConversationHistory>>> singleton.
  - Helpers: init_history, history_push_user, history_push_assistant,
    history_snapshot, history_clear, history_pop_last_user, history_last_assistant.
  - llm_fallback migrated off its own Mutex<History> — now reads/writes shared.
  - ConversationHistory gains last_assistant() method.

New Lua APIs
  - jarvis.llm_reset()        → clear conversation turns (keeps system prompt).
  - jarvis.llm_last_reply()   → string or nil (last assistant message text).
  - jarvis.health()           → debug table {tts_backend, llm_backend, llm_model,
                                  active_profile, memory_facts, scheduled_tasks,
                                  language, voice, microphone, vosk_model,
                                  noise_suppression}. No secrets included.

New voice packs
  - resources/commands/llm_context/   (P0.3)
    * "сбрось контекст" / "забудь разговор"     → llm.reset
    * "повтори последнее" / "повтори ответ"     → llm.repeat (uses last_assistant)
  - resources/commands/quick_search/   (imba P1 item)
    * "найди в гугле <X>" / "загугли <X>"
    * Uses DuckDuckGo Instant Answer API (api.duckduckgo.com, no key required).
      Pulls AbstractText or RelatedTopics into LLM prompt; falls back to pure
      LLM knowledge if DDG returns nothing useful. Speaks 2-4 sentence answer.
  - resources/commands/diagnostics/
    * "диагностика" / "доложи о себе" / "статус"
    * Reads jarvis.health() and speaks a one-line summary. Useful when
      debugging — user can read out their current state for a bug report.

Build: cargo build --release -p jarvis-app -p jarvis-gui green.
Tests: 52/52 jarvis-core unit tests pass.
This commit is contained in:
Bossiara13 2026-05-15 16:25:28 +03:00
parent 5c7245012e
commit 385bd5c8ce
15 changed files with 413 additions and 37 deletions

View file

@ -1,20 +1,19 @@
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use jarvis_core::config;
use jarvis_core::i18n;
use jarvis_core::ipc::{self, IpcEvent};
use jarvis_core::llm::{self, ChatMessage, ConversationHistory};
use jarvis_core::llm::{self, ChatMessage};
use jarvis_core::long_term_memory;
use jarvis_core::profiles;
use jarvis_core::tts::{self, SpeakOpts};
use jarvis_core::voices;
// State now only holds conversation history — the actual LLM client lives in
// `jarvis_core::llm::GLOBAL` so that voice/Lua commands can hot-swap backends
// (Ollama ↔ Groq) without rebuilding this module's state.
// State now only holds the max_tokens config — both the LLM client AND the
// conversation history live in `jarvis_core::llm::*` globals. This lets voice
// commands ("сбрось контекст", "повтори последнее") and Lua scripts share the
// same buffer instead of each module owning its own.
struct State {
history: Mutex<ConversationHistory>,
max_tokens: u32,
}
@ -38,11 +37,10 @@ fn build_state() -> Option<State> {
let lang = i18n::get_language();
let prompt = config::get_llm_system_prompt(&lang);
let history = Mutex::new(ConversationHistory::new(prompt, config::LLM_DEFAULT_MAX_HISTORY));
llm::init_history(prompt, config::LLM_DEFAULT_MAX_HISTORY);
info!("LLM fallback enabled (backend: {}).", llm::current_backend_name());
Some(State {
history,
max_tokens: config::LLM_DEFAULT_MAX_TOKENS,
})
}
@ -89,31 +87,26 @@ pub fn handle(prompt: &str) {
info!("LLM prompt: {}", prompt);
let snapshot: Vec<ChatMessage> = {
let mut h = state.history.lock();
h.push_user(prompt);
let mut snap = h.snapshot();
llm::history_push_user(prompt);
let mut snapshot: Vec<ChatMessage> = llm::history_snapshot();
// Inject (a) profile personality (b) relevant long-term memory as a fresh
// system message right after the base prompt. Both are optional.
let profile = profiles::active();
let mut overlay = String::new();
if !profile.llm_personality.is_empty() {
overlay.push_str(&format!("Активный профиль: {} {}\nХарактер для ответа: {}\n",
profile.icon, profile.name, profile.llm_personality));
}
let mem_ctx = long_term_memory::build_context(prompt, 5);
if !mem_ctx.is_empty() {
overlay.push_str(&mem_ctx);
}
if !overlay.is_empty() {
// Insert after the base system prompt (index 0 typically), before user msgs.
let insert_at = if !snap.is_empty() && snap[0].role == "system" { 1 } else { 0 };
snap.insert(insert_at, ChatMessage::system(overlay));
}
snap
};
// Inject (a) profile personality (b) relevant long-term memory as a fresh
// system message right after the base prompt. Both are optional.
let profile = profiles::active();
let mut overlay = String::new();
if !profile.llm_personality.is_empty() {
overlay.push_str(&format!("Активный профиль: {} {}\nХарактер для ответа: {}\n",
profile.icon, profile.name, profile.llm_personality));
}
let mem_ctx = long_term_memory::build_context(prompt, 5);
if !mem_ctx.is_empty() {
overlay.push_str(&mem_ctx);
}
if !overlay.is_empty() {
// Insert after the base system prompt (index 0 typically), before user msgs.
let insert_at = if !snapshot.is_empty() && snapshot[0].role == "system" { 1 } else { 0 };
snapshot.insert(insert_at, ChatMessage::system(overlay));
}
let client = match llm::current() {
Some(c) => c,
@ -127,14 +120,14 @@ pub fn handle(prompt: &str) {
Ok(reply) => {
let reply = reply.trim().to_string();
info!("LLM reply: {}", reply);
state.history.lock().push_assistant(reply.clone());
llm::history_push_assistant(reply.clone());
ipc::send(IpcEvent::LlmReply { text: reply.clone() });
voices::play_ok();
speak_reply(&reply);
}
Err(e) => {
error!("LLM request failed: {}", e);
state.history.lock().pop_last_user();
llm::history_pop_last_user();
let err_text = config::LLM_FALLBACK_ERROR_RU.to_string();
ipc::send(IpcEvent::LlmReply { text: err_text.clone() });
voices::play_error();