feat(app): start Strata from the data folder and point the brain at it

M5 step 4, second part. The services start the LLM first: the installed
Strata with the M0 kit's model and normal placement (models in
models/llm, parallel 1, or 2 when a chat channel answers every message,
pictures off, --restart), wait until /v1/models lists the model, and stop
it last. The first start downloads the model; the dashboard shows
Strata's last line and percentage, and stop also cancels a start (the
server is cleared). llm.url uses a server the app does not start.

On every start the app writes config/brain.json (Strata's /v1, the
listed model id, memory/jarvis.db) and hands it to the worker as
JARVIS_CONFIG_PATH. Loading a config with its own db_path no longer
creates ~/.local/share/jarvis.

service_start/service_restart run in the background. Settings gain
llm.context and llm.port (model screen) and llm.url (file only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-12 17:45:38 +09:00
parent 1a6d6447f6
commit 5c510bb602
16 changed files with 741 additions and 62 deletions

407
app/src/strata.rs Normal file
View File

@@ -0,0 +1,407 @@
//! The LLM the brain answers with (`app/src/admin.spec.md`, "LLM"): the app starts the installed
//! Strata from the data folder with the M0 kit's choices, waits until the model answers, and stops
//! it with the services. Strata downloads the model (about 23 GB) on its first start; the dashboard
//! shows how far it got. With `llm.url` the app uses that server instead and starts nothing.
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use serde::Serialize;
use serde_json::{json, Value};
use crate::install::{Ctx, Layout};
use crate::settings::Settings;
/// The one model v2 runs (M0: Qwen3.6-35B-A3B UD-Q4_K_XL; docs/v2/roadmap.md).
pub const FAMILY: &str = "qwen36";
pub const MODEL: &str = "ud-q4_k_xl";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum LlmState {
Off,
Starting,
Ready,
Failed,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LlmStatus {
pub state: LlmState,
/// Strata's own server (false: `llm.url`).
pub managed: bool,
/// The last percentage Strata printed while starting (the model download).
pub percent: Option<f64>,
/// Strata's last line while starting, or why it failed.
pub note: Option<String>,
}
/// Requests answered at once: one is faster on a 16 GB card (M0), two only when a chat channel
/// answers every message (so its answers do not wait behind the voice answers).
pub fn parallel(settings: &Settings) -> u32 {
if settings.chat_channels.iter().any(|c| c.answer_all) { 2 } else { 1 }
}
/// `strata launch` for the services: the M0 kit's normal placement, models in `models/llm`, this
/// computer only. No pictures yet (nothing in v2 sends one; reading them takes graphics memory).
/// `--restart` replaces a server started with other choices; the same choices are reused.
pub fn launch_args(layout: &Layout, settings: &Settings) -> Vec<String> {
let models = layout.data.join("models").join("llm").to_string_lossy().into_owned();
let mut a: Vec<String> = ["launch", "--family", FAMILY, "--model", MODEL, "--data-dir"].map(String::from).into();
a.push(models);
for (k, v) in [("--context", settings.llm.context.to_string()), ("--vision", "off".into()),
("--parallel", parallel(settings).to_string()), ("--access", "local".into()),
("--port", settings.llm.port.to_string())] {
a.push(k.into());
a.push(v);
}
a.extend(["--no-api-key", "--restart", "--yes", "--no-tui"].map(String::from));
a
}
/// The last `NN%` or `NN.N%` in a line.
pub fn percent(line: &str) -> Option<f64> {
let b = line.as_bytes();
let mut found = None;
for (i, _) in line.match_indices('%') {
let mut s = i;
while s > 0 && (b[s - 1].is_ascii_digit() || b[s - 1] == b'.') {
s -= 1;
}
if let Ok(n) = line[s..i].parse::<f64>() {
if (0.0..=100.0).contains(&n) {
found = Some(n);
}
}
}
found
}
/// Wait until `base` (`.../v1`) lists a model; returns its id. Stops early on `cancel`.
pub async fn wait_ready(base: &str, timeout: Duration, cancel: &AtomicBool) -> Result<String, String> {
let client = reqwest::Client::builder().timeout(Duration::from_secs(5)).build().map_err(|e| e.to_string())?;
let until = Instant::now() + timeout;
loop {
if cancel.load(Ordering::Relaxed) {
return Err("cancelled".into());
}
if let Ok(r) = client.get(format!("{base}/models")).send().await {
if let Ok(v) = r.text().await.map(|t| serde_json::from_str::<Value>(&t).unwrap_or_default()) {
if let Some(id) = v["data"][0]["id"].as_str() {
return Ok(id.to_owned());
}
}
}
if Instant::now() >= until {
return Err(format!("대화 모델이 {}초 안에 준비되지 않았습니다 ({base})", timeout.as_secs()));
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
/// The brain's settings (`config/brain.json`, the worker's `JARVIS_CONFIG_PATH`): the LLM and the
/// memory database inside the data folder. The app owns this file and writes it on every start.
pub fn write_brain_config(data: &Path, base_url: &str, model: &str) -> Result<std::path::PathBuf, String> {
let file = data.join("config").join("brain.json");
let cfg = json!({
"ollama_base_url": base_url,
"ollama_chat_model": model,
"db_path": data.join("memory").join("jarvis.db").to_string_lossy(),
"_config_version": 1,
});
let mut text = serde_json::to_string_pretty(&cfg).unwrap();
text.push('\n');
crate::datadir::write_atomic(&file, text.as_bytes()).map_err(|e| e.to_string())?;
Ok(file)
}
/// One LLM for the services: Strata from the layout, or the server at `llm.url`.
pub struct Llm {
layout: Layout,
/// The program run as Strata (the installed one; a script in tests).
exe: std::path::PathBuf,
status: Mutex<LlmStatus>,
active: Mutex<Option<Arc<Ctx>>>,
cancel: Arc<AtomicBool>,
}
/// How long the model may take to answer after `strata launch` returned (it loads in about 15 s
/// on the game PC; the first start may also tune).
const READY_TIMEOUT: Duration = Duration::from_secs(30 * 60);
/// A server the app does not start must already answer.
const URL_TIMEOUT: Duration = Duration::from_secs(30);
impl Llm {
pub fn new(data: &Path) -> Self {
// Only the data folder matters here (the Python sources are the install's business).
let layout = Layout { data: data.to_path_buf(), src: std::path::PathBuf::new() };
let exe = layout.strata_exe();
Self::with_exe(layout, exe)
}
pub fn with_exe(layout: Layout, exe: std::path::PathBuf) -> Self {
Self { layout, exe, status: Mutex::new(LlmStatus { state: LlmState::Off, managed: false, percent: None, note: None }),
active: Mutex::new(None), cancel: Arc::new(AtomicBool::new(false)) }
}
pub fn status(&self) -> LlmStatus {
let mut s = self.status.lock().unwrap().clone();
if let Some(ctx) = self.active.lock().unwrap().as_ref() {
s.note = ctx.last_note();
if let Some(p) = s.note.as_deref().and_then(percent) {
// Kept in the status, so the bar does not vanish on a line without one.
self.status.lock().unwrap().percent = Some(p);
}
s.percent = self.status.lock().unwrap().percent;
}
s
}
fn set(&self, state: LlmState, note: Option<String>) {
let mut s = self.status.lock().unwrap();
s.state = state;
if state != LlmState::Starting {
s.note = note;
}
}
/// Start (or reuse) the LLM; returns its `/v1` address and model id.
pub async fn start(&self, settings: &Settings) -> Result<(String, String), String> {
self.cancel.store(false, Ordering::SeqCst);
let managed = settings.llm.url.is_none();
*self.status.lock().unwrap() = LlmStatus { state: LlmState::Starting, managed, percent: None, note: None };
let result = self.start_inner(settings).await;
match &result {
Ok((base, model)) => {
crate::info_log!("llm", "ready: {base} model={model}");
self.set(LlmState::Ready, None);
}
Err(e) if e == "cancelled" => self.set(LlmState::Off, None),
Err(e) => {
crate::error_log!("llm", "did not start: {e}");
self.set(LlmState::Failed, Some(e.clone()));
}
}
result
}
async fn start_inner(&self, settings: &Settings) -> Result<(String, String), String> {
if let Some(url) = &settings.llm.url {
let model = wait_ready(url, URL_TIMEOUT, &self.cancel).await?;
return Ok((url.clone(), model));
}
if !self.exe.exists() {
return Err("Strata가 설치되어 있지 않습니다. 마법사의 모델 단계에서 설치해 주세요".into());
}
let ctx = Arc::new(Ctx::standalone(self.layout.clone(), "llm", self.cancel.clone()));
*self.active.lock().unwrap() = Some(ctx.clone());
let args = launch_args(&self.layout, settings);
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
let home = self.layout.strata_home();
let ran = ctx.run_in(&self.exe, &refs, Some(&home)).await;
let base = format!("http://127.0.0.1:{}/v1", settings.llm.port);
let ready = match ran {
Ok(()) => wait_ready(&base, READY_TIMEOUT, &self.cancel).await,
Err(e) => Err(e),
};
*self.active.lock().unwrap() = None;
if ready.is_err() {
// Nothing half-started stays on the graphics card.
self.stop_server().await;
}
Ok((base, ready?))
}
/// Stop a start in progress (the download resumes on the next start).
pub fn cancel(&self) {
self.cancel.store(true, Ordering::SeqCst);
}
/// Stop the server this app started (nothing for `llm.url`).
pub async fn stop(&self) {
let managed = self.status.lock().unwrap().managed;
if managed {
self.stop_server().await;
}
self.set(LlmState::Off, None);
}
async fn stop_server(&self) {
if !self.exe.exists() {
return;
}
let ctx = Ctx::standalone(self.layout.clone(), "llm", Arc::new(AtomicBool::new(false)));
let home = self.layout.strata_home();
let stop = ctx.run_in(&self.exe, &["launch", "--stop"], Some(&home));
match tokio::time::timeout(Duration::from_secs(120), stop).await {
Ok(Ok(())) => { crate::info_log!("llm", "stopped"); }
Ok(Err(e)) => { crate::warn_log!("llm", "stop failed: {e}"); }
Err(_) => { crate::warn_log!("llm", "stop timed out"); }
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::datadir::temp_dir;
use crate::settings::{parse_settings, ChatChannelSettings};
fn layout(tag: &str) -> Layout {
Layout { data: temp_dir(tag), src: std::path::PathBuf::from("src") }
}
#[test]
fn the_launch_keeps_the_model_in_the_data_folder_and_follows_the_settings() {
let l = layout("llm1");
let s = parse_settings(&json!({"llm": {"context": 16384, "port": 8099}})).unwrap();
let a = launch_args(&l, &s);
let after = |k: &str| a[a.iter().position(|x| x == k).unwrap() + 1].clone();
assert!(Path::new(&after("--data-dir")).starts_with(&l.data));
assert_eq!((after("--context"), after("--port"), after("--parallel")), ("16384".into(), "8099".into(), "1".into()));
assert_eq!(after("--access"), "local");
assert!(a.iter().any(|x| x == "--no-tui") && a.iter().any(|x| x == "--yes"));
}
#[test]
fn a_chat_channel_answering_everything_gets_a_second_request_slot() {
let mut s = Settings::default();
assert_eq!(parallel(&s), 1);
s.chat_channels.push(ChatChannelSettings { id: 1, name: String::new(), description: String::new(), read: true,
send: true, edit: true, react: true, delete: false, pin: false, answer_all: true });
assert_eq!(parallel(&s), 2);
}
#[test]
fn the_progress_is_the_last_percentage_on_a_line() {
assert_eq!(percent("Downloading 3 of 5: 41.5% (9.6 GB of 23.1 GB)"), Some(41.5));
assert_eq!(percent("50% done, now 75%"), Some(75.0));
assert_eq!(percent("Loading the model… 15 s"), None);
}
#[test]
fn the_brain_config_points_at_the_llm_and_keeps_memory_in_the_data_folder() {
let l = layout("llm2");
let f = write_brain_config(&l.data, "http://127.0.0.1:8080/v1", "m").unwrap();
let v: Value = serde_json::from_str(&std::fs::read_to_string(f).unwrap()).unwrap();
assert_eq!(v["ollama_base_url"], "http://127.0.0.1:8080/v1");
assert_eq!(v["ollama_chat_model"], "m");
assert!(Path::new(v["db_path"].as_str().unwrap()).starts_with(&l.data));
}
/// A tiny `/v1/models` server answering with `id`, after `delay`.
async fn models_server(id: &'static str, delay: Duration) -> u16 {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let opened = Instant::now();
tokio::spawn(async move {
while let Ok((mut s, _)) = listener.accept().await {
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf).await;
let body = if opened.elapsed() >= delay { format!(r#"{{"data":[{{"id":"{id}"}}]}}"#) } else { "{}".into() };
let _ = s.write_all(format!("HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()).as_bytes()).await;
}
});
port
}
#[tokio::test]
async fn a_given_server_is_used_without_starting_strata() {
let port = models_server("given-model", Duration::ZERO).await;
let l = layout("llm3");
let llm = Llm::new(&l.data);
let s = parse_settings(&json!({"llm": {"url": format!("http://127.0.0.1:{port}/v1")}})).unwrap();
let (base, model) = llm.start(&s).await.unwrap();
assert_eq!((base.as_str(), model.as_str()), (format!("http://127.0.0.1:{port}/v1").as_str(), "given-model"));
assert_eq!(llm.status().state, LlmState::Ready);
assert!(!llm.status().managed);
}
#[tokio::test]
async fn without_strata_installed_the_start_fails_with_a_reason() {
let llm = Llm::new(&layout("llm4").data);
let e = llm.start(&Settings::default()).await.unwrap_err();
assert!(e.contains("Strata"), "{e}");
assert_eq!(llm.status().state, LlmState::Failed);
assert_eq!(llm.status().note.as_deref(), Some(e.as_str()));
}
/// A fake `strata`: `launch --stop` records itself; `launch ...` prints progress and returns.
#[cfg(unix)]
fn fake_strata(l: &Layout, launch_body: &str) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let exe = l.data.join("fake-strata");
std::fs::create_dir_all(l.strata_home()).unwrap();
let log = l.data.join("calls");
std::fs::write(&exe, format!("#!/bin/sh\necho \"$@\" >> '{}'\nif [ \"$2\" = --stop ]; then exit 0; fi\n{launch_body}\n",
log.display())).unwrap();
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
exe
}
#[cfg(unix)]
#[tokio::test]
async fn strata_starts_reports_its_download_waits_for_the_model_and_stops() {
let port = models_server("qwen-test", Duration::from_millis(300)).await;
let l = layout("llm5");
let exe = fake_strata(&l, "echo 'Downloading: 12.5%'; sleep 1; echo 'Downloading: 100%'; echo 'Strata is serving.'");
let llm = Arc::new(Llm::with_exe(l.clone(), exe));
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
let l2 = llm.clone();
let s2 = s.clone();
let run = tokio::spawn(async move { l2.start(&s2).await });
let mut seen = None;
for _ in 0..40 {
tokio::time::sleep(Duration::from_millis(50)).await;
let st = llm.status();
if st.percent.is_some() {
seen = Some(st);
break;
}
}
let st = seen.expect("progress while starting");
assert_eq!((st.state, st.percent), (LlmState::Starting, Some(12.5)));
let (base, model) = run.await.unwrap().unwrap();
assert_eq!((base, model.as_str()), (format!("http://127.0.0.1:{port}/v1"), "qwen-test"));
assert_eq!(llm.status().state, LlmState::Ready);
llm.stop().await;
let calls = std::fs::read_to_string(l.data.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().starts_with("launch --family"), "{calls}");
assert_eq!(calls.lines().last(), Some("launch --stop"));
assert_eq!(llm.status().state, LlmState::Off);
}
#[cfg(unix)]
#[tokio::test]
async fn a_cancel_during_the_download_stops_it_and_clears_the_server() {
let l = layout("llm6");
let exe = fake_strata(&l, "echo 'Downloading: 1%'; sleep 30");
let llm = Arc::new(Llm::with_exe(l.clone(), exe));
let l2 = llm.clone();
let run = tokio::spawn(async move { l2.start(&Settings::default()).await });
tokio::time::sleep(Duration::from_millis(400)).await;
let t = Instant::now();
llm.cancel();
assert_eq!(run.await.unwrap().unwrap_err(), "cancelled");
assert!(t.elapsed() < Duration::from_secs(5));
assert_eq!(llm.status().state, LlmState::Off);
let calls = std::fs::read_to_string(l.data.join("calls")).unwrap();
assert_eq!(calls.lines().last(), Some("launch --stop"));
}
#[cfg(unix)]
#[tokio::test]
async fn a_failed_launch_shows_strata_s_last_line() {
let l = layout("llm7");
let exe = fake_strata(&l, "echo 'Not enough disk space for the model' >&2; exit 4");
let llm = Llm::with_exe(l, exe);
let e = llm.start(&Settings::default()).await.unwrap_err();
assert!(e.contains("Not enough disk space"), "{e}");
assert_eq!(llm.status().state, LlmState::Failed);
}
}