Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tui): /vibe-setting maps a plain-language request onto settings (#9078)
thinhlpg454c1d48d629
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdxindex 1e5b9781e..acf1a6ee3 100644--- a/docs/src/pages/docs/agent/slash-commands.mdx+++ b/docs/src/pages/docs/agent/slash-commands.mdx@@ -74,6 +74,47 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-| `/config` | View provider config (`~/.jan/config.toml`) || `/terminal-setup` | Configure this terminal so <kbd>Shift</kbd>+<kbd>Enter</kbd> inserts a newline and, on macOS, <kbd>Option</kbd>+<kbd>Delete</kbd> deletes a word. Writes the terminal's own config where it can (VS Code, kitty, Ghostty, tmux) and prints the manual step where it cannot. Idempotent || `/settings [max_parallel_subagents N]` | Edit settings in an interactive menu - the project's `agent.toml` (`[agent]` knobs `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `[budget]` limits, the `[tools]` / `[skills]` toggles) and user-wide `~/.jan/config.toml` keys such as `wave` and `ask_timeout_secs` in the one list (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets - except `wave`, where an empty field is the "no sweep" value and `x` restores the default π). The leading `providers` row opens a manager for OpenAI-compatible providers in `~/.jan/config.toml`: `a` adds, Enter edits, `d` twice deletes. `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next session (or after `/reload config` for the `[agent]`/`[budget]` limits), except cosmetic ones like `wave` that apply immediately |+| `/vibe-setting <what you want>` | Say what you want in plain words and the agent proposes the settings changes that get it. See [below](#vibe-setting) |++### `/vibe-setting`++```+/vibe-setting I work on huge repos with Opus, stop compacting so often and show me its thinking+```++The session's model receives the `/settings` keys (name, file, type, default, current value, what+it does) and your sentence, in one request of its own. The conversation is not included, and+nothing is added to it. The model answers with a list of changes. Jan checks each one with the+same rules `/settings` uses, then shows a diff:++```+agent.toml (this project)+ context_window 128000 -> 1000000 Opus has a 1M window+ compaction_ratio 0.8 -> 0.9 compact later+ show_reasoning default (false) -> true+Apply? [y/N]+```++Nothing is written until you press <kbd>y</kbd>. <kbd>Enter</kbd>, <kbd>n</kbd> or <kbd>Esc</kbd>+cancels. Accepted changes go through the `/settings` writer, and the note that follows says when+each one applies:++| Keys | Applies |+| --- | --- |+| `wave` | Now |+| `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `send_reasoning`, `budget.max_tokens` | After `/reload config`, from the next run |+| Everything else (`max_parallel_subagents`, `tools.default`, `skills.inject`, `show_reasoning`, ...) | When Jan restarts |++- It only changes `/settings` keys. The model, providers, API keys, MCP servers and skills are out+ of scope; when a request needs one, the reply names the command to use (`/model`, `/login`, ...).+- It never touches credentials. `claude_code_alias` is not offered.+- A change that loosens tool permissions (`tools.default` toward `allow`) needs `yes` typed out, not+ a single key.+- A key it doesn't know, or a value outside its range, is listed as refused and never written.+- When the request is ambiguous ("make it faster"), it asks a question instead of guessing. Nothing+ is written.++It runs only while the agent is idle.See [Providers](/docs/agent/providers), [MCP](/docs/agent/mcp), [Plugins](/docs/agent/plugins), and[Keybindings](/docs/agent/keybindings#shiftenter-and-the-option-key).diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 86b4a9509..5fbeac859 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -3679,6 +3679,38 @@ pub(crate) async fn evaluate_goal(condition: &str,messages: &[serde_json::Value],) -> Result<crate::core::agent::goal::GoalVerdict, String> {+ let model = side_call_invoker(args, smol_model_id).await?;+ crate::core::agent::goal::evaluate(smol_model_id, condition, messages, &model).await+}++/// One stateless, tool-free completion outside the run: `request` is sent as+/// is and the reply's text content returned. For CLI side calls that must not+/// touch the session's history or prompt -- `/vibe-setting` maps a sentence to+/// settings this way, so the conversation's cached prefix is never involved.+#[cfg(feature = "cli")]+pub(crate) async fn side_completion(+ args: &OrchestrationArgs,+ model_id: &str,+ request: &serde_json::Value,+) -> Result<String, String> {+ let model = side_call_invoker(args, model_id).await?;+ // Nothing streams to the user: a dropped receiver keeps the tokens internal.+ let (sink, _rx) = mpsc::unbounded_channel();+ let completion = model.invoke(request, &sink).await?;+ Ok(crate::core::agent::upstream::extract_choice_message(&completion)+ .and_then(|m| m.get("content"))+ .and_then(|c| c.as_str())+ .unwrap_or_default()+ .to_string())+}++/// The invoker a between-turns side call uses: `model_id`'s upstream, billed to+/// this session, with no run stream to report provenance on.+#[cfg(feature = "cli")]+async fn side_call_invoker(+ args: &OrchestrationArgs,+ smol_model_id: &str,+) -> Result<HttpModelInvoker, String> {let (upstream_url, api_keys) = resolve_upstream_for_model(smol_model_id,args.provider_configs.clone(),@@ -3714,7 +3746,7 @@ pub(crate) async fn evaluate_goal(// Between turns, like `/compact`: no run stream exists to carry it.provenance_events: None,};- crate::core::agent::goal::evaluate(smol_model_id, condition, messages, &model).await+ Ok(model)}/// Summary of still-open (pending/in-progress) todos, or `None` when there isdiff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 1c606940b..4a50f2e39 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -37,6 +37,7 @@ use tokio::task::JoinHandle;mod highlight;mod markdown;mod theme;+mod vibe_setting;use markdown::{format_markdown_lines, live_assistant_lines, reasoning_detail_lines, reasoning_summary_row,@@ -2064,6 +2065,12 @@ struct App {/// keyboard while open. Holds the setting being edited and any validation/// error; writes go straight to agent.toml on Enter.settings_prompt: Option<SettingsPrompt>,+ /// `/vibe-setting`'s side call mapping the request onto settings, while it+ /// runs. Awaited by the chat loop; off the render loop like `/context`.+ vibe_task: Option<JoinHandle<Result<String, String>>>,+ /// `/vibe-setting`'s proposed diff, docked for a yes/no. Owns the keyboard+ /// while open; nothing is written until it is confirmed.+ vibe_confirm: Option<vibe_setting::VibeProposal>,/// The open readout (`/context` or any `/usage` view), or `None`. One/// field, so opening either replaces the other instead of stacking two/// popups over each other.@@ -2691,6 +2698,8 @@ impl App {model_picker: None,login: None,settings_prompt: None,+ vibe_task: None,+ vibe_confirm: None,readout: None,context_request: false,last_execution_id: None,@@ -3638,6 +3647,8 @@ impl App {Some("answer the question above")} else if self.settings_prompt.is_some() {Some("edit the setting above")+ } else if self.vibe_confirm.is_some() {+ Some("answer the proposal above")} else if self.mcp_prompt.is_some() || self.provider_prompt.is_some() {Some("finish the wizard above")} else if self.readout.is_some() {@@ -9062,6 +9073,19 @@ fn spawn_snapshot(})}+/// Await `/vibe-setting`'s side call, parking forever when none is running so+/// this can sit in the loop's `select!` unconditionally.+async fn await_vibe(+ task: &mut Option<JoinHandle<Result<String, String>>>,+) -> Option<Result<String, String>> {+ let joined = match task.as_mut() {+ Some(h) => h.await,+ None => return pending().await,+ };+ *task = None;+ Some(joined.unwrap_or_else(|e| Err(format!("vibe-setting task failed: {e}"))))+}+/// Await the in-flight snapshot task once, clearing the slot. Same cancel-safe/// borrow as `await_mcp`; pends forever when idle.async fn await_snapshot(@@ -10192,6 +10216,9 @@ async fn chat_loop<B: Backend>(Some(done) = await_mcp_job(&mut mcp_job) => {finish_mcp_job(app, done, mcp_servers, &mut mcp_job).await;}+ Some(reply) = await_vibe(&mut app.vibe_task) => {+ vibe_setting::finish(app, reply);+ }Some(report) = await_context(&mut context_task) => {// Only apply a report the user is still looking at: a result// landing after the overlay was closed must not reopen it.@@ -10689,6 +10716,8 @@ fn route_paste_event(app: &mut App, event: Event) {prompt.paste(&text);} else if let Some(prompt) = app.settings_prompt.as_mut() {prompt.paste(&text);+ } else if let Some(proposal) = app.vibe_confirm.as_mut() {+ proposal.paste(&text);} else if let Some(prompt) = app.mcp_prompt.as_mut() {prompt.paste(&text);} else if let Some(prompt) = app.provider_prompt.as_mut() {@@ -11132,6 +11161,11 @@ async fn handle_key(handle_settings_key(app, key, ctrl);return;}+ // So does `/vibe-setting`'s confirm dock: nothing is written without it.+ if app.vibe_confirm.is_some() {+ vibe_setting::handle_key(app, key, ctrl);+ return;+ }// The MCP add/edit wizard owns the keyboard while open.if app.mcp_prompt.is_some() {@@ -12279,6 +12313,12 @@ const SLASH_COMMANDS: &[SlashCommand] = &[description: "Edit agent.toml and ~/.jan settings (menu); most apply next run",alias_of: None,},+ SlashCommand {+ name: "/vibe-setting",+ hint: "<what you want>",+ description: "Describe what you want; review and confirm the settings it changes",+ alias_of: None,+ },SlashCommand {name: "/update",hint: "",@@ -12492,6 +12532,7 @@ async fn run_command("config" => open_config_screen(app),"terminal-setup" => terminal_setup_command(app),"settings" => settings_command(app, arg),+ "vibe-setting" => vibe_setting::command(app, arg),"goal" => goal_command(app, arg),"init" => init_command(app),"plan" => plan_command(app, arg),@@ -13805,6 +13846,83 @@ fn grapheme_prefix(s: &str, n: usize) -> String {s.graphemes(true).take(n).collect()}+/// Parse what was typed for a `/settings` row into the TOML item to write, the+/// one validator every settings writer shares (`/settings` and `/vibe-setting`).+/// `Ok(None)` is an unset -- the key is removed so its default applies -- except+/// for a `Glyph`, where an empty field is the written "off" value. `Err` is the+/// message to show, naming the valid range.+fn parse_setting_input(+ def: &AgentSettingDef,+ input: &str,+) -> Result<Option<toml_edit::Item>, String> {+ let trimmed = input.trim();+ match def.kind {+ AgentSettingKind::Int { default, min } => {+ if trimmed.is_empty() {+ return Ok(None);+ }+ match trimmed.parse::<u64>() {+ Ok(n) if n >= min => Ok(Some(toml_edit::value(n as i64))),+ Ok(_) => Err(format!(+ "must be at least {min} (default: {})",+ default+ .map(|d| d.to_string())+ .unwrap_or_else(|| "unset".into())+ )),+ Err(_) => Err(format!("'{input}' is not an integer")),+ }+ }+ AgentSettingKind::Float { default, min, max } => {+ if trimmed.is_empty() {+ return Ok(None);+ }+ match trimmed.parse::<f64>() {+ Ok(n) if n >= min && n <= max => Ok(Some(toml_edit::value(n))),+ Ok(_) => Err(format!(+ "must be between {min} and {max} (default: {})",+ default+ .map(|d| d.to_string())+ .unwrap_or_else(|| "unset".into())+ )),+ Err(_) => Err(format!("'{input}' is not a number")),+ }+ }+ AgentSettingKind::Glyph { .. } => {+ // Not trimmed to empty-means-unset like `Text`: a cleared field+ // writes `""`, which is the off switch. `x` on the row is how you+ // get back to the default.+ if let Some(err) = crate::core::agent::global_config::wave_error(trimmed) {+ return Err(err);+ }+ Ok(Some(toml_edit::value(trimmed.to_string())))+ }+ AgentSettingKind::Text { .. } => {+ Ok((!trimmed.is_empty()).then(|| toml_edit::value(trimmed.to_string())))+ }+ AgentSettingKind::Enum { options, default } => {+ if trimmed.is_empty() {+ Ok(None)+ } else if options.contains(&trimmed) {+ Ok(Some(toml_edit::value(trimmed.to_string())))+ } else {+ Err(format!(+ "must be one of: {} (default: {default})",+ options.join(" | ")+ ))+ }+ }+ AgentSettingKind::Bool { default } => {+ if trimmed.is_empty() {+ Ok(None)+ } else if let Ok(b) = trimmed.parse::<bool>() {+ Ok(Some(toml_edit::value(b)))+ } else {+ Err(format!("must be true or false (default: {default})"))+ }+ }+ }+}+/// Keyboard for the `/settings` edit dock: chars/backspace edit the field,/// Enter validates and writes (an empty field clears the key, except for a/// `Glyph`, where it writes the off value), Esc cancels. Mirrors@@ -13822,90 +13940,11 @@ fn handle_settings_key(app: &mut App, key: KeyEvent, ctrl: bool) {match key.code {KeyCode::Enter => {let toml_path = app.agent_dir.join("agent.toml");- let value: Option<toml_edit::Item> = match prompt.def().kind {- AgentSettingKind::Int { default, min } => {- if prompt.input.trim().is_empty() {- None- } else {- match prompt.input.trim().parse::<u64>() {- Ok(n) if n >= min => Some(toml_edit::value(n as i64)),- Ok(_) => {- prompt.error = Some(format!(- "must be at least {min} (default: {})",- default- .map(|d| d.to_string())- .unwrap_or_else(|| "unset".into())- ));- return;- }- Err(_) => {- prompt.error =- Some(format!("'{}' is not an integer", prompt.input));- return;- }- }- }- }- AgentSettingKind::Float { default, min, max } => {- if prompt.input.trim().is_empty() {- None- } else {- match prompt.input.trim().parse::<f64>() {- Ok(n) if n >= min && n <= max => Some(toml_edit::value(n)),- Ok(_) => {- prompt.error = Some(format!(- "must be between {min} and {max} (default: {})",- default- .map(|d| d.to_string())- .unwrap_or_else(|| "unset".into())- ));- return;- }- Err(_) => {- prompt.error =- Some(format!("'{}' is not a number", prompt.input));- return;- }- }- }- }- AgentSettingKind::Glyph { .. } => {- // Not trimmed to empty-means-unset like `Text`: a cleared- // field writes `""`, which is the off switch. `x` on the- // row is how you get back to the default.- let input = prompt.input.trim();- if let Some(err) = crate::core::agent::global_config::wave_error(input) {- prompt.error = Some(err);- return;- }- Some(toml_edit::value(input.to_string()))- }- AgentSettingKind::Text { .. } => (!prompt.input.trim().is_empty())- .then(|| toml_edit::value(prompt.input.trim().to_string())),- AgentSettingKind::Enum { options, default } => {- let input = prompt.input.trim();- if input.is_empty() {- None- } else if options.contains(&input) {- Some(toml_edit::value(input.to_string()))- } else {- prompt.error = Some(format!(- "must be one of: {} (default: {default})",- options.join(" | ")- ));- return;- }- }- AgentSettingKind::Bool { default } => {- let input = prompt.input.trim();- if input.is_empty() {- None- } else if let Ok(b) = input.parse::<bool>() {- Some(toml_edit::value(b))- } else {- prompt.error = Some(format!("must be true or false (default: {default})"));- return;- }+ let value = match parse_setting_input(prompt.def(), &prompt.input) {+ Ok(value) => value,+ Err(error) => {+ prompt.error = Some(error);+ return;}};match write_setting(prompt.def(), &toml_path, value) {@@ -17876,6 +17915,19 @@ fn draw(f: &mut Frame, app: &mut App) {draw_login(f, rect, prompt);} else if let Some(confirm) = &app.browser_confirm {draw_browser_confirm_overlay(f, confirm, chunks[2], chunks[1]);+ } else if let Some(proposal) = &app.vibe_confirm {+ let height = (vibe_setting::lines(proposal, chunks[2].width.saturating_sub(2)).len()+ as u16+ + 2)+ .min(chunks[1].height);+ let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);+ let rect = ratatui::layout::Rect {+ x: chunks[2].x,+ y,+ width: chunks[2].width,+ height,+ };+ vibe_setting::draw(f, rect, proposal);} else if let Some(prompt) = &app.settings_prompt {let toml_path = app.agent_dir.join("agent.toml");let height = (settings_prompt_lines(prompt, &toml_path, chunks[2].width.saturating_sub(2))@@ -25248,7 +25300,7 @@ mod tests {/// the next dock added cannot quietly regress only the rendering half.#[test]fn every_blocking_dock_marks_the_input_row_inactive() {- let setups: [DockSetup; 8] = [+ let setups: [DockSetup; 9] = [// The account OAuth dock takes every keystroke and outranks the// API-key one, so it has to block the field as hard as the rest.("account_login", |app| {@@ -25289,6 +25341,13 @@ mod tests {("provider_prompt", |app| {app.provider_prompt = Some(super::ProviderPrompt::new())}),+ ("vibe_confirm", |app| {+ super::vibe_setting::finish(+ app,+ Ok(r#"{"changes": [{"key": "max_tokens", "new_value": 512}]}"#.into()),+ );+ assert!(app.vibe_confirm.is_some());+ }),];for (name, open) in setups {let mut app = test_app();@@ -26126,6 +26185,173 @@ mod tests {let _ = std::fs::remove_dir_all(&app.agent_dir);}+ // ββ /vibe-setting (#9078) ββββββββββββββββββββββββββββββββββββββββββββ++ /// A project agent.toml under a scratch HOME, so a global key written by a+ /// test never reaches the developer's ~/.jan.+ fn vibe_app(body: &str) -> TestApp {+ let app = test_app();+ std::fs::create_dir_all(&app.agent_dir).unwrap();+ std::fs::write(app.agent_dir.join("agent.toml"), body).unwrap();+ app+ }++ fn vibe_reply(app: &mut App, reply: &str) {+ super::vibe_setting::finish(app, Ok(reply.to_string()));+ }++ /// The confirm path: the diff docks, nothing is written until `y`, then the+ /// writes go through the /settings writer and the note says when they apply.+ #[test]+ fn vibe_setting_writes_only_after_confirmation() {+ crate::core::agent::global_config::with_temp_home(|home| {+ let mut app = vibe_app("# keep me\n[agent]\ncontext_window = 128000\n");+ let toml_path = app.agent_dir.join("agent.toml");+ vibe_reply(+ &mut app,+ r#"{"changes": [+ {"key": "context_window", "scope": "project", "new_value": 1000000, "reason": "1M window"},+ {"key": "show_reasoning", "scope": "project", "new_value": true},+ {"key": "wave", "scope": "global", "new_value": "~"}+ ]}"#,+ );+ assert!(app.vibe_confirm.is_some(), "the diff docks");+ assert!(app.blocking_dock().is_some(), "and owns the field");+ let before = std::fs::read_to_string(&toml_path).unwrap();+ assert!(!before.contains("1000000"), "nothing written yet: {before}");+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("128000 -> 1000000"), "{screen}");+ assert!(screen.contains("~/.jan/config.toml"), "{screen}");+ assert!(screen.contains("Apply? [y/N]"), "{screen}");++ super::vibe_setting::handle_key(&mut app, key(KeyCode::Char('y')), false);+ assert!(app.vibe_confirm.is_none());+ let doc = std::fs::read_to_string(&toml_path).unwrap();+ assert!(doc.contains("context_window = 1000000"), "{doc}");+ assert!(doc.contains("# keep me"), "format-preserving: {doc}");+ assert!(doc.contains("show_reasoning = true"), "{doc}");+ let global = std::fs::read_to_string(home.join(".jan/config.toml")).unwrap();+ assert!(global.contains("wave = \"~\""), "{global}");+ let note = transcript_text(&app);+ assert!(note.contains("wrote 3 setting(s)"), "{note}");+ let flat = note.split_whitespace().collect::<Vec<_>>().join(" ");+ assert!(flat.contains("wave in effect now"), "{flat}");+ assert!(flat.contains("run /reload config to apply context_window"), "{flat}");+ assert!(flat.contains("show_reasoning applies when jan restarts"), "{flat}");+ // A side call, not a turn: the conversation -- and so the cached+ // request prefix -- is exactly what it was before the command.+ assert!(app.history.is_empty(), "{:?}", app.history);+ assert!(!app.want_start);+ super::set_wave_glyph(None);+ let _ = std::fs::remove_dir_all(&app.agent_dir);+ });+ }++ /// The note's `/reload config` bucket is exactly what `/reload config`+ /// re-applies, and every such key is a `/settings` row.+ #[test]+ fn vibe_setting_reload_keys_match_reload_config() {+ let (app, root) = skill_test_app("deploy", "How to deploy.");+ let mut reloaded: Vec<String> =+ super::reload_config_entries(&app).into_iter().map(|e| e.key).collect();+ let mut listed: Vec<String> = super::vibe_setting::RELOAD_CONFIG_KEYS+ .iter()+ .map(|k| k.to_string())+ .collect();+ reloaded.sort();+ listed.sort();+ assert_eq!(listed, reloaded);+ for key in super::vibe_setting::RELOAD_CONFIG_KEYS {+ assert!(super::AGENT_SETTINGS.iter().any(|d| d.key == *key), "{key}");+ }+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The refuse path: Enter (the default, N) or Esc drops the proposal and+ /// writes nothing.+ #[test]+ fn vibe_setting_declined_writes_nothing() {+ for answer in [KeyCode::Enter, KeyCode::Char('n'), KeyCode::Esc] {+ let mut app = vibe_app("[agent]\n");+ let toml_path = app.agent_dir.join("agent.toml");+ vibe_reply(+ &mut app,+ r#"{"changes": [{"key": "max_parallel_subagents", "new_value": 3}]}"#,+ );+ assert!(app.vibe_confirm.is_some());+ super::vibe_setting::handle_key(&mut app, key(answer), false);+ assert!(app.vibe_confirm.is_none(), "{answer:?} closes the dock");+ assert_eq!(std::fs::read_to_string(&toml_path).unwrap(), "[agent]\n");+ assert!(transcript_text(&app).contains("nothing written"));+ let _ = std::fs::remove_dir_all(&app.agent_dir);+ }+ }++ /// Widening tool permissions needs `yes` typed out: a stray `y` is not it.+ #[test]+ fn vibe_setting_widening_permissions_needs_a_typed_yes() {+ let mut app = vibe_app("[tools]\ndefault = \"read-only\"\n");+ let toml_path = app.agent_dir.join("agent.toml");+ vibe_reply(+ &mut app,+ r#"{"changes": [{"key": "tools.default", "new_value": "allow", "reason": "stop asking"}]}"#,+ );+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("widens tool permissions"), "{screen}");+ super::vibe_setting::handle_key(&mut app, key(KeyCode::Char('y')), false);+ super::vibe_setting::handle_key(&mut app, key(KeyCode::Enter), false);+ assert!(app.vibe_confirm.is_some(), "`y` alone does not apply it");+ assert!(std::fs::read_to_string(&toml_path).unwrap().contains("read-only"));+ super::vibe_setting::handle_key(&mut app, key(KeyCode::Backspace), false);+ for ch in "yes".chars() {+ super::vibe_setting::handle_key(&mut app, key(KeyCode::Char(ch)), false);+ }+ super::vibe_setting::handle_key(&mut app, key(KeyCode::Enter), false);+ assert!(app.vibe_confirm.is_none());+ let doc = std::fs::read_to_string(&toml_path).unwrap();+ assert!(doc.contains("default = \"allow\""), "{doc}");+ let _ = std::fs::remove_dir_all(&app.agent_dir);+ }++ /// An ambiguous request asks back; a failed or non-JSON reply writes nothing.+ #[test]+ fn vibe_setting_asks_back_and_survives_bad_replies() {+ let mut app = vibe_app("[agent]\n");+ vibe_reply(+ &mut app,+ r#"{"changes": [], "question": "Faster as in a smaller model, or shorter replies?"}"#,+ );+ assert!(app.vibe_confirm.is_none());+ assert!(transcript_text(&app).contains("smaller model"));+ vibe_reply(&mut app, "I changed it for you!");+ super::vibe_setting::finish(&mut app, Err("HTTP 500".into()));+ assert!(app.vibe_confirm.is_none());+ let text = transcript_text(&app);+ assert!(text.contains("vibe-setting failed: the model did not answer with JSON"), "{text}");+ assert!(text.contains("vibe-setting failed: HTTP 500"), "{text}");+ assert_eq!(+ std::fs::read_to_string(app.agent_dir.join("agent.toml")).unwrap(),+ "[agent]\n"+ );+ let _ = std::fs::remove_dir_all(&app.agent_dir);+ }++ /// The command refuses what it cannot do instead of queueing it.+ #[test]+ fn vibe_setting_command_guards() {+ let mut app = test_app();+ super::vibe_setting::command(&mut app, " ");+ assert!(transcript_text(&app).contains("usage: /vibe-setting"));+ app.status = Status::Running;+ super::vibe_setting::command(&mut app, "cheaper runs");+ assert!(transcript_text(&app).contains("only available once the run has finished"));+ app.status = Status::Idle;+ super::vibe_setting::command(&mut app, "cheaper runs");+ assert!(transcript_text(&app).contains("no active session"));+ assert!(app.vibe_task.is_none());+ assert!(SLASH_COMMANDS.iter().any(|c| c.name == "/vibe-setting"));+ }+#[test]fn settings_prompt_edits_text_key() {let mut app = test_app();diff --git a/src-tauri/src/core/cli/tui/vibe_setting.rs b/src-tauri/src/core/cli/tui/vibe_setting.rsnew file mode 100644index 000000000..b82f69242--- /dev/null+++ b/src-tauri/src/core/cli/tui/vibe_setting.rs@@ -0,0 +1,793 @@+//! `/vibe-setting` (#9078): describe what you want in plain words and the agent+//! proposes the settings changes that get it, for you to confirm.+//!+//! The model only ever sees the `/settings` catalog (key, scope, type, default,+//! current value, description) and the request, in one stateless side call that+//! never touches the conversation -- so the session's cached prompt prefix is+//! the same whether or not the command is used. It must answer with a list of+//! `{key, scope, new_value, reason}` changes, which are validated here with the+//! same parser `/settings` uses, shown as a diff, and written only after an+//! explicit yes. Free-form TOML is never accepted.+//!+//! Deliberately narrow: only `/settings` keys, never credentials (the Claude+//! Code keychain toggle is left out of the catalog), and a change that widens+//! tool permissions needs a typed `yes` rather than a single key.++use ratatui::prelude::*;+use ratatui::widgets::{Block, Borders, Paragraph};+use serde_json::{json, Value};++use super::{+ apply_live_setting, apply_live_unset, current_setting_value, parse_setting_input,+ setting_path, wrap_spans_hard, write_setting, AgentSettingDef, AgentSettingKind, App, KeyCode,+ KeyEvent, SettingScope, AGENT_SETTINGS,+};++/// `/settings` keys `/vibe-setting` may not propose. `claude_code_alias` decides+/// whether Jan reuses another tool's keychain login: a credential decision, and+/// the issue rules those out of anything the model can change.+const EXCLUDED_KEYS: &[&str] = &["claude_code_alias"];++/// `/settings` keys that `/reload config` re-applies to the running session+/// (see `reload_config` in tui.rs), so a written one needs no restart. Pinned+/// against `reload_config_entries` by a test, so the note can't drift.+pub(super) const RELOAD_CONFIG_KEYS: &[&str] = &[+ "context_window",+ "compaction_ratio",+ "compaction_reserve_tokens",+ "max_tokens",+ "budget.max_tokens",+ "send_reasoning",+];++/// The keys a proposal may name, in `/settings` order.+pub(super) fn catalog() -> impl Iterator<Item = &'static AgentSettingDef> {+ AGENT_SETTINGS+ .iter()+ .filter(|def| !EXCLUDED_KEYS.contains(&def.key))+}++/// One validated change: the key, what it is now, what it becomes (`None` =+/// removed, so its default applies), and the model's reason.+pub(super) struct VibeChange {+ pub def: &'static AgentSettingDef,+ pub current: Option<String>,+ pub new_value: Option<String>,+ pub item: Option<toml_edit::Item>,+ pub reason: String,+}++/// A proposal waiting on the user's answer in the confirm dock.+pub(super) struct VibeProposal {+ pub changes: Vec<VibeChange>,+ /// Entries the model returned that failed validation, each with why.+ pub refused: Vec<String>,+ /// Keys whose change widens tool permissions; non-empty means the dock asks+ /// for a typed `yes` instead of a single `y`.+ pub widens: Vec<String>,+ /// Anything the model could not do with these settings (a model switch, a+ /// provider), passed on so the request is not silently half-done.+ pub note: Option<String>,+ /// The confirmation line typed so far, for a widening proposal.+ pub typed: String,+ pub error: Option<String>,+}++impl VibeProposal {+ pub(super) fn paste(&mut self, text: &str) {+ if !self.widens.is_empty() {+ self.typed.push_str(text.trim());+ }+ }+}++/// What the model's answer comes to once validated.+pub(super) enum VibeOutcome {+ /// At least one real change: open the confirm dock.+ Propose(VibeProposal),+ /// The request was ambiguous; nothing is proposed until it is clearer.+ Ask(String),+ /// Nothing to change: already set that way, or every entry was refused.+ Nothing {+ refused: Vec<String>,+ note: Option<String>,+ },+}++fn scope_name(scope: SettingScope) -> &'static str {+ match scope {+ SettingScope::Project => "project",+ SettingScope::Global => "global",+ }+}++fn file_label(scope: SettingScope) -> &'static str {+ match scope {+ SettingScope::Project => "agent.toml (this project)",+ SettingScope::Global => "~/.jan/config.toml (all projects)",+ }+}++/// Type, range and default of a key, as the model and the diff both read it.+fn kind_text(def: &AgentSettingDef) -> (String, String) {+ let opt = |d: Option<String>| d.unwrap_or_else(|| "unset".to_string());+ match def.kind {+ AgentSettingKind::Int { default, min } => (+ format!("integer >= {min}"),+ opt(default.map(|d| d.to_string())),+ ),+ AgentSettingKind::Float { default, min, max } => (+ format!("number {min}-{max}"),+ opt(default.map(|d| d.to_string())),+ ),+ AgentSettingKind::Glyph { default, max } => (+ format!("string of up to {max} characters, \"\" = off"),+ default.to_string(),+ ),+ AgentSettingKind::Text { default } => ("string".to_string(), default.to_string()),+ AgentSettingKind::Enum { options, default } => {+ (format!("one of {}", options.join(" | ")), default.to_string())+ }+ AgentSettingKind::Bool { default } => ("true | false".to_string(), default.to_string()),+ }+}++const SYSTEM_PROMPT: &str = "You map a user's plain-language request onto Jan agent settings. \+You may only use the settings listed below. Reply with one JSON object and nothing else:\n\+{\"changes\": [{\"key\": \"<key>\", \"scope\": \"project\" or \"global\", \"new_value\": <value, or null to reset it to its default>, \"reason\": \"<a few words>\"}], \"question\": null, \"note\": null}\n\n\+Rules:\n\+- Use only keys from the list, with the scope shown. Every value must satisfy the listed type and range.\n\+- Change only what the request asks for. Leave every other key out.\n\+- If the request is ambiguous (\"faster\" could mean a smaller model or fewer tokens per reply), return \"changes\": [] and one short clarifying question in \"question\".\n\+- The model, providers, API keys, MCP servers and skills are not settings here. If the request needs one, name the command that handles it (/model, /login, /mcp, /settings) in \"note\".\n\n\+Settings (key | scope | type | default | current | description):";++/// The side-call request: the catalog with current values as the system+/// message, the user's words as the only user message. Temperature 0: this is+/// a lookup, not writing.+pub(super) fn build_request(+ model: &str,+ request: &str,+ current: &dyn Fn(&AgentSettingDef) -> Option<String>,+) -> Value {+ let mut system = SYSTEM_PROMPT.to_string();+ for def in catalog() {+ let (kind, default) = kind_text(def);+ let now = current(def).unwrap_or_else(|| "unset".to_string());+ system.push_str(&format!(+ "\n- {} | {} | {kind} | {default} | {now} | {}",+ def.key,+ scope_name(def.scope),+ def.desc+ ));+ }+ json!({+ "model": model,+ "messages": [+ { "role": "system", "content": system },+ { "role": "user", "content": request },+ ],+ "temperature": 0,+ })+}++/// The first `{` to the last `}`: models wrap JSON in prose or a fence often+/// enough that insisting on a bare object would fail for no good reason.+fn json_object(reply: &str) -> Option<serde_json::Map<String, Value>> {+ let start = reply.find('{')?;+ let end = reply.rfind('}')?;+ if end < start {+ return None;+ }+ match serde_json::from_str::<Value>(&reply[start..=end]).ok()? {+ Value::Object(map) => Some(map),+ _ => None,+ }+}++fn text_field(map: &serde_json::Map<String, Value>, key: &str) -> Option<String> {+ map.get(key)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+}++/// A JSON value as the text `/settings` would have been typed, or `None` for+/// null (reset). An integral float for an integer key (`1000000.0`) is written+/// as the integer the model meant.+fn value_text(def: &AgentSettingDef, value: &Value) -> Result<Option<String>, String> {+ match value {+ Value::Null => Ok(None),+ Value::String(s) => Ok(Some(s.clone())),+ Value::Bool(b) => Ok(Some(b.to_string())),+ Value::Number(n) => {+ if let (AgentSettingKind::Int { .. }, Some(f)) = (&def.kind, n.as_f64()) {+ if n.as_u64().is_none() && f.fract() == 0.0 && f >= 0.0 {+ return Ok(Some(format!("{}", f as u64)));+ }+ }+ Ok(Some(n.to_string()))+ }+ _ => Err("expected a single value".to_string()),+ }+}++/// A value normalized through the shared parser, so `0.90` and `0.9` compare+/// equal and a no-op change can be dropped.+fn normalized(def: &AgentSettingDef, value: Option<&str>) -> Option<String> {+ let value = value?;+ parse_setting_input(def, value)+ .ok()+ .flatten()+ .map(|item| item.to_string().trim().to_string())+}++/// `tools.default` rank, loosest last. Unset is the default, `read-only`; an+/// unknown value reads as the default too.+fn permission_rank(value: Option<&str>) -> u8 {+ match value.map(str::trim) {+ Some("deny") => 0,+ Some("allow") => 2,+ _ => 1,+ }+}++/// Whether a change loosens what tools may do without asking.+fn widens_permissions(def: &AgentSettingDef, current: Option<&str>, new: Option<&str>) -> bool {+ def.key == "tools.default" && permission_rank(new) > permission_rank(current)+}++/// Validate the model's reply against the catalog. Every entry is checked with+/// the `/settings` parser; unknown keys, excluded keys, duplicates and bad+/// values are refused with a reason rather than dropped silently, and a change+/// to the value a key already has is left out.+pub(super) fn interpret_reply(+ reply: &str,+ current: &dyn Fn(&AgentSettingDef) -> Option<String>,+) -> Result<VibeOutcome, String> {+ let map = json_object(reply).ok_or_else(|| "the model did not answer with JSON".to_string())?;+ let note = text_field(&map, "note");+ if let Some(question) = text_field(&map, "question") {+ return Ok(VibeOutcome::Ask(question));+ }+ let entries = match map.get("changes") {+ None | Some(Value::Null) => Vec::new(),+ Some(Value::Array(entries)) => entries.clone(),+ Some(_) => return Err("the model's \"changes\" is not a list".to_string()),+ };+ let mut changes: Vec<VibeChange> = Vec::new();+ let mut refused: Vec<String> = Vec::new();+ let mut widens: Vec<String> = Vec::new();+ // Bounded: a reply can only name each catalog key once, and anything past+ // that is noise.+ for entry in entries.iter().take(AGENT_SETTINGS.len() * 2) {+ let Some(entry) = entry.as_object() else {+ refused.push("an entry that is not an object".to_string());+ continue;+ };+ let Some(key) = text_field(entry, "key") else {+ refused.push("an entry with no key".to_string());+ continue;+ };+ if EXCLUDED_KEYS.contains(&key.as_str()) {+ refused.push(format!(+ "{key}: credential settings are never changed by /vibe-setting (use /settings)"+ ));+ continue;+ }+ let Some(def) = catalog().find(|d| d.key == key) else {+ refused.push(format!("{key}: not a setting /vibe-setting can change"));+ continue;+ };+ if changes.iter().any(|c| c.def.key == def.key) {+ refused.push(format!("{key}: listed twice"));+ continue;+ }+ match text_field(entry, "scope").as_deref() {+ None | Some("project") | Some("global") => {}+ Some(other) => {+ refused.push(format!("{key}: unknown scope '{other}'"));+ continue;+ }+ }+ let Some(raw) = entry.get("new_value") else {+ refused.push(format!("{key}: no new_value"));+ continue;+ };+ let text = match value_text(def, raw) {+ Ok(text) => text,+ Err(e) => {+ refused.push(format!("{key}: {e}"));+ continue;+ }+ };+ let item = match &text {+ None => None,+ Some(text) => match parse_setting_input(def, text) {+ Ok(item) => item,+ Err(e) => {+ refused.push(format!("{key} = {text}: {e}"));+ continue;+ }+ },+ };+ // What the parser made of it: an empty field is an unset for every+ // kind but a glyph, whose "" is the written "off".+ let new_value = item.as_ref().map(|_| text.clone().unwrap_or_default().trim().to_string());+ let now = current(def);+ if normalized(def, now.as_deref()) == normalized(def, new_value.as_deref())+ && now.is_some() == new_value.is_some()+ {+ continue;+ }+ if widens_permissions(def, now.as_deref(), new_value.as_deref()) {+ widens.push(def.key.to_string());+ }+ changes.push(VibeChange {+ def,+ current: now,+ new_value,+ item,+ reason: text_field(entry, "reason").unwrap_or_default(),+ });+ }+ if changes.is_empty() {+ return Ok(VibeOutcome::Nothing { refused, note });+ }+ Ok(VibeOutcome::Propose(VibeProposal {+ changes,+ refused,+ widens,+ note,+ typed: String::new(),+ error: None,+ }))+}++/// `/vibe-setting <what you want>`: validate the state, then hand the request+/// to the loop's side call. Idle only, like `/init`: a confirm dock opening+/// over a live run would take the keys from someone steering it.+pub(super) fn command(app: &mut App, arg: &str) {+ let request = arg.trim();+ if request.is_empty() {+ app.note("usage: /vibe-setting <what you want>, e.g. /vibe-setting stop compacting so often");+ return;+ }+ if app.run_is_live() {+ app.note("/vibe-setting is only available once the run has finished");+ return;+ }+ if app.vibe_task.is_some() || app.vibe_confirm.is_some() {+ app.note("/vibe-setting is already working on a request");+ return;+ }+ if app.model.is_empty() {+ app.note("not signed in - run /login to choose a provider");+ return;+ }+ let Some(args) = app.args.clone() else {+ app.note("/vibe-setting unavailable (no active session)");+ return;+ };+ let toml_path = app.agent_dir.join("agent.toml");+ let body = build_request(&app.model, request, &|def| {+ current_setting_value(def, &toml_path)+ });+ let model = app.model.clone();+ app.note("β vibe-setting Β· working out which settings that means...");+ app.vibe_task = Some(tokio::spawn(async move {+ crate::core::agent::r#loop::side_completion(&args, &model, &body).await+ }));+}++/// The side call came back: validate it and open the dock, or say why not.+pub(super) fn finish(app: &mut App, reply: Result<String, String>) {+ let toml_path = app.agent_dir.join("agent.toml");+ let outcome = reply.and_then(|reply| {+ interpret_reply(&reply, &|def| current_setting_value(def, &toml_path))+ });+ match outcome {+ Err(e) => app.note(&format!("β vibe-setting failed: {e}; nothing written")),+ Ok(VibeOutcome::Ask(question)) => {+ app.note(&format!("β vibe-setting needs more detail: {question}"));+ app.system_detail_text("run /vibe-setting again with the answer; nothing written");+ }+ Ok(VibeOutcome::Nothing { refused, note }) => {+ app.note("β vibe-setting Β· nothing to change; nothing written");+ for line in refused {+ app.system_detail_text(&format!("refused: {line}"));+ }+ if let Some(note) = note {+ app.system_detail_text(¬e);+ }+ }+ Ok(VibeOutcome::Propose(proposal)) => app.vibe_confirm = Some(proposal),+ }+}++/// Keys for the confirm dock. `y` applies, `n`/Enter/Esc cancel ([y/N]); a+/// proposal that widens tool permissions needs `yes` typed and Enter.+pub(super) fn handle_key(app: &mut App, key: KeyEvent, ctrl: bool) {+ let Some(proposal) = app.vibe_confirm.as_mut() else {+ return;+ };+ let cancel = key.code == KeyCode::Esc || (ctrl && key.code == KeyCode::Char('c'));+ if cancel {+ app.vibe_confirm = None;+ app.note("β vibe-setting Β· cancelled; nothing written");+ return;+ }+ if !proposal.widens.is_empty() {+ match key.code {+ KeyCode::Enter => {+ if proposal.typed.trim().eq_ignore_ascii_case("yes") {+ apply(app);+ } else {+ proposal.error = Some("type yes to apply, or Esc to cancel".to_string());+ }+ }+ KeyCode::Backspace => {+ proposal.typed.pop();+ }+ KeyCode::Char(ch) if !ctrl => proposal.typed.push(ch),+ _ => {}+ }+ return;+ }+ match key.code {+ KeyCode::Char('y') | KeyCode::Char('Y') => apply(app),+ KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Enter => {+ app.vibe_confirm = None;+ app.note("β vibe-setting Β· cancelled; nothing written");+ }+ _ => {}+ }+}++/// Write every change through the `/settings` writer, then report which took+/// effect now, which `/reload config` applies, and which wait for a restart.+fn apply(app: &mut App) {+ let Some(proposal) = app.vibe_confirm.take() else {+ return;+ };+ let toml_path = app.agent_dir.join("agent.toml");+ let mut written: Vec<String> = Vec::new();+ let mut live: Vec<String> = Vec::new();+ let mut reloadable: Vec<String> = Vec::new();+ let mut restart: Vec<String> = Vec::new();+ let mut failed: Vec<String> = Vec::new();+ for change in &proposal.changes {+ match write_setting(change.def, &toml_path, change.item.clone()) {+ Ok(()) => {+ let now_live = match &change.new_value {+ Some(value) => apply_live_setting(change.def, value),+ None => apply_live_unset(change.def),+ };+ let key = change.def.key.to_string();+ if now_live {+ live.push(key);+ } else if RELOAD_CONFIG_KEYS.contains(&change.def.key) {+ reloadable.push(key);+ } else {+ restart.push(key);+ }+ written.push(match &change.new_value {+ Some(value) => format!("{} = {value}", change.def.key),+ None => format!("{} unset (default applies)", change.def.key),+ });+ }+ Err(e) => failed.push(format!(+ "{}: failed to write {}: {e}",+ change.def.key,+ setting_path(change.def, &toml_path)+ )),+ }+ }+ let when = apply_when(&live, &reloadable, &restart);+ if !written.is_empty() {+ app.note(&format!(+ "β vibe-setting Β· wrote {} setting(s); {when}",+ written.len()+ ));+ for line in written {+ app.system_detail_text(&line);+ }+ }+ for line in failed {+ app.note(&format!("β vibe-setting Β· {line}"));+ }+}++/// The "when does it apply" half of the result note, one clause per bucket.+fn apply_when(live: &[String], reloadable: &[String], restart: &[String]) -> String {+ let mut parts: Vec<String> = Vec::new();+ if !live.is_empty() {+ parts.push(format!("{} in effect now", live.join(", ")));+ }+ if !reloadable.is_empty() {+ parts.push(format!("run /reload config to apply {}", reloadable.join(", ")));+ }+ if !restart.is_empty() {+ let verb = if restart.len() == 1 { "applies" } else { "apply" };+ parts.push(format!("{} {verb} when jan restarts", restart.join(", ")));+ }+ parts.join("; ")+}++fn shown(def: &AgentSettingDef, value: Option<&str>) -> String {+ match value {+ Some("") if matches!(def.kind, AgentSettingKind::Glyph { .. }) => "\"\" (off)".to_string(),+ Some(v) => v.to_string(),+ None => format!("default ({})", kind_text(def).1),+ }+}++/// The dock's contents at `width`: the diff grouped by file, what was refused,+/// the permission warning, and the confirmation line.+pub(super) fn lines(proposal: &VibeProposal, width: u16) -> Vec<Line<'static>> {+ let dim = Style::new().dark_gray();+ let max = width.max(1) as usize;+ let mut out: Vec<Line<'static>> = Vec::new();+ let mut push = |spans: Vec<Span<'static>>| {+ out.extend(wrap_spans_hard(spans, max).into_iter().map(Line::from));+ };+ let key_width = proposal+ .changes+ .iter()+ .map(|c| c.def.key.chars().count())+ .max()+ .unwrap_or_default();+ for scope in [SettingScope::Project, SettingScope::Global] {+ let rows: Vec<&VibeChange> = proposal+ .changes+ .iter()+ .filter(|c| c.def.scope == scope)+ .collect();+ if rows.is_empty() {+ continue;+ }+ push(vec![Span::styled(file_label(scope), Style::new().bold())]);+ for change in rows {+ let mut spans = vec![+ Span::raw(format!(" {:<key_width$} ", change.def.key)),+ Span::styled(shown(change.def, change.current.as_deref()), dim),+ Span::raw(" -> "),+ Span::styled(+ shown(change.def, change.new_value.as_deref()),+ Style::new().cyan(),+ ),+ ];+ if !change.reason.is_empty() {+ spans.push(Span::styled(format!(" {}", change.reason), dim));+ }+ push(spans);+ }+ }+ for line in &proposal.refused {+ push(vec![Span::styled(+ format!("refused: {line}"),+ Style::new().yellow(),+ )]);+ }+ if let Some(note) = &proposal.note {+ push(vec![Span::styled(note.clone(), dim)]);+ }+ if proposal.widens.is_empty() {+ push(vec![Span::styled(+ "Apply? [y/N]",+ Style::new().bold(),+ )]);+ } else {+ push(vec![Span::styled(+ format!(+ "This widens tool permissions ({}): tools may run without asking.",+ proposal.widens.join(", ")+ ),+ Style::new().red().bold(),+ )]);+ push(vec![+ Span::styled("Type yes to apply: ", Style::new().bold()),+ Span::raw(proposal.typed.clone()),+ ]);+ }+ if let Some(error) = &proposal.error {+ push(vec![Span::styled(error.clone(), Style::new().red())]);+ }+ out+}++pub(super) fn draw(f: &mut Frame, area: Rect, proposal: &VibeProposal) {+ use ratatui::widgets::Clear;+ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(Style::new().cyan())+ .title(Span::styled(+ " vibe-setting: proposed changes ",+ Style::new().on_cyan().black().bold(),+ ));+ f.render_widget(Clear, area);+ let inner = block.inner(area);+ f.render_widget(block, area);+ f.render_widget(Paragraph::new(lines(proposal, inner.width)), inner);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn apply_when_names_each_bucket() {+ let v = |xs: &[&str]| xs.iter().map(|x| x.to_string()).collect::<Vec<_>>();+ assert_eq!(apply_when(&v(&["wave"]), &[], &[]), "wave in effect now");+ assert_eq!(+ apply_when(&[], &v(&["context_window", "max_tokens"]), &[]),+ "run /reload config to apply context_window, max_tokens"+ );+ assert_eq!(+ apply_when(&[], &[], &v(&["show_reasoning", "tools.default"])),+ "show_reasoning, tools.default apply when jan restarts"+ );+ assert_eq!(+ apply_when(&v(&["wave"]), &v(&["max_tokens"]), &v(&["show_reasoning"])),+ "wave in effect now; run /reload config to apply max_tokens; show_reasoning applies when jan restarts"+ );+ }++ fn unset(_: &AgentSettingDef) -> Option<String> {+ None+ }++ fn propose(reply: &str, current: &dyn Fn(&AgentSettingDef) -> Option<String>) -> VibeProposal {+ match interpret_reply(reply, current).expect("a valid reply") {+ VibeOutcome::Propose(p) => p,+ VibeOutcome::Ask(q) => panic!("asked instead: {q}"),+ VibeOutcome::Nothing { refused, .. } => panic!("nothing proposed: {refused:?}"),+ }+ }++ /// The request carries the catalog with current values and nothing else:+ /// no credentials row, and the user's words as the only user message.+ #[test]+ fn the_request_carries_only_the_catalog_and_the_words() {+ let body = build_request("m", "show me its thinking", &|def| {+ (def.key == "context_window").then(|| "200000".to_string())+ });+ let system = body["messages"][0]["content"].as_str().unwrap();+ assert!(system.contains("- context_window | project | integer >= 1 | 128000 | 200000 |"));+ assert!(system.contains("- wave | global |"));+ assert!(!system.contains("claude_code_alias"), "{system}");+ assert_eq!(body["messages"][1]["content"], "show me its thinking");+ assert_eq!(body["messages"].as_array().unwrap().len(), 2);+ }++ /// The issue's own example parses into a three-row diff, JSON wrapped in+ /// prose included.+ #[test]+ fn parses_the_issue_example() {+ let reply = r#"Here you go:+```json+{"changes": [+ {"key": "context_window", "scope": "project", "new_value": 1000000, "reason": "Opus has 1M"},+ {"key": "compaction_ratio", "scope": "project", "new_value": 0.9, "reason": "compact later"},+ {"key": "show_reasoning", "scope": "project", "new_value": true, "reason": "show thinking"}+], "question": null}+```"#;+ let current = |def: &AgentSettingDef| match def.key {+ "context_window" => Some("128000".to_string()),+ "compaction_ratio" => Some("0.8".to_string()),+ _ => None,+ };+ let p = propose(reply, ¤t);+ let keys: Vec<&str> = p.changes.iter().map(|c| c.def.key).collect();+ assert_eq!(keys, ["context_window", "compaction_ratio", "show_reasoning"]);+ assert_eq!(p.changes[0].new_value.as_deref(), Some("1000000"));+ assert!(p.refused.is_empty() && p.widens.is_empty());+ let text: String = lines(&p, 120)+ .iter()+ .flat_map(|l| l.spans.iter().map(|s| s.content.to_string()))+ .collect::<Vec<_>>()+ .join("");+ assert!(text.contains("agent.toml (this project)"), "{text}");+ assert!(text.contains("128000 -> 1000000"), "{text}");+ assert!(text.contains("Apply? [y/N]"), "{text}");+ }++ /// Every value goes through the `/settings` parser: out of range, wrong+ /// type, unknown key, credential key and duplicates are refused with a+ /// reason, and the valid rest is still proposed.+ #[test]+ fn invalid_entries_are_refused_with_a_reason() {+ let reply = r#"{"changes": [+ {"key": "compaction_ratio", "new_value": 1.5},+ {"key": "max_parallel_subagents", "new_value": "lots"},+ {"key": "api_key", "new_value": "sk-123"},+ {"key": "claude_code_alias", "new_value": false},+ {"key": "tools.default", "new_value": "yolo"},+ {"key": "max_parallel_subagents", "new_value": 4},+ {"key": "max_parallel_subagents", "new_value": 5},+ {"key": "show_reasoning", "new_value": [true]},+ {"key": "send_reasoning"}+ ]}"#;+ let p = propose(reply, &unset);+ assert_eq!(p.changes.len(), 1, "only the valid entry");+ assert_eq!(p.changes[0].def.key, "max_parallel_subagents");+ assert_eq!(p.changes[0].new_value.as_deref(), Some("4"));+ let refused = p.refused.join("\n");+ for needle in [+ "compaction_ratio = 1.5: must be between",+ "max_parallel_subagents = lots: 'lots' is not an integer",+ "api_key: not a setting",+ "claude_code_alias: credential settings are never changed",+ "tools.default = yolo: must be one of",+ "max_parallel_subagents: listed twice",+ "show_reasoning: expected a single value",+ "send_reasoning: no new_value",+ ] {+ assert!(refused.contains(needle), "missing {needle:?} in:\n{refused}");+ }+ }++ /// Ambiguity asks back instead of guessing, even with changes attached.+ #[test]+ fn a_question_wins_over_changes() {+ let reply = r#"{"changes": [{"key": "max_tokens", "new_value": 512}],+ "question": "Faster as in a smaller model, or shorter replies?"}"#;+ match interpret_reply(reply, &unset).unwrap() {+ VibeOutcome::Ask(q) => assert!(q.contains("smaller model")),+ _ => panic!("must ask back"),+ }+ }++ /// A change to the value a key already has is no change; with nothing+ /// left, nothing is proposed.+ #[test]+ fn no_op_changes_are_dropped() {+ let reply = r#"{"changes": [{"key": "compaction_ratio", "new_value": 0.90}],+ "note": "use /model to switch to Opus"}"#;+ let current = |def: &AgentSettingDef| {+ (def.key == "compaction_ratio").then(|| "0.9".to_string())+ };+ match interpret_reply(reply, ¤t).unwrap() {+ VibeOutcome::Nothing { refused, note } => {+ assert!(refused.is_empty());+ assert_eq!(note.as_deref(), Some("use /model to switch to Opus"));+ }+ _ => panic!("nothing to change"),+ }+ }++ /// `null` resets a key to its default: the change is an unset.+ #[test]+ fn null_resets_to_the_default() {+ let current = |def: &AgentSettingDef| {+ (def.key == "max_tokens").then(|| "4096".to_string())+ };+ let p = propose(r#"{"changes": [{"key": "max_tokens", "new_value": null}]}"#, ¤t);+ assert!(p.changes[0].new_value.is_none() && p.changes[0].item.is_none());+ }++ /// Loosening `tools.default` is flagged; tightening it is not.+ #[test]+ fn widening_tool_permissions_is_flagged() {+ let allow = r#"{"changes": [{"key": "tools.default", "new_value": "allow"}]}"#;+ assert_eq!(propose(allow, &unset).widens, ["tools.default"]);+ let deny = r#"{"changes": [{"key": "tools.default", "new_value": "deny"}]}"#;+ assert!(propose(deny, &unset).widens.is_empty());+ let from_deny = |def: &AgentSettingDef| {+ (def.key == "tools.default").then(|| "deny".to_string())+ };+ let reset = r#"{"changes": [{"key": "tools.default", "new_value": null}]}"#;+ assert_eq!(+ propose(reset, &from_deny).widens,+ ["tools.default"],+ "resetting deny to the read-only default loosens it"+ );+ }++ #[test]+ fn a_reply_that_is_not_json_is_an_error() {+ assert!(interpret_reply("sure, I set it for you", &unset).is_err());+ assert!(interpret_reply(r#"{"changes": "all of them"}"#, &unset).is_err());+ }+}