Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): add /reload config to re-apply agent.toml limits mid-session
thinhlpg195cd73b94ee
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdxindex 9c4f83619..888e51206 100644--- a/docs/src/pages/docs/agent/slash-commands.mdx+++ b/docs/src/pages/docs/agent/slash-commands.mdx@@ -66,11 +66,11 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-| `/effort [low\|medium\|high]` | Set reasoning effort. Bare: show current; `low` is faster, `high` thinks deeper || `/mcp` | List, toggle, add, edit, and remove MCP servers; Enter opens a server's detail screen, where you can list its tools and sign in to it || `/plugin [list\|install <spec>\|remove <name>\|search [query]]` | Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace |-| `/reload [plugin\|skills\|system-prompt]` | Re-scan skills/plugins from disk and rebuild the catalog mid-session (bare: `plugin`), reporting added/removed/changed entries. `system-prompt` re-reads `JAN.md` and applies on the next run |+| `/reload [config\|plugin\|skills\|system-prompt]` | Re-read on-disk state into the running session without a restart (bare: all). `config` re-applies the project's `agent.toml` limits - `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `send_reasoning`, `[budget].max_tokens` - to the next run and lists what changed; the model, `[tools]`, `[provider]` and `[budget].max_usd` still need a restart. `plugin`/`skills` re-scan and rebuild the catalog, reporting added/removed/changed entries. `system-prompt` re-reads `JAN.md`, which applies on the next run || `/login` | Sign in to Tokamak and save the API key || `/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 run, except cosmetic ones like `wave` that apply immediately |+| `/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 |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/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 4161f0eb2..2e3037cfd 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -767,7 +767,7 @@ use tokio::sync::{mpsc, Mutex};/// Advisory, not a bound: crossing it compacts the history and records a note,/// then the run carries on (see `body_session_budget`). `--max-turns` and/// cancellation are what actually stop a runaway loop.-const DEFAULT_MAX_SESSION_TOKENS: u64 = 128_000;+pub(crate) const DEFAULT_MAX_SESSION_TOKENS: u64 = 128_000;/// Where the session token ceiling in effect came from, so `agent status` can/// say which source won.@@ -1265,6 +1265,9 @@ pub(crate) struct SessionLimits {/// Advisory: crossing it triggers compaction and a recorded note, it does/// not end the run. `max_turns` is the hard bound.pub max_session_tokens: u64,+ /// Whether `--max-session-tokens` set `max_session_tokens`. A flag outranks+ /// `[budget].max_tokens`, so `/reload config` must leave a pinned value alone.+ pub max_session_tokens_pinned: bool,/// `--max-turns`: hard cap on agentic turns for this run, and the only/// setting that terminates one. `None` omits the field from the request/// body, which the engine reads as unbounded; `0` means unbounded too (see@@ -1736,6 +1739,7 @@ fn prepare_agent_session(flags.max_session_tokens,cfg.budget.max_tokens,),+ max_session_tokens_pinned: flags.max_session_tokens.is_some(),max_turns: flags.max_turns,cost_ceiling,},@@ -4436,6 +4440,7 @@ mod tests {compaction_reserve_tokens: None,max_tokens: None,max_session_tokens,+ max_session_tokens_pinned: false,max_turns,cost_ceiling: None,}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex d326c5925..9b677f1a1 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -1854,6 +1854,9 @@ struct App {/// Token-spend ceiling for one message's run; `0` is unbounded. Advisory:/// crossing it compacts and files a note rather than stopping the run.max_session_tokens: u64,+ /// `--max-session-tokens` pinned `max_session_tokens`, so `/reload config`+ /// does not replace it with `[budget].max_tokens`.+ max_session_tokens_pinned: bool,/// `[budget].max_usd`: what one message's run may spend before it stops,/// with the rates to meter it against. `None` -- the default -- leaves the/// session unmetered. Per run, not per session: each message gets the same@@ -2620,6 +2623,7 @@ impl App {compaction_reserve_tokens: limits.compaction_reserve_tokens,max_tokens: limits.max_tokens,max_session_tokens: limits.max_session_tokens,+ max_session_tokens_pinned: limits.max_session_tokens_pinned,cost_ceiling: limits.cost_ceiling,repo_root,git_branch: git::current_branch(&project_root),@@ -4970,8 +4974,37 @@ impl App {let changed = resolved.tokens != self.context_window;self.context_window = resolved.tokens;self.context_window_source = resolved.source;+ self.sync_compaction_budget();changed}++ /// Hand the engine the compaction budget the TUI now shows. The loop's+ /// preflight reads `args.compaction`, a copy taken at startup, so without+ /// this a model switch or `/reload config` would move the header gauge+ /// while runs kept compacting against the startup window. `args` is shared+ /// behind an `Arc`; a cheap clone with the new budget replaces it, and the+ /// next run spawned from `self.args` picks it up.+ fn sync_compaction_budget(&mut self) {+ let Some(args) = self.args.as_ref() else {+ return;+ };+ let budget = crate::core::agent::compaction::CompactionBudget {+ context_window: self.context_window,+ ratio: self.compaction_ratio,+ reserve_tokens: self.compaction_reserve_tokens,+ };+ let unchanged = args.compaction.is_some_and(|b| {+ b.context_window == budget.context_window+ && b.ratio == budget.ratio+ && b.reserve_tokens == budget.reserve_tokens+ });+ if unchanged {+ return;+ }+ let mut next = (**args).clone();+ next.compaction = Some(budget);+ self.args = Some(Arc::new(next));+ }/// Mark the memoized model -> provider answer as needing re-resolution/// while keeping the answer itself. The value survives because/// [`Self::serving_provider`] falls back to it when the provider-config@@ -9953,7 +9986,9 @@ async fn chat_loop<B: Backend>(// flight, and the result replaces `history` wholesale.if compact_task.is_none() {if let Some(kind) = app.compact_request.take() {- let args = args.clone();+ // `app.args`, not the startup handle: it carries the budget a+ // model switch or `/reload config` last synced.+ let args = app.args.clone().unwrap_or_else(|| args.clone());let model = app.model.clone();let history = app.history.clone();compact_base = history.len();@@ -9992,7 +10027,8 @@ async fn chat_loop<B: Backend>(// The submission itself is one human turn toward the aging// grace period; model roundtrips count via `Step` events.age_closed_todos(app).await;- current = Some(spawn_run(args, app.body()));+ let run_args = app.args.clone().unwrap_or_else(|| args.clone());+ current = Some(spawn_run(&run_args, app.body()));} else if !loading_noted && !mcp_ready {// The base snapshot gates silently; only the MCP connect notes.loading_noted = true;@@ -12159,8 +12195,8 @@ const SLASH_COMMANDS: &[SlashCommand] = &[},SlashCommand {name: "/reload",- hint: "[plugin|skills|system-prompt]",- description: "Re-scan skills/plugins from disk and rebuild the catalog mid-session (bare: plugin)",+ hint: "[config|plugin|skills|system-prompt]",+ description: "Re-read agent.toml, skills, plugins and JAN.md without restarting (bare: all)",alias_of: None,},SlashCommand {@@ -14518,54 +14554,144 @@ fn diff_reload_entries((added, removed, updated)}-/// `/reload [plugin|skills|system-prompt]`: re-run skill/plugin discovery and-/// rebuild the slash catalog mid-session, reporting added/removed/changed-/// entries. Bare `/reload` targets plugins — the payload an install most-/// often changes. The model-facing system prompt (JAN.md instructions, the-/// skills catalog) is rebuilt from disk on every run, so the `system-prompt`-/// target re-reads and reports what the next run picks up.+/// `/reload [config|plugin|skills|system-prompt]`: re-read on-disk state into+/// the running session instead of restarting it. `config` re-applies the+/// project's `agent.toml` limits (context window, compaction, output cap,+/// token budget) and reports each value that moved; `plugin`/`skills` re-run+/// discovery and rebuild the slash catalog, reporting added/removed/changed+/// entries. The model-facing system prompt (JAN.md instructions, the skills+/// catalog) is rebuilt from disk on every run, so `system-prompt` re-reads and+/// reports what the next run picks up. Bare `/reload` does all of them.fn reload_command(app: &mut App, arg: &str) {- let root = app.project_root.clone();match arg.trim() {- "" | "plugin" | "plugins" => {- let before = reload_plugin_entries(&app.slash_catalog.plugins);- app.refresh_slash_catalog();- let after = reload_plugin_entries(&app.slash_catalog.plugins);- app.note("◈ reload · plugin · re-scanned installed plugins");- report_reload_diff(app, diff_reload_entries(&before, &after));- }- "skill" | "skills" => {- let before = reload_skill_entries(&app.slash_catalog.all_skills);- app.refresh_slash_catalog();- let after = reload_skill_entries(&app.slash_catalog.all_skills);- app.note("◈ reload · skills · re-scanned project and plugin skills");- report_reload_diff(app, diff_reload_entries(&before, &after));- }- "system-prompt" => {- // Nothing caches the instructions across runs: the system prompt- // (including this block and the skills catalog) is rebuilt from- // disk at the start of every run. Re-read now to confirm what the- // next run will pick up.- let files = crate::core::agent::context::context_files(&root);- if files.is_empty() {- app.note("◈ reload · system-prompt · no JAN.md in this project or its ancestors");- return;- }- app.note("◈ reload · system-prompt · re-read project instructions (applies next run)");- for (path, content) in &files {- app.system_detail_text(&format!(- " {} ({} bytes)",- path.display(),- content.len()- ));- }- }+ "" | "all" => {+ reload_config(app);+ reload_plugins(app);+ reload_skills(app);+ reload_system_prompt(app);+ }+ "config" | "settings" => reload_config(app),+ "plugin" | "plugins" => reload_plugins(app),+ "skill" | "skills" => reload_skills(app),+ "system-prompt" => reload_system_prompt(app),other => app.note(&format!(- "unknown /reload target '{other}' (try plugin | skills | system-prompt)"+ "unknown /reload target '{other}' (try config | plugin | skills | system-prompt)")),}}+fn reload_plugins(app: &mut App) {+ let before = reload_plugin_entries(&app.slash_catalog.plugins);+ app.refresh_slash_catalog();+ let after = reload_plugin_entries(&app.slash_catalog.plugins);+ app.note("◈ reload · plugin · re-scanned installed plugins");+ report_reload_diff(app, diff_reload_entries(&before, &after));+}++fn reload_skills(app: &mut App) {+ let before = reload_skill_entries(&app.slash_catalog.all_skills);+ app.refresh_slash_catalog();+ let after = reload_skill_entries(&app.slash_catalog.all_skills);+ app.note("◈ reload · skills · re-scanned project and plugin skills");+ report_reload_diff(app, diff_reload_entries(&before, &after));+}++fn reload_system_prompt(app: &mut App) {+ // Nothing caches the instructions across runs: the system prompt+ // (including this block and the skills catalog) is rebuilt from disk at+ // the start of every run. Re-read now to confirm what the next run picks up.+ let files = crate::core::agent::context::context_files(&app.project_root);+ if files.is_empty() {+ app.note("◈ reload · system-prompt · no JAN.md in this project or its ancestors");+ return;+ }+ app.note("◈ reload · system-prompt · re-read project instructions (applies next run)");+ for (path, content) in &files {+ app.system_detail_text(&format!(" {} ({} bytes)", path.display(), content.len()));+ }+}++/// Re-read the project's `agent.toml` and apply the `[agent]`/`[budget]`+/// limits the session snapshotted at startup, using the same precedence the+/// startup path does (`prepare_agent_session`): a provider's own+/// `compaction_ratio` beats the project's, and a `--max-session-tokens` flag+/// beats `[budget].max_tokens`. The next run spawned gets the new compaction+/// budget via [`App::sync_compaction_budget`]; a run already in flight keeps+/// the one it started with.+///+/// Not reloaded: the model (switch it with `/model`), `[tools]` permissions+/// and `[provider]`, which are wired into the session's tools and routes at+/// startup, and `[budget].max_usd`, whose rates are priced once at startup.+fn reload_config(app: &mut App) {+ let cfg = match crate::core::agent::project::load_agent_config(&app.project_root) {+ Ok(cfg) => cfg,+ Err(e) => {+ app.note(&format!("◈ reload · config · {e}; kept the current settings"));+ return;+ }+ };+ let before = reload_config_entries(app);++ app.configured_context_window = cfg.agent.context_window;+ let provider_ratio = app.args.as_ref().and_then(|args| {+ let pc = args.provider_configs.try_lock().ok()?;+ crate::core::agent::upstream::pick_provider_for_model(&app.model, &pc)+ .and_then(|name| pc.get(&name)?.compaction_ratio)+ });+ app.compaction_ratio = provider_ratio+ .or(cfg.agent.compaction_ratio)+ .unwrap_or(crate::core::agent::compaction::DEFAULT_COMPACTION_RATIO);+ app.compaction_reserve_tokens = cfg.agent.compaction_reserve_tokens;+ app.max_tokens = cfg.agent.max_tokens;+ if !app.max_session_tokens_pinned {+ app.max_session_tokens = cfg+ .budget+ .max_tokens+ .unwrap_or(super::DEFAULT_MAX_SESSION_TOKENS);+ }+ app.send_reasoning = cfg.agent.send_reasoning.unwrap_or(true);+ // Re-resolves the window and pushes the compaction budget to the engine.+ app.refresh_context_window();++ let after = reload_config_entries(app);+ app.note(&format!(+ "◈ reload · config · re-read {}",+ crate::core::agent::project::agent_toml_path(&app.project_root).display()+ ));+ report_reload_diff(app, diff_reload_entries(&before, &after));+ if app.max_session_tokens_pinned {+ app.system_detail_text(" budget.max_tokens ignored: --max-session-tokens was passed");+ }+ if app.should_auto_compact() {+ app.compact_request = Some(CompactKind::Auto);+ app.system_detail_text(" context now over the compaction trigger; compacting");+ }+}++/// The reloadable limits as diffable entries, so `/reload config` reports+/// exactly the values that moved.+fn reload_config_entries(app: &App) -> Vec<ReloadEntry> {+ fn entry(key: &str, state: String) -> ReloadEntry {+ ReloadEntry {+ key: key.to_string(),+ label: key.to_string(),+ state,+ }+ }+ let opt = |v: Option<u64>| v.map_or_else(|| "unset".to_string(), |v| v.to_string());+ vec![+ entry(+ "context_window",+ format!("{} ({})", app.context_window, app.context_window_source.label()),+ ),+ entry("compaction_ratio", app.compaction_ratio.to_string()),+ entry("compaction_reserve_tokens", opt(app.compaction_reserve_tokens)),+ entry("max_tokens", opt(app.max_tokens)),+ entry("budget.max_tokens", app.max_session_tokens.to_string()),+ entry("send_reasoning", app.send_reasoning.to_string()),+ ]+}+/// Print a reload diff, or the unchanged note when the scan found nothing new.fn report_reload_diff(app: &mut App,@@ -20068,6 +20194,7 @@ mod tests {compaction_reserve_tokens: Some(16_384),max_tokens: None,max_session_tokens: 128_000,+ max_session_tokens_pinned: false,max_turns: None,cost_ceiling: None,};@@ -20574,6 +20701,7 @@ mod tests {compaction_reserve_tokens: Some(16_384),max_tokens: None,max_session_tokens: 128_000,+ max_session_tokens_pinned: false,max_turns: None,cost_ceiling: None,},@@ -36975,7 +37103,8 @@ mod tests {/// to report.fn plugin_manifest_in_app(root: &std::path::Path, plugin: &str, version: &str) {std::fs::write(- root.join(".jan/agent/plugins")+ crate::core::agent::project::store_root(root)+ .join("plugins").join(plugin).join("plugin.toml"),format!("name = \"{plugin}\"\nversion = \"{version}\"\n"),@@ -36986,8 +37115,8 @@ mod tests {#[tokio::test]async fn reload_bare_defaults_to_plugin_and_reports_changes() {let (mut app, root) = skill_test_app("deploy", "How to deploy.");- // Bare /reload targets plugins; nothing installed, nothing changed.- run_command(&mut app, "reload", &no_mcp()).await;+ // Bare /reload covers plugins; nothing installed, nothing changed.+ run_command(&mut app, "reload plugin", &no_mcp()).await;let out = transcript_text(&app);assert!(out.contains("re-scanned installed plugins"),@@ -37025,7 +37154,7 @@ mod tests {run_command(&mut app, "reload skills", &no_mcp()).await;assert!(transcript_text(&app).contains("no changes since the last scan"));- let skills = root.join(".jan/agent/skills");+ let skills = crate::core::agent::project::store_root(&root).join("skills");// Added: a new skill shows up and joins the popup catalog.std::fs::create_dir_all(skills.join("audit")).unwrap();@@ -37089,6 +37218,107 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ #[tokio::test]+ async fn reload_bare_covers_every_target() {+ let (mut app, root) = skill_test_app("deploy", "How to deploy.");+ run_command(&mut app, "reload", &no_mcp()).await;+ let out = transcript_text(&app);+ for want in [+ "reload · config",+ "reload · plugin",+ "reload · skills",+ "reload · system-prompt",+ ] {+ assert!(out.contains(want), "missing {want}: {out}");+ }+ let _ = std::fs::remove_dir_all(&root);+ }++ fn write_agent_toml(root: &std::path::Path, body: &str) {+ let path = crate::core::agent::project::agent_toml_path(root);+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, body).unwrap();+ }++ #[tokio::test]+ async fn reload_config_applies_agent_toml_limits_live() {+ let (mut app, root) = skill_test_app("deploy", "How to deploy.");+ write_agent_toml(+ &root,+ "[agent]\ncontext_window = 300000\ncompaction_ratio = 0.7\nmax_tokens = 8192\n\n[budget]\nmax_tokens = 0\n",+ );+ run_command(&mut app, "reload config", &no_mcp()).await;+ assert_eq!(app.context_window, 300_000);+ assert_eq!(app.configured_context_window, Some(300_000));+ assert_eq!(+ app.context_window_source,+ crate::core::cli::model_capabilities::ContextWindowSource::Configured+ );+ assert_eq!(app.compaction_ratio, 0.7);+ assert_eq!(app.max_tokens, Some(8192));+ assert_eq!(app.max_session_tokens, 0);+ assert_eq!(app.body()["max_tokens"], 8192);+ let out = transcript_text(&app);+ assert!(out.contains("~ context_window (128000"), "diff: {out}");+ assert!(out.contains("→ 300000"), "diff: {out}");++ // Unchanged file: nothing to report.+ run_command(&mut app, "reload config", &no_mcp()).await;+ assert!(transcript_text(&app).ends_with("no changes since the last scan"));++ // Removing the override falls back to the catalog/fallback window.+ write_agent_toml(&root, "[agent]\n");+ run_command(&mut app, "reload config", &no_mcp()).await;+ assert_eq!(app.configured_context_window, None);+ assert_eq!(app.context_window, 128_000);+ assert_eq!(app.max_tokens, None);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn reload_config_keeps_settings_on_a_malformed_file() {+ let (mut app, root) = skill_test_app("deploy", "How to deploy.");+ write_agent_toml(&root, "[agent\ncontext_window = 300000\n");+ run_command(&mut app, "reload config", &no_mcp()).await;+ assert_eq!(app.context_window, 128_000);+ assert!(+ transcript_text(&app).contains("kept the current settings"),+ "{}",+ transcript_text(&app)+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn reload_config_respects_a_pinned_session_budget() {+ let (mut app, root) = skill_test_app("deploy", "How to deploy.");+ app.max_session_tokens = 42;+ app.max_session_tokens_pinned = true;+ write_agent_toml(&root, "[budget]\nmax_tokens = 999\n");+ run_command(&mut app, "reload config", &no_mcp()).await;+ assert_eq!(app.max_session_tokens, 42, "--max-session-tokens outranks the file");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn reload_config_hands_the_new_window_to_the_engine() {+ let (mut app, root) = skill_test_app("deploy", "How to deploy.");+ let args = test_args(&app, std::collections::HashMap::new());+ app.args = Some(args.clone());+ write_agent_toml(&root, "[agent]\ncontext_window = 300000\n");+ run_command(&mut app, "reload config", &no_mcp()).await;+ let budget = app+ .args+ .as_ref()+ .and_then(|a| a.compaction)+ .expect("compaction budget synced to the run args");+ assert_eq!(budget.context_window, 300_000);+ assert_eq!(budget.ratio, app.compaction_ratio);+ // The shared session args are untouched; only new runs see the swap.+ assert!(!Arc::ptr_eq(app.args.as_ref().unwrap(), &args));+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn slash_commands_include_reload() {assert!(SLASH_COMMANDS.iter().any(|c| c.name == "/reload"));