179 lines · 8.1 KB · RustRaw
//! This device's Code model preference.use crate::{handle::CottonHandle, methods::MethodError, shell::client::ClientController};use serde_json::{json, Value};use std::sync::Mutex;pub const METHODS: [&str; 3] = [ "code.preferences.import", "code.preferences.read", "code.preferences.set",];const FILE: &str = "code-preferences.json";static LOCK: Mutex<()> = Mutex::new(());pub fn call(h: &CottonHandle, m: &str, r: &Value) -> Result<Value, MethodError> { match m { "code.preferences.read" => read(h), "code.preferences.import" => import(h, r), "code.preferences.set" => set(h, r), _ => Err(MethodError::new( "unknown_method", "unknown code preference method", )), }}fn path(h: &CottonHandle) -> std::path::PathBuf { path_for(&h.client())}fn path_for(client: &ClientController) -> std::path::PathBuf { client.layout().client_dir().join(FILE)}fn load(h: &CottonHandle) -> Result<Option<Value>, MethodError> { let p = path(h); match std::fs::read(p) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(MethodError::new("unreadable", format!("{FILE}: {e}"))), Ok(b) => Ok(Some(decode(&b)?)), }}fn decode(b:&[u8])->Result<Value,MethodError>{let v:Value=serde_json::from_slice(b).map_err(|_|MethodError::new("unreadable",format!("{FILE} is not valid JSON")))?;if valid(&v){Ok(v)}else{Err(MethodError::new("unreadable",format!("{FILE} is invalid")))}}fn valid(v: &Value) -> bool { v.get("model") .is_some_and(|m| m.is_null() || m.as_str().is_some_and(allowed))}fn allowed(m: &str) -> bool { cotton_core::rules::session_model::OFFERED_MODELS .iter() .any(|x| x.0 == m)}fn answer(v: Value) -> Value { json!({"model":v["model"],"needs_import":false})}fn read(h: &CottonHandle) -> Result<Value, MethodError> { read_for(&h.client())}/// Read the device-owned preference through the same decoder used by the/// native command. Settings records use this to avoid representing an/// unimported preference as a selected model.pub(crate) fn read_for(client: &ClientController) -> Result<Value, MethodError> { let p = path_for(client); let stored = match std::fs::read(p) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, Err(e) => return Err(MethodError::new("unreadable", format!("{FILE}: {e}"))), Ok(bytes) => Some(decode(&bytes)?), }; Ok(match stored { Some(v) => answer(v), None => json!({"needs_import":true}), })}/// Supply the persisted model only when the caller did not name `model`,/// and only to a Claude Code session: the preference is a Claude model, and/// Codex picks its own. An unimported file preserves the agent's default.pub fn with_default(client: &ClientController, request: &Value) -> Result<Value, MethodError> { let mut out = request.as_object().cloned() .ok_or_else(|| MethodError::new("bad_request", "session.create needs an arguments object"))?; let tool = out.get("tool").and_then(Value::as_str).unwrap_or("claude-code"); if out.contains_key("model") || tool != "claude-code" { return Ok(Value::Object(out)); } let pref = read_for(client)?; if let Some(model) = pref.get("model").filter(|value| !value.is_null()) { out.insert("model".into(), model.clone()); } Ok(Value::Object(out))}fn save(h: &CottonHandle, v: &Value) -> Result<(), MethodError> { let p = path(h); std::fs::create_dir_all(p.parent().unwrap()) .map_err(|e| MethodError::new("unwritable", e.to_string()))?; let t = p.with_extension(format!("json.{}.partial", std::process::id())); // not a copy: preferences file. std::fs::write(&t, serde_json::to_vec(v).unwrap()) .map_err(|e| MethodError::new("unwritable", e.to_string()))?; // not a copy: preferences file. std::fs::rename(t, p).map_err(|e| MethodError::new("unwritable", e.to_string()))}fn import(h: &CottonHandle, r: &Value) -> Result<Value, MethodError> { let _g = LOCK.lock().unwrap(); if let Some(v) = load(h)? { return Ok(answer(v)); } let model=r.get("model").ok_or_else(||MethodError::new("bad_request","code.preferences.import needs model"))?; let v = json!({"model":model}); if !valid(&v) { return Err(MethodError::new("bad_request", "model is not offered")); } save(h, &v)?; drop(_g); emit(h); Ok(answer(v))}fn set(h: &CottonHandle, r: &Value) -> Result<Value, MethodError> { let (old, v) = { let _g = LOCK.lock().unwrap(); let old = load(h)? .ok_or_else(|| MethodError::new("needs_import", "Import Code preferences first"))?; let patch=r.get("patch").and_then(Value::as_object).filter(|p|p.len()==1).ok_or_else(||MethodError::new("bad_request","code.preferences.set needs exactly patch.model"))?; let model=patch.get("model").ok_or_else(||MethodError::new("bad_request","code.preferences.set needs patch.model"))?; let v = json!({"model":model}); if !valid(&v) { return Err(MethodError::new("bad_request", "model is not offered")); } save(h, &v)?; (old, v) }; emit(h); Ok( json!({"model":v["model"],"undo":{"method":"code.preferences.set","args":{"patch":{"model":old["model"]}}}}), )}fn emit(h: &CottonHandle) { if let Ok(ws) = h .client() .with_writer(|f| Ok::<String, String>(f.workspace_id.to_string())) { h.client() .emit_data(&ws, vec!["cotton_workspaces".into()], "local"); }}#[cfg(test)]mod tests { use super::*; #[test] fn models_are_canonical_and_invalid_values_refuse() { assert!(valid(&json!({"model":"fable"}))); assert!(valid(&json!({"model":null}))); assert!(!valid(&json!({"model":"Fable"}))); assert!(!valid(&json!({"model":7}))); } #[test] fn preference_file_imports_once_and_refuses_corruption_or_an_implicit_reset() { // RULE: Import must preserve a device's existing choice, and missing // or corrupt input must never silently replace it with the default. let (_dir, handle) = crate::fixture::synthetic_phone(); let run = |method, args| crate::methods::dispatch(&handle, method, &args); assert_eq!(run("code.preferences.read", json!({})).unwrap()["needs_import"], true); assert!(run("code.preferences.set", json!({"patch":{"model":"fable"}})).is_err()); assert!(run("code.preferences.import", json!({})).is_err()); assert_eq!(run("code.preferences.import", json!({"model":"opus"})).unwrap()["model"], "opus"); assert_eq!(with_default(&handle.client(), &json!({"tool":"claude-code"})).unwrap()["model"], "opus"); // RULE: The Claude model preference never rides on a Codex session, which picks its own model. assert!(with_default(&handle.client(), &json!({"tool":"codex"})).unwrap().get("model").is_none()); assert_eq!(with_default(&handle.client(), &json!({"model":"sonnet"})).unwrap()["model"], "sonnet"); assert!(with_default(&handle.client(), &json!({"model":null})).unwrap()["model"].is_null()); assert!(with_default(&handle.client(), &Value::Null).is_err()); assert_eq!(run("code.preferences.import", json!({"model":"fable"})).unwrap()["model"], "opus"); let changed = run("code.preferences.set", json!({"patch":{"model":"sonnet"}})).unwrap(); assert_eq!(changed["undo"]["args"]["patch"]["model"], "opus"); assert!(run("code.preferences.set", json!({"patch":{}})).is_err()); assert!(run("code.preferences.set", json!({"patch":{"model":null,"extra":true}})).is_err()); assert_eq!(run("code.preferences.read", json!({})).unwrap()["model"], "sonnet"); std::fs::write(path(&handle), b"broken").unwrap(); for (method, args) in [ ("code.preferences.read", json!({})), ("code.preferences.import", json!({"model":"opus"})), ("code.preferences.set", json!({"patch":{"model":null}})), ] { assert_eq!(run(method, args).unwrap_err().code, "unreadable"); } assert_eq!(std::fs::read(path(&handle)).unwrap(), b"broken"); }}