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:
@@ -37,6 +37,13 @@ pub trait Host: Send + Sync + 'static {
|
||||
async fn start(&self) -> Result<(Arc<dyn Running>, mpsc::UnboundedReceiver<CoreEvent>), String>;
|
||||
/// Stored secrets, masked in error messages.
|
||||
fn secrets(&self) -> Vec<String>;
|
||||
/// Stop a start in progress (the LLM's first start downloads the model); `start` then returns
|
||||
/// `Err("cancelled")` if it had not finished.
|
||||
fn cancel_start(&self) {}
|
||||
/// The LLM's state for the dashboard, also while starting.
|
||||
fn llm(&self) -> Value {
|
||||
Value::Null
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
@@ -47,6 +54,8 @@ struct Inner {
|
||||
/// one, so an event of an earlier run can never reach a later dashboard.
|
||||
dashboard: Arc<Mutex<Dashboard>>,
|
||||
feeder: Option<tokio::task::JoinHandle<()>>,
|
||||
/// Stop was asked for while starting.
|
||||
stop_asked: bool,
|
||||
}
|
||||
|
||||
pub struct Controller {
|
||||
@@ -58,7 +67,7 @@ pub struct Controller {
|
||||
impl Controller {
|
||||
pub fn new(host: impl Host) -> Arc<Self> {
|
||||
Arc::new(Self { host: Box::new(host), inner: Mutex::new(Inner { state: State::Stopped, error: None, running: None,
|
||||
dashboard: Arc::default(), feeder: None }), usage: tokio::sync::Mutex::new(None) })
|
||||
dashboard: Arc::default(), feeder: None, stop_asked: false }), usage: tokio::sync::Mutex::new(None) })
|
||||
}
|
||||
|
||||
pub fn state(&self) -> State {
|
||||
@@ -74,39 +83,62 @@ impl Controller {
|
||||
}
|
||||
i.state = State::Starting;
|
||||
i.error = None;
|
||||
i.stop_asked = false;
|
||||
}
|
||||
crate::info_log!("app", "starting the services");
|
||||
match self.host.start().await {
|
||||
Ok((running, mut events)) => {
|
||||
let dash: Arc<Mutex<Dashboard>> = Arc::default();
|
||||
let d2 = dash.clone();
|
||||
let feeder = tokio::spawn(async move {
|
||||
while let Some(ev) = events.recv().await {
|
||||
d2.lock().unwrap().on_event(&ev, Instant::now());
|
||||
let started = self.host.start().await;
|
||||
// The stop flag is read under the same lock that makes the state Running, so a stop asked
|
||||
// for while starting is never lost.
|
||||
let started = {
|
||||
let mut i = self.inner.lock().unwrap();
|
||||
if std::mem::take(&mut i.stop_asked) {
|
||||
i.state = State::Stopping;
|
||||
started
|
||||
} else {
|
||||
return match started {
|
||||
Ok((running, mut events)) => {
|
||||
let dash: Arc<Mutex<Dashboard>> = Arc::default();
|
||||
let d2 = dash.clone();
|
||||
let feeder = tokio::spawn(async move {
|
||||
while let Some(ev) = events.recv().await {
|
||||
d2.lock().unwrap().on_event(&ev, Instant::now());
|
||||
}
|
||||
});
|
||||
i.state = State::Running;
|
||||
i.running = Some(running);
|
||||
i.dashboard = dash;
|
||||
i.feeder = Some(feeder);
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
let mut i = self.inner.lock().unwrap();
|
||||
i.state = State::Running;
|
||||
i.running = Some(running);
|
||||
i.dashboard = dash;
|
||||
i.feeder = Some(feeder);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
let e = crate::logs::redact(&e, &self.host.secrets());
|
||||
crate::error_log!("app", "the services did not start: {e}");
|
||||
let mut i = self.inner.lock().unwrap();
|
||||
i.state = State::Failed;
|
||||
i.error = Some(e.clone());
|
||||
Err(e)
|
||||
Err(e) => {
|
||||
let e = crate::logs::redact(&e, &self.host.secrets());
|
||||
crate::error_log!("app", "the services did not start: {e}");
|
||||
i.state = State::Failed;
|
||||
i.error = Some(e.clone());
|
||||
Err(e)
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
// Stopped while starting: whatever came up goes down again.
|
||||
if let Ok((running, _)) = started {
|
||||
running.stop().await;
|
||||
}
|
||||
self.inner.lock().unwrap().state = State::Stopped;
|
||||
crate::info_log!("app", "start cancelled");
|
||||
Err("cancelled".into())
|
||||
}
|
||||
|
||||
/// Stop from running; what was said is forgotten.
|
||||
/// Stop from running, or cancel a start; what was said is forgotten.
|
||||
pub async fn stop(&self) -> Result<(), String> {
|
||||
let running = {
|
||||
let mut i = self.inner.lock().unwrap();
|
||||
if i.state == State::Starting {
|
||||
i.stop_asked = true;
|
||||
drop(i);
|
||||
self.host.cancel_start();
|
||||
return Ok(());
|
||||
}
|
||||
if i.state != State::Running {
|
||||
return Err(format!("cannot stop while {:?}", i.state).to_lowercase());
|
||||
}
|
||||
@@ -153,6 +185,7 @@ impl Controller {
|
||||
view["state"] = json!(state);
|
||||
view["error"] = json!(error);
|
||||
view["system"] = json!(self.system().await);
|
||||
view["llm"] = self.host.llm();
|
||||
view["performance"] = Value::Null; // game detection comes in M7
|
||||
view
|
||||
}
|
||||
@@ -173,13 +206,21 @@ impl Controller {
|
||||
|
||||
/// The real services from a data folder.
|
||||
pub struct ServicesHost {
|
||||
pub data_dir: PathBuf,
|
||||
data_dir: PathBuf,
|
||||
llm: Arc<crate::strata::Llm>,
|
||||
}
|
||||
|
||||
impl ServicesHost {
|
||||
pub fn new(data_dir: PathBuf) -> Self {
|
||||
let llm = Arc::new(crate::strata::Llm::new(&data_dir));
|
||||
Self { data_dir, llm }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Host for ServicesHost {
|
||||
async fn start(&self) -> Result<(Arc<dyn Running>, mpsc::UnboundedReceiver<CoreEvent>), String> {
|
||||
let mut s = crate::services::start_services(&self.data_dir).await.map_err(|e| e.to_string())?;
|
||||
let mut s = crate::services::start_services(&self.data_dir, self.llm.clone()).await.map_err(|e| e.to_string())?;
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let mut events = std::mem::replace(&mut s.events, mpsc::unbounded_channel().1);
|
||||
tokio::spawn(async move {
|
||||
@@ -195,6 +236,14 @@ impl Host for ServicesHost {
|
||||
fn secrets(&self) -> Vec<String> {
|
||||
crate::secrets::Secrets::new(&self.data_dir.join("config").join("secrets.dat")).values()
|
||||
}
|
||||
|
||||
fn cancel_start(&self) {
|
||||
self.llm.cancel();
|
||||
}
|
||||
|
||||
fn llm(&self) -> Value {
|
||||
json!(self.llm.status())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@@ -278,6 +327,56 @@ mod tests {
|
||||
(Controller::new(Shared(host.clone())), counts, host)
|
||||
}
|
||||
|
||||
/// A start that takes a while (the LLM's first start) and honours a cancel or ignores it.
|
||||
struct SlowHost {
|
||||
counts: Arc<Counts>,
|
||||
honours_cancel: bool,
|
||||
cancelled: Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
#[async_trait]
|
||||
impl Host for SlowHost {
|
||||
async fn start(&self) -> Result<(Arc<dyn Running>, mpsc::UnboundedReceiver<CoreEvent>), String> {
|
||||
self.counts.starts.fetch_add(1, Ordering::SeqCst);
|
||||
self.cancelled.store(false, Ordering::SeqCst); // as the LLM does: a cancel ends one start
|
||||
for _ in 0..50 {
|
||||
if self.honours_cancel && self.cancelled.load(Ordering::SeqCst) {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
Ok((Arc::new(FakeRunning(self.counts.clone())), mpsc::unbounded_channel().1))
|
||||
}
|
||||
fn secrets(&self) -> Vec<String> {
|
||||
vec![]
|
||||
}
|
||||
fn cancel_start(&self) {
|
||||
self.cancelled.store(true, Ordering::SeqCst);
|
||||
}
|
||||
fn llm(&self) -> Value {
|
||||
json!({"state": "starting", "percent": 12.5})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stop_while_starting_cancels_the_start_or_stops_what_came_up() {
|
||||
for honours_cancel in [true, false] {
|
||||
let counts = Arc::new(Counts::default());
|
||||
let c = Controller::new(SlowHost { counts: counts.clone(), honours_cancel, cancelled: Arc::default() });
|
||||
let c2 = c.clone();
|
||||
let start = tokio::spawn(async move { c2.start().await });
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
assert_eq!(c.snapshot().await["llm"]["percent"], json!(12.5), "progress shows while starting");
|
||||
c.stop().await.unwrap();
|
||||
assert_eq!(start.await.unwrap().unwrap_err(), "cancelled");
|
||||
let s = c.snapshot().await;
|
||||
assert_eq!((s["state"].clone(), s["error"].clone()), (json!("stopped"), Value::Null));
|
||||
// What came up anyway was stopped; a cancelled start left nothing to stop.
|
||||
assert_eq!(counts.stops.load(Ordering::SeqCst), if honours_cancel { 0 } else { 1 });
|
||||
c.start().await.unwrap();
|
||||
assert_eq!(c.state(), State::Running, "it can start again");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_and_stop_follow_the_state_rules() {
|
||||
let (c, counts, _) = controller(0);
|
||||
|
||||
Reference in New Issue
Block a user