Remember last chosen provider/model in HX_HOME/last.json

This commit is contained in:
hermes committed 2026-10-06 11:43:51 +00:00
1 parent 6f951ad7f8
commit 2f1ce2c072
2 files changed
+65 -4

No files matched your search

+46
View File
@@ -23,7 +23,22 @@ pub struct Switched {
pub window: u64,
}
/// Last chosen provider + model, kept in `$HX_HOME/last.json` so the next start reuses it.
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
pub struct Last {
pub provider: Kind,
pub model: String,
}
impl Last {
/// `None` when the file is missing or unreadable.
pub fn load(path: &std::path::Path) -> Option<Self> {
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}
}
pub struct Switcher {
remember: Option<std::path::PathBuf>,
kind: Kind,
models: Vec<ModelInfo>,
make_provider: MakeProvider,
@@ -40,6 +55,7 @@ impl Switcher {
auto_compact: bool,
) -> Self {
Self {
remember: None,
kind,
models,
make_provider,
@@ -47,6 +63,12 @@ impl Switcher {
}
}
/// Write every successful switch to `path` (best effort).
pub fn remember_in(mut self, path: std::path::PathBuf) -> Self {
self.remember = Some(path);
self
}
/// The provider the agent currently uses.
pub fn kind(&self) -> Kind {
self.kind
@@ -81,6 +103,14 @@ impl Switcher {
} else {
agent.set_model(model.as_str());
}
if let Some(p) = &self.remember {
let last = Last {
provider: kind,
model: model.clone(),
};
// ponytail: failing to save must not fail the switch
let _ = serde_json::to_vec(&last).map(|b| std::fs::write(p, b));
}
let window = models::window(&self.models, &model);
if self.auto_compact {
agent.fit_window(window);
@@ -219,6 +249,22 @@ mod tests {
);
}
#[test]
fn switches_are_remembered() {
let (sw, mut a, _m, d) = setup(true, false);
let f = d.path().join("last.json");
assert_eq!(Last::load(&f), None);
let mut sw = sw.remember_in(f.clone());
sw.set_model(&mut a, "gpt-x").unwrap();
let want = Last {
provider: Kind::Codex,
model: "gpt-x".into(),
};
assert_eq!(Last::load(&f), Some(want));
std::fs::write(&f, "junk").unwrap();
assert_eq!(Last::load(&f), None);
}
#[test]
fn configured_threshold_is_left_alone() {
let (mut sw, mut a, _m, _d) = setup(false, false);