Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): subagent model roles and per-subagent model settings

Akarshan Biswas7c8bdb6a9ae4
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 88d1ed91e..854878e8e 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -16,8 +16,9 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.
# agent.toml [provider] section (~/.jan/projects/<project>/agent.toml).
#
# default_model = "my-model" # used when no --model / agent.toml model is set
-# smol_model = "my-fast-model" # fast model for the `smol` role (/goal evaluation);
-# # defaults to `default_model` when unset
+# smol_model = "my-fast-model" # fast model for the `smol` role (/goal evaluation and
+# # subagents with model = "smol"); defaults to the
+# # session's model when unset
# mouse = false # disable TUI mouse tracking (scroll wheel,
# # click-to-expand); on by default
# sandbox = true # run `shell` under OS confinement (same as
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index cfed3120a..374bae234 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -1459,6 +1459,7 @@ impl CompositeToolInvoker {
plan,
&crate::core::agent::subagent::ParentRun {
model: ctx.model_id.clone(),
+ smol_model: crate::core::agent::subagent::configured_smol_model(),
budget_remaining: ctx.max_session_tokens,
send_reasoning: ctx.send_reasoning,
cost_remaining: ctx.cost_ceiling,
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index 5bb39690c..af1d85b96 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -42,6 +42,21 @@ pub(crate) struct AgentToml {
/// `[hooks]` map because several hooks may share one event.
#[serde(default)]
pub hooks: Vec<tauri_plugin_agent_tools::tools::hooks::HookEntry>,
+ /// `[subagents.<name>]` -- per-project overrides of saved subagent
+ /// definitions, keyed by definition name.
+ #[serde(default)]
+ pub subagents: BTreeMap<String, SubagentOverride>,
+}
+
+/// One `[subagents.<name>]` table. Lets a project move a definition it does
+/// not own (a user-wide or plugin agent) to another model without editing the
+/// definition's file.
+#[derive(Debug, Clone, Default, Deserialize)]
+pub(crate) struct SubagentOverride {
+ /// Replaces the definition's `model`: a role (`smol`, `inherit`) or a
+ /// literal model id. Blank is ignored.
+ #[serde(default)]
+ pub model: Option<String>,
}
/// `[prompt]` — where each contributor to the system prompt may sit. Deny-wins,
@@ -370,6 +385,12 @@ allow_write = []
[skills]
enabled = []
+# Per-project model for a saved subagent, overriding its definition's own.
+# A model id, "smol" (smol_model in ~/.jan/config.toml) or "inherit" (this
+# session's model). /settings > subagents edits these.
+# [subagents.explorer]
+# model = "smol"
+
# Where each contributor to the system prompt may sit, deny-wins like [tools].
# Above the cache line ("prefix") a contributor must be constant for the whole
# session: a provider only reuses a prefix whose bytes are identical to the
@@ -673,6 +694,70 @@ pub(crate) fn set_model_in_agent_toml(path: &Path, model: &str) -> Result<(), St
.map_err(|e| format!("Failed to write {}: {e}", path.display()))
}
+/// Persist `[subagents.<name>].model` into the agent.toml at `path`,
+/// format-preserving. `None` removes the key, and the table with it once
+/// empty, so the definition's own model applies again. A dedicated writer
+/// rather than [`set_agent_key`]: a definition name may itself be any
+/// `[A-Za-z0-9_-]` string, so `subagents.<name>.model` cannot be split on dots.
+#[cfg(feature = "cli")]
+pub(crate) fn set_subagent_model(
+ path: &Path,
+ name: &str,
+ model: Option<&str>,
+) -> Result<(), String> {
+ let raw = match std::fs::read_to_string(path) {
+ Ok(raw) => raw,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
+ Err(e) => return Err(format!("Failed to read {}: {e}", path.display())),
+ };
+ let mut doc = raw
+ .parse::<toml_edit::DocumentMut>()
+ .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
+
+ match model.map(str::trim).filter(|m| !m.is_empty()) {
+ Some(model) => {
+ let subagents = doc["subagents"].or_insert(toml_edit::table());
+ // Dotted headers (`[subagents.explorer]`) rather than an empty
+ // `[subagents]` header above them. A hand-written inline table is
+ // edited in place instead, in whatever shape the user chose.
+ if let Some(table) = subagents.as_table_mut() {
+ table.set_implicit(true);
+ }
+ let subagents = subagents
+ .as_table_like_mut()
+ .ok_or_else(|| format!("{}: `subagents` is not a table", path.display()))?;
+ if subagents.get(name).is_none() {
+ subagents.insert(name, toml_edit::table());
+ }
+ let entry = subagents
+ .get_mut(name)
+ .and_then(|e| e.as_table_like_mut())
+ .ok_or_else(|| format!("{}: `subagents.{name}` is not a table", path.display()))?;
+ entry.insert("model", toml_edit::value(model));
+ }
+ None => {
+ if let Some(subagents) = doc.get_mut("subagents").and_then(|t| t.as_table_like_mut()) {
+ if let Some(entry) = subagents.get_mut(name).and_then(|t| t.as_table_like_mut()) {
+ entry.remove("model");
+ if entry.is_empty() {
+ subagents.remove(name);
+ }
+ }
+ if subagents.is_empty() {
+ doc.remove("subagents");
+ }
+ }
+ }
+ }
+
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)
+ .map_err(|e| format!("Failed to create {}: {e}", parent.display()))?;
+ }
+ std::fs::write(path, doc.to_string())
+ .map_err(|e| format!("Failed to write {}: {e}", path.display()))
+}
+
/// Persist a scalar key into the agent.toml at `path`, format-preserving
/// (comments kept). Keys are `section.key` with `agent` the default section,
/// so the `/settings` menu can reach `[agent]`, `[budget]`, `[tools]` and
@@ -1019,6 +1104,44 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ /// The `/settings` subagent-model writer round-trips through the parser,
+ /// keeps the rest of the file, and unsetting the last override removes the
+ /// table rather than leaving an empty `[subagents]` header behind.
+ #[cfg(feature = "cli")]
+ #[test]
+ fn subagent_model_override_round_trips_and_unsets_cleanly() {
+ let root = unique_root("subagent_model");
+ ensure_project(&root).expect("scaffold");
+ let path = agent_toml_path(&root);
+
+ set_subagent_model(&path, "explorer", Some("smol")).expect("write");
+ set_subagent_model(&path, "code-reviewer", Some("gpt-x")).expect("write");
+ let raw = std::fs::read_to_string(&path).unwrap();
+ assert!(raw.contains("[subagents.explorer]"), "{raw}");
+ assert!(raw.contains("[agent]"), "the rest of the file is kept: {raw}");
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.subagents["explorer"].model.as_deref(), Some("smol"));
+ assert_eq!(cfg.subagents["code-reviewer"].model.as_deref(), Some("gpt-x"));
+
+ set_subagent_model(&path, "explorer", None).expect("unset");
+ set_subagent_model(&path, "code-reviewer", Some(" ")).expect("blank unsets");
+ let raw = std::fs::read_to_string(&path).unwrap();
+ assert!(
+ !raw.lines().any(|l| l.starts_with("[subagents")),
+ "no live [subagents] header left: {raw}"
+ );
+ assert!(load_agent_config(&root).expect("load").subagents.is_empty());
+
+ // A hand-written inline entry is edited in place, not refused.
+ let raw = std::fs::read_to_string(&path).unwrap();
+ std::fs::write(&path, format!("{raw}\n[subagents]\nexplorer = {{ model = \"a\" }}\n"))
+ .unwrap();
+ set_subagent_model(&path, "explorer", Some("b")).expect("inline write");
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.subagents["explorer"].model.as_deref(), Some("b"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[cfg(feature = "cli")]
#[test]
fn max_parallel_subagents_parses_and_defaults_to_none() {
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index c353a6357..29faac8b2 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -129,6 +129,16 @@ impl SubagentRegistry {
/// agent of the same name. Malformed files are skipped with a warning
/// rather than failing the whole run.
pub fn load(project_root: &Path) -> Self {
+ let mut registry = Self::load_definitions(project_root);
+ apply_model_overrides(project_root, &mut registry.defs);
+ registry
+ }
+
+ /// [`load`](Self::load) without the project's `[subagents.<name>]`
+ /// overrides: each definition's model as its own file states it. The
+ /// `/settings` screen shows that next to the override, so a user can see
+ /// what clearing the override falls back to.
+ pub fn load_definitions(project_root: &Path) -> Self {
let mut defs = Vec::new();
load_plugin_agents(project_root, &mut defs);
if let Some(dir) = user_subagents_dir() {
@@ -247,6 +257,28 @@ impl SubagentRegistry {
}
}
+/// Apply the project's `[subagents.<name>] model` overrides from agent.toml.
+/// Every same-name entry is overridden, shadowed ones too, so `list` and `get`
+/// agree on the model a name dispatches on. An unreadable agent.toml
+/// overrides nothing: the run reports a malformed file on its own load, and a
+/// dispatch should not fail over a knob.
+fn apply_model_overrides(project_root: &Path, defs: &mut [SubagentDefinition]) {
+ let Ok(cfg) = crate::core::agent::project::load_agent_config(project_root) else {
+ return;
+ };
+ for def in defs.iter_mut() {
+ let model = cfg
+ .subagents
+ .get(&def.name)
+ .and_then(|o| o.model.as_deref())
+ .map(str::trim)
+ .filter(|m| !m.is_empty());
+ if let Some(model) = model {
+ def.model = Some(model.to_string());
+ }
+ }
+}
+
/// Load subagent definitions shipped by installed plugins as Markdown agent
/// files (`<plugin>/agents/**/*.md`, the Claude Code convention). Loaded
/// first so user/project TOML definitions shadow them by name. Frontmatter
@@ -1434,6 +1466,10 @@ impl Drop for AbortOnDrop {
#[derive(Clone)]
pub(crate) struct ParentRun {
pub(crate) model: String,
+ /// The configured `smol` role model a definition's `model = "smol"`
+ /// resolves to, or `None` when none is configured (the role then falls
+ /// back to `model`).
+ pub(crate) smol_model: Option<String>,
pub(crate) budget_remaining: Option<u64>,
pub(crate) send_reasoning: bool,
/// The parent's remaining money ceiling, or `None` when it meters none.
@@ -1460,15 +1496,42 @@ pub(crate) struct ParentRun {
pub(crate) known_tools: Vec<String>,
}
-/// The model a dispatch will actually be billed for: the definition's own when
-/// it names one, else the dispatching run's. Resolved in one place because the
-/// request body and the ceiling priced against it must not disagree.
+/// Definition `model` value naming the configured cheap model (`smol_model`).
+pub(crate) const SMOL_ROLE: &str = "smol";
+/// Definition `model` value naming the dispatching run's model, the same as
+/// leaving `model` unset.
+pub(crate) const INHERIT_ROLE: &str = "inherit";
+
+/// The model a dispatch will actually be billed for. A definition's `model` is
+/// either a role (`smol`, `inherit`) or a literal model id; no model, or a
+/// blank one, is the dispatching run's. Roles let a definition ask for "the
+/// cheap model" without naming one provider's id for it. Resolved in one place
+/// because the request body, the ceiling priced against it and the compaction
+/// window must not disagree.
fn child_model(resolved: &ResolvedDispatch, parent: &ParentRun) -> String {
- resolved
- .definition
- .model
- .clone()
- .unwrap_or_else(|| parent.model.clone())
+ match resolved.definition.model.as_deref().map(str::trim) {
+ None | Some("") | Some(INHERIT_ROLE) => parent.model.clone(),
+ Some(SMOL_ROLE) => parent
+ .smol_model
+ .clone()
+ .unwrap_or_else(|| parent.model.clone()),
+ Some(model) => model.to_string(),
+ }
+}
+
+/// The configured `smol` role model, read when a dispatch is made so a
+/// `/settings` change reaches the next dispatch without a restart. A malformed
+/// config reads as unset: the role then falls back to the parent's model, the
+/// same answer `/goal` evaluation gives.
+#[cfg(feature = "cli")]
+pub(crate) fn configured_smol_model() -> Option<String> {
+ crate::core::agent::global_config::smol_model().ok().flatten()
+}
+
+/// The desktop has no `~/.jan/config.toml`, so `smol` is the parent's model.
+#[cfg(not(feature = "cli"))]
+pub(crate) fn configured_smol_model() -> Option<String> {
+ None
}
/// The context window `model` resolves to, the way the CLI resolves a run's
@@ -2910,6 +2973,37 @@ pub(crate) mod tests {
assert!(spilled_text(&failed).starts_with("ERROR: "));
}
+ /// `[subagents.<name>] model` in the project's agent.toml outranks the
+ /// definition's own model, so a user can move a shipped or shared agent to
+ /// a cheaper model without editing its file. Unnamed agents are untouched.
+ #[test]
+ fn agent_toml_overrides_a_definitions_model() {
+ let root = unique_root("model_override");
+ let dir = project_subagents_dir(&root);
+ write_def(&dir, "explorer", "model = \"big\"\n");
+ write_def(&dir, "reviewer", "model = \"big\"\n");
+ let toml = crate::core::agent::project::agent_toml_path(&root);
+ std::fs::write(&toml, "[subagents.explorer]\nmodel = \"smol\"\n").unwrap();
+
+ let reg = SubagentRegistry::load(&root);
+ assert_eq!(reg.get("explorer").unwrap().model.as_deref(), Some("smol"));
+ assert_eq!(reg.get("reviewer").unwrap().model.as_deref(), Some("big"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A blank override is no override: the definition's own model stands.
+ #[test]
+ fn a_blank_override_keeps_the_definitions_model() {
+ let root = unique_root("blank_override");
+ write_def(&project_subagents_dir(&root), "explorer", "model = \"big\"\n");
+ let toml = crate::core::agent::project::agent_toml_path(&root);
+ std::fs::write(&toml, "[subagents.explorer]\nmodel = \" \"\n").unwrap();
+
+ let reg = SubagentRegistry::load(&root);
+ assert_eq!(reg.get("explorer").unwrap().model.as_deref(), Some("big"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[test]
fn empty_directories_yield_empty_registry() {
let root = unique_root("empty");
@@ -3296,6 +3390,7 @@ pub(crate) mod tests {
fn parent_run() -> ParentRun {
ParentRun {
model: "m".to_string(),
+ smol_model: None,
budget_remaining: None,
send_reasoning: true,
cost_remaining: None,
@@ -3399,6 +3494,74 @@ pub(crate) mod tests {
);
}
+ /// `reviewer` resolved against a registry whose definition names `model`.
+ fn resolved_on(model: Option<&str>) -> ResolvedDispatch {
+ let mut reg = registry_with("reviewer", None);
+ reg.defs[0].model = model.map(String::from);
+ resolve_dispatch_plain(&reg, &req("reviewer", None), &ToolPermissions::allow_all())
+ .expect("resolves")
+ }
+
+ /// `model = "smol"` names the user's cheap model without naming a provider's
+ /// id for it, so one definition keeps working across a provider switch.
+ #[test]
+ fn the_smol_role_runs_the_child_on_the_configured_smol_model() {
+ let parent = ParentRun {
+ smol_model: Some("cheap".to_string()),
+ ..parent_run()
+ };
+ let resolved = resolved_on(Some("smol"));
+ assert_eq!(child_model(&resolved, &parent), "cheap");
+ // The body is built from the same answer, so the request, its price and
+ // its compaction window all describe the model that actually runs.
+ assert_eq!(child_body(&resolved, "task", &parent)["model"], "cheap");
+ }
+
+ /// With no smol model configured the role falls back to the dispatching
+ /// run's model, the same fallback `/goal` evaluation uses, rather than
+ /// sending the literal `smol` upstream as a model id.
+ #[test]
+ fn the_smol_role_falls_back_to_the_parents_model_when_unset() {
+ assert_eq!(child_model(&resolved_on(Some("smol")), &parent_run()), "m");
+ }
+
+ /// `inherit` (or no model at all) is the parent's model; a literal id is
+ /// used as written.
+ #[test]
+ fn inherit_and_literal_models_resolve_as_named() {
+ let parent = ParentRun {
+ smol_model: Some("cheap".to_string()),
+ ..parent_run()
+ };
+ assert_eq!(child_model(&resolved_on(Some("inherit")), &parent), "m");
+ assert_eq!(child_model(&resolved_on(None), &parent), "m");
+ assert_eq!(child_model(&resolved_on(Some(" ")), &parent), "m");
+ assert_eq!(child_model(&resolved_on(Some("gpt-x")), &parent), "gpt-x");
+ }
+
+ /// A smol child under a cost ceiling is priced at the smol model's rates:
+ /// the alias resolves before pricing, so an unpriced smol model is refused
+ /// by name instead of being metered as the parent.
+ #[test]
+ fn a_smol_child_is_priced_as_the_resolved_model() {
+ let parent = ParentRun {
+ smol_model: Some("no-such-model-jan-test".to_string()),
+ cost_remaining: Some(crate::core::agent::session::CostCeiling {
+ rates: crate::core::agent::session::TokenRates {
+ prompt_usd: 1e-6,
+ completion_usd: 2e-6,
+ cache_read_usd: None,
+ cache_write_usd: None,
+ },
+ max_usd: 0.25,
+ }),
+ ..parent_run()
+ };
+ let model = child_model(&resolved_on(Some("smol")), &parent);
+ let err = child_cost_ceiling(&model, &parent).expect_err("unpriced smol refused");
+ assert!(err.to_string().contains("no-such-model-jan-test"), "{err}");
+ }
+
/// `[agent].send_reasoning = false` has to reach the child body: a child
/// resends the `reasoning_content` of its own tool-call turns, so an opt-out
/// that stopped at the parent would still break a strict provider on the
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 3d933a4f6..9ff1b771a 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -753,6 +753,9 @@ enum PickerKind {
/// `/settings > providers`: manage `~/.jan/config.toml` providers via a
/// docked add/edit wizard (`a`/`e`) or deletion (`d`).
ProviderSettings,
+ /// `/settings > subagents`: every saved subagent with the model it
+ /// dispatches on. Enter picks a model override, `x` clears it.
+ SubagentModels,
/// `/todo` editor: browse the phased list and mutate the selected task
/// (done/drop/rm) through the same canonical `TodoList` the model uses.
Todo,
@@ -831,6 +834,7 @@ impl Picker {
PickerKind::ViewConfig => " provider config ",
PickerKind::AgentSettings => " agent settings ",
PickerKind::ProviderSettings => " providers ",
+ PickerKind::SubagentModels => " subagent models ",
PickerKind::Todo => " todo ",
PickerKind::PluginSelect => " install plugins ",
PickerKind::PluginSetup => " set up plugin ",
@@ -856,6 +860,9 @@ impl Picker {
PickerKind::RewindScope => " ↑/↓ select Enter restore Esc cancel",
PickerKind::ViewConfig => " set via: jan config set --provider <id> ... Esc close",
PickerKind::AgentSettings => " ↑/↓ select Enter edit x unset Esc close",
+ PickerKind::SubagentModels => {
+ " ↑/↓ select Enter choose model x clear override Esc back"
+ }
PickerKind::ProviderSettings => {
" ↑/↓ select Enter edit a add dd delete x logout Esc close"
}
@@ -893,6 +900,23 @@ struct ModelItem {
value: String,
}
+/// What a model picker's choice is written to. One picker serves the session's
+/// `/model` and the `/settings` model rows, so choosing a model reads the same
+/// everywhere and a settings choice can never be a typo.
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum ModelTarget {
+ /// The session's own model (`/model`), saved to `[agent].model`.
+ Session,
+ /// `smol_model` in `~/.jan/config.toml`.
+ SmolModel,
+ /// `[subagents.<name>] model` in the project's agent.toml.
+ Subagent(String),
+}
+
+/// Scope label of the model-role rows (`smol`, `inherit`) in a subagent's
+/// model picker; also their `provider`, so search matches the word "role".
+const ROLE_SCOPE: &str = "role";
+
struct ModelPicker {
scopes: Vec<ModelScope>,
active_scope: usize,
@@ -901,16 +925,34 @@ struct ModelPicker {
items: Vec<ModelItem>,
query: String,
selected: usize,
+ target: ModelTarget,
+ /// The value the target holds now, marked "current" in the detail line.
+ current: String,
}
impl ModelPicker {
- fn from_pairs(mut pairs: Vec<(String, String)>, current_model: &str) -> Option<Self> {
+ fn from_pairs(pairs: Vec<(String, String)>, current_model: &str) -> Option<Self> {
+ Self::with_roles(pairs, &[], current_model)
+ }
+
+ /// [`from_pairs`](Self::from_pairs) with model `roles` offered first, in
+ /// their own `role` scope. Roles are not provider models, so a picker that
+ /// offers them opens even when no provider lists a model.
+ fn with_roles(
+ mut pairs: Vec<(String, String)>,
+ roles: &[&str],
+ current_model: &str,
+ ) -> Option<Self> {
pairs.sort_by(|a, b| match (a.0 == "tokamak", b.0 == "tokamak") {
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
_ => a.cmp(b),
});
pairs.dedup();
+ let roles = roles
+ .iter()
+ .map(|role| (ROLE_SCOPE.to_string(), (*role).to_string()));
+ let pairs: Vec<(String, String)> = roles.chain(pairs).collect();
if pairs.is_empty() {
return None;
}
@@ -954,6 +996,8 @@ impl ModelPicker {
all_items,
query: String::new(),
selected,
+ target: ModelTarget::Session,
+ current: current_model.to_string(),
})
}
@@ -13985,8 +14029,32 @@ async fn handle_model_picker_key(app: &mut App, key: KeyEvent, ctrl: bool) {
}
}
if let Some(value) = chosen {
- app.set_model(value);
- app.model_picker = None;
+ let target = app
+ .model_picker
+ .take()
+ .map(|picker| picker.target)
+ .unwrap_or(ModelTarget::Session);
+ match target {
+ ModelTarget::Session => app.set_model(value),
+ ModelTarget::SmolModel => {
+ let written = crate::core::agent::global_config::set_global_key(
+ "smol_model",
+ Some(toml_edit::value(value.as_str())),
+ );
+ match written {
+ Ok(_) => app.note(&format!(
+ "smol_model = {value} written; subagents on the smol role use it from \
+ their next dispatch, /goal from the next session"
+ )),
+ Err(e) => app.note(&format!("failed to write smol_model: {e}")),
+ }
+ open_settings_screen(app);
+ }
+ ModelTarget::Subagent(name) => {
+ set_subagent_model_override(app, &name, Some(&value));
+ open_subagent_settings(app, Some(&name));
+ }
+ }
}
}
/// The copyable continuation command shown when a session closes, mirroring
@@ -14429,6 +14497,15 @@ async fn handle_key(
}
}
}
+ // `/settings > subagents`: `x` removes the selected agent's model
+ // override, so the definition's own model applies again.
+ KeyCode::Char('x') if picker.kind == PickerKind::SubagentModels => {
+ let name = picker.items[picker.selected].value.clone();
+ if !name.is_empty() {
+ set_subagent_model_override(app, &name, None);
+ open_subagent_settings(app, Some(&name));
+ }
+ }
// `/settings` picker: `x` restores the selected key to its default
// by removing it from the file its scope names - same write as
// clearing the field in the edit dock, one keypress instead of two.
@@ -14583,6 +14660,16 @@ async fn handle_key(
PickerKind::AgentSettings => {
if value == PROVIDERS_SETTINGS_ROW {
open_provider_settings(app);
+ } else if value == SUBAGENTS_SETTINGS_ROW {
+ open_subagent_settings(app, None);
+ } else if value == SMOL_MODEL_KEY {
+ let current =
+ crate::core::agent::global_config::global_value(SMOL_MODEL_KEY);
+ open_settings_model_picker(
+ app,
+ ModelTarget::SmolModel,
+ current.as_deref(),
+ );
} else if let Some(def) =
AGENT_SETTINGS.iter().find(|d| d.key == value)
{
@@ -14616,6 +14703,22 @@ async fn handle_key(
// Agents Enter is handled by the guarded arm above; the
// detail has no Enter action of its own. Background shells are
// acted on with `x` (stop), not Enter.
+ PickerKind::SubagentModels => {
+ // The watermark row (no subagents saved) has no name.
+ if !value.is_empty() {
+ let current =
+ crate::core::agent::subagent::SubagentRegistry::load(
+ &app.project_root,
+ )
+ .get(&value)
+ .and_then(|d| d.model.clone());
+ open_settings_model_picker(
+ app,
+ ModelTarget::Subagent(value),
+ current.as_deref(),
+ );
+ }
+ }
PickerKind::Agents
| PickerKind::AgentDetail
| PickerKind::BackgroundShells
@@ -16192,6 +16295,14 @@ enum AgentSettingKind {
/// management screen instead of an `[agent]` edit dock.
const PROVIDERS_SETTINGS_ROW: &str = "__providers__";
+/// Sentinel row value in the `/settings` picker that opens the per-subagent
+/// model screen (`open_subagent_settings`).
+const SUBAGENTS_SETTINGS_ROW: &str = "__subagents__";
+
+/// The `/settings` row whose Enter opens the model picker instead of a text
+/// dock. Still an [`AGENT_SETTINGS`] def, so `x` and `/vibe-setting` reach it.
+const SMOL_MODEL_KEY: &str = "smol_model";
+
const AGENT_SETTINGS: &[AgentSettingDef] = &[
AgentSettingDef {
key: "context_window",
@@ -16310,6 +16421,16 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[
kind: AgentSettingKind::Int { default: Some(0), min: 0 },
scope: SettingScope::Global,
},
+ AgentSettingDef {
+ key: SMOL_MODEL_KEY,
+ label: "smol_model",
+ desc: "cheap model for subagents with model = \"smol\" and /goal checks",
+ // Unset falls back to the session's model; there is no fixed id to show.
+ kind: AgentSettingKind::Text {
+ default: "the main model",
+ },
+ scope: SettingScope::Global,
+ },
];
/// Docked message field for one running subagent, opened from `/agents`. What
@@ -16993,6 +17114,13 @@ fn build_agent_settings_items(toml_path: &std::path::Path) -> Vec<PickerItem> {
checkbox: None,
spans: None,
}];
+ items.push(PickerItem {
+ value: SUBAGENTS_SETTINGS_ROW.to_string(),
+ label: "subagents".to_string(),
+ hint: Some("choose the model each saved subagent runs on".to_string()),
+ checkbox: None,
+ spans: None,
+ });
items.extend(
AGENT_SETTINGS
.iter()
@@ -17028,6 +17156,81 @@ fn open_settings_screen(app: &mut App) {
});
}
+/// Open the `/settings > subagents` screen: one row per saved subagent name
+/// (the winning definition) with the model it dispatches on. An override in
+/// agent.toml is labelled with the definition's own model beside it, so the
+/// user can see what `x` falls back to. `select` re-aims the cursor at a name
+/// after a write rebuilds the list.
+fn open_subagent_settings(app: &mut App, select: Option<&str>) {
+ use crate::core::agent::subagent::{SubagentRegistry, INHERIT_ROLE};
+ let effective = SubagentRegistry::load(&app.project_root);
+ let own = SubagentRegistry::load_definitions(&app.project_root);
+ let mut names: Vec<&str> = effective.list().iter().map(|d| d.name.as_str()).collect();
+ names.sort_unstable();
+ names.dedup();
+
+ let model_of = |reg: &SubagentRegistry, name: &str| {
+ reg.get(name)
+ .and_then(|d| d.model.as_deref())
+ .map(str::trim)
+ .filter(|m| !m.is_empty())
+ .unwrap_or(INHERIT_ROLE)
+ .to_string()
+ };
+ let items: Vec<PickerItem> = if names.is_empty() {
+ vec![PickerItem {
+ label: "no saved subagents - create one with create_subagent or a plugin".to_string(),
+ value: String::new(),
+ hint: None,
+ checkbox: None,
+ spans: None,
+ }]
+ } else {
+ names
+ .iter()
+ .map(|name| {
+ let now = model_of(&effective, name);
+ let base = model_of(&own, name);
+ PickerItem {
+ value: (*name).to_string(),
+ label: (*name).to_string(),
+ hint: Some(if now == base {
+ now
+ } else {
+ format!("{now} (override; own: {base})")
+ }),
+ checkbox: None,
+ spans: None,
+ }
+ })
+ .collect()
+ };
+ let selected = select
+ .and_then(|name| items.iter().position(|i| i.value == name))
+ .unwrap_or(0);
+ app.picker = Some(Picker {
+ kind: PickerKind::SubagentModels,
+ search: None,
+ items,
+ selected,
+ armed_delete: None,
+ });
+}
+
+/// Write or clear (`None`) one subagent's `[subagents.<name>] model` in the
+/// project's agent.toml and report it. Read at each dispatch, so it applies to
+/// the next one, mid-session included.
+fn set_subagent_model_override(app: &mut App, name: &str, model: Option<&str>) {
+ let path = app.agent_dir.join("agent.toml");
+ match crate::core::agent::project::set_subagent_model(&path, name, model) {
+ Ok(()) => app.note(&match model {
+ Some(model) => format!("subagent {name} now runs on {model} from its next dispatch"),
+ None => format!("subagent {name} model override cleared"),
+ }),
+ Err(e) => app.note(&format!("failed to write {}: {e}", path.display())),
+ }
+}
+
/// Open the `/settings > providers` screen: a picker row per provider in
/// `~/.jan/config.toml` (the standalone-agent credential store), with `a` to
/// add, Enter to edit the selected row, and `d` pressed twice to delete it
@@ -18316,10 +18519,27 @@ async fn open_model_picker(app: &mut App) {
/// automatic probe cheap), then rebuild the picker in place.
async fn refresh_model_picker(app: &mut App) {
let project_root = app.project_root.clone();
+ let target = app
+ .model_picker
+ .as_ref()
+ .map(|picker| picker.target.clone())
+ .unwrap_or(ModelTarget::Session);
app.probed_models.clear();
let refreshed = super::providers::refresh_models(Some(&project_root), None).await;
apply_model_refresh(app, refreshed, true).await;
- show_model_picker(app);
+ match target {
+ ModelTarget::Session => show_model_picker(app),
+ ModelTarget::SmolModel => {
+ let current = crate::core::agent::global_config::global_value("smol_model");
+ open_settings_model_picker(app, ModelTarget::SmolModel, current.as_deref());
+ }
+ ModelTarget::Subagent(name) => {
+ let current = crate::core::agent::subagent::SubagentRegistry::load(&app.project_root)
+ .get(&name)
+ .and_then(|d| d.model.clone());
+ open_settings_model_picker(app, ModelTarget::Subagent(name), current.as_deref());
+ }
+ }
}
/// Report a probe and reload the session's provider snapshot when it changed
@@ -18361,6 +18581,31 @@ async fn apply_model_refresh(
}
}
+/// Open the model picker aimed at a `/settings` row instead of the session.
+/// `current` is pre-highlighted. A subagent target also offers the `smol` and
+/// `inherit` roles; `smol_model` cannot be a role (`smol` would name itself).
+fn open_settings_model_picker(app: &mut App, target: ModelTarget, current: Option<&str>) {
+ let pairs = super::providers::list_provider_models(Some(&app.project_root));
+ let current = current.unwrap_or_default();
+ let roles: &[&str] = match &target {
+ ModelTarget::Subagent(_) => &[
+ crate::core::agent::subagent::SMOL_ROLE,
+ crate::core::agent::subagent::INHERIT_ROLE,
+ ],
+ _ => &[],
+ };
+ let picker = ModelPicker::with_roles(pairs, roles, current);
+ match picker {
+ Some(picker) => {
+ app.picker = None;
+ app.model_picker = Some(ModelPicker { target, ..picker });
+ }
+ None => app.note(
+ "no models available (add a provider with `jan config set`, or configure one in the desktop app)",
+ ),
+ }
+}
+
/// Build the picker from what is currently configured, replacing any open one.
fn show_model_picker(app: &mut App) {
let pairs = super::providers::list_provider_models(Some(&app.project_root));
@@ -21016,7 +21261,7 @@ fn draw(f: &mut Frame, app: &mut App) {
// the full frame width (its border is top-only).
app.transcript.view_width = f.area().width.max(1);
if let Some(picker) = app.model_picker.as_ref() {
- draw_model_picker(f, f.area(), picker, &app.model);
+ draw_model_picker(f, f.area(), picker);
return;
}
// Every frame, so a finished plan hides on wall-clock time even with the
@@ -22301,14 +22546,18 @@ fn count_label(label: &str, count: usize, width: u16) -> String {
format!("{label}{}{}", " ".repeat(width - used), count)
}
-fn draw_model_picker(f: &mut Frame, area: Rect, picker: &ModelPicker, current_model: &str) {
+fn draw_model_picker(f: &mut Frame, area: Rect, picker: &ModelPicker) {
use ratatui::widgets::{Clear, List, ListItem, ListState};
+ // Named for what the choice is written to, so a settings pick is never
+ // mistaken for switching the session's model.
+ let title = match &picker.target {
+ ModelTarget::Session => " Models ".to_string(),
+ ModelTarget::SmolModel => " Models for smol_model ".to_string(),
+ ModelTarget::Subagent(name) => format!(" Models for subagent {name} "),
+ };
let block = panel_block(theme::border_active())
- .title(Span::styled(
- " Models ",
- title_style(theme::border_active()),
- ));
+ .title(Span::styled(title, title_style(theme::border_active())));
f.render_widget(Clear, area);
let inner = block.inner(area);
f.render_widget(block, area);
@@ -22452,7 +22701,7 @@ fn draw_model_picker(f: &mut Frame, area: Rect, picker: &ModelPicker, current_mo
.items
.get(picker.selected)
.map(|item| {
- let state = if item.value == current_model {
+ let state = if item.value == picker.current {
"current"
} else {
"default"
@@ -30692,8 +30941,8 @@ mod tests {
super::settings_command(&mut app, "");
let picker = app.picker.as_ref().expect("bare /settings opens picker");
assert_eq!(picker.kind, PickerKind::AgentSettings);
- // One leading "providers" row plus a row per `[agent]` def.
- assert_eq!(picker.items.len(), AGENT_SETTINGS.len() + 1);
+ // The leading "providers" and "subagents" rows plus a row per def.
+ assert_eq!(picker.items.len(), AGENT_SETTINGS.len() + 2);
assert_eq!(picker.items[0].value, PROVIDERS_SETTINGS_ROW);
let row = picker
.items
@@ -30996,6 +31245,169 @@ mod tests {
let _ = std::fs::remove_dir_all(&app.agent_dir);
}
+ /// A project with an `explorer` (own model `big`) and a `reviewer`, plus an
+ /// app pointed at it. Returns the project root.
+ fn app_with_subagents(app: &mut App) -> std::path::PathBuf {
+ let root = app.agent_dir.join("project");
+ std::fs::create_dir_all(&root).unwrap();
+ app.project_root = root.clone();
+ let dir = crate::core::agent::subagent::project_subagents_dir(&root);
+ std::fs::create_dir_all(&dir).unwrap();
+ for (name, model) in [("explorer", "model = \"big\"\n"), ("reviewer", "")] {
+ std::fs::write(
+ dir.join(format!("{name}.toml")),
+ format!("name = \"{name}\"\ndescription = \"d\"\nsystem_prompt = \"p\"\n{model}"),
+ )
+ .unwrap();
+ }
+ app.agent_dir = crate::core::agent::project::store_root(&root);
+ std::fs::create_dir_all(&app.agent_dir).unwrap();
+ std::fs::write(app.agent_dir.join("agent.toml"), "[agent]\n").unwrap();
+ root
+ }
+
+ /// `/settings > subagents` lists every saved subagent with the model it
+ /// dispatches on, and Enter opens the model picker aimed at that agent,
+ /// with the `smol`/`inherit` roles offered beside the provider models.
+ /// Choosing one writes `[subagents.<name>] model` to the project's
+ /// agent.toml, which the registry then reports; `x` removes it again.
+ #[tokio::test]
+ async fn settings_subagents_screen_sets_and_clears_a_model_override() {
+ let mut app = test_app();
+ let root = app_with_subagents(&mut app);
+
+ super::settings_command(&mut app, "");
+ let picker = app.picker.as_mut().expect("settings open");
+ let row = picker
+ .items
+ .iter()
+ .position(|i| i.value == super::SUBAGENTS_SETTINGS_ROW)
+ .expect("/settings has a subagents row");
+ picker.selected = row;
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+
+ let picker = app.picker.as_ref().expect("subagents screen open");
+ assert_eq!(picker.kind, PickerKind::SubagentModels);
+ let labels: Vec<_> = picker.items.iter().map(|i| i.value.as_str()).collect();
+ assert_eq!(labels, ["explorer", "reviewer"]);
+ assert_eq!(picker.items[0].hint.as_deref(), Some("big"));
+ assert_eq!(picker.items[1].hint.as_deref(), Some("inherit"));
+
+ // Enter on explorer: the model picker, aimed at it, offering roles.
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ let mp = app.model_picker.as_mut().expect("model picker opened");
+ assert_eq!(mp.target, super::ModelTarget::Subagent("explorer".into()));
+ let smol = mp
+ .items
+ .iter()
+ .position(|i| i.value == "smol")
+ .expect("the smol role is offered");
+ assert!(mp.items.iter().any(|i| i.value == "inherit"));
+ mp.selected = smol;
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+
+ assert!(app.model_picker.is_none());
+ assert_eq!(app.model, "m", "the session's own model is untouched");
+ let reg = crate::core::agent::subagent::SubagentRegistry::load(&root);
+ assert_eq!(reg.get("explorer").unwrap().model.as_deref(), Some("smol"));
+ // Back on the refreshed list, which shows the override and its source.
+ let picker = app.picker.as_ref().expect("returns to the subagents list");
+ assert_eq!(picker.kind, PickerKind::SubagentModels);
+ assert_eq!(picker.items[0].hint.as_deref(), Some("smol (override; own: big)"));
+
+ // `x` clears the override: the definition's own model applies again.
+ press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE).await;
+ let reg = crate::core::agent::subagent::SubagentRegistry::load(&root);
+ assert_eq!(reg.get("explorer").unwrap().model.as_deref(), Some("big"));
+ assert_eq!(app.picker.as_ref().unwrap().items[0].hint.as_deref(), Some("big"));
+ }
+
+ /// Enter on the `smol_model` row picks from the configured models rather
+ /// than a free-text field, so a typo cannot reach a dispatch.
+ #[test]
+ fn settings_smol_model_row_opens_the_model_picker() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ crate::core::agent::global_config::set_provider(
+ "openai",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some("http://127.0.0.1:9/v1".into()),
+ models: Some(vec!["gpt-big".into(), "gpt-mini".into()]),
+ ..Default::default()
+ },
+ )
+ .expect("seed provider");
+ let mut app = test_app();
+ std::fs::create_dir_all(&app.agent_dir).unwrap();
+ std::fs::write(app.agent_dir.join("agent.toml"), "[agent]\n").unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ rt.block_on(async {
+ super::settings_command(&mut app, "");
+ let picker = app.picker.as_mut().unwrap();
+ picker.selected =
+ picker.items.iter().position(|i| i.value == "smol_model").unwrap();
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ let mp = app.model_picker.as_mut().expect("model picker opened");
+ assert_eq!(mp.target, super::ModelTarget::SmolModel);
+ assert!(
+ !mp.items.iter().any(|i| i.value == "smol"),
+ "smol cannot point at itself"
+ );
+ mp.selected = mp.items.iter().position(|i| i.value == "gpt-mini").unwrap();
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ });
+
+ assert_eq!(
+ crate::core::agent::global_config::smol_model(),
+ Ok(Some("gpt-mini".to_string()))
+ );
+ assert_eq!(app.model, "m", "the session's own model is untouched");
+ let picker = app.picker.as_ref().expect("returns to /settings");
+ assert_eq!(picker.kind, PickerKind::AgentSettings);
+ });
+ }
+
+ /// `smol_model` is the cheap model behind the `smol` subagent role and
+ /// `/goal` evaluation. It is user-wide, so the row writes the global config
+ /// as a string, and a cleared field unsets it so the main model applies.
+ #[test]
+ fn settings_prompt_writes_smol_model_globally() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let mut app = test_app();
+ std::fs::create_dir_all(&app.agent_dir).unwrap();
+ let toml_path = app.agent_dir.join("agent.toml");
+ std::fs::write(&toml_path, "[agent]\n").unwrap();
+
+ let def = AGENT_SETTINGS
+ .iter()
+ .find(|d| d.key == "smol_model")
+ .expect("/settings lists smol_model");
+ assert!(def.scope == super::SettingScope::Global);
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));
+ for c in "cheap-1".chars() {
+ super::handle_settings_key(&mut app, key(KeyCode::Char(c)), false);
+ }
+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
+
+ assert_eq!(
+ crate::core::agent::global_config::smol_model(),
+ Ok(Some("cheap-1".to_string()))
+ );
+ let project = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(!project.contains("smol_model"), "{project}");
+
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, Some("cheap-1")));
+ for _ in 0.."cheap-1".len() {
+ super::handle_settings_key(&mut app, key(KeyCode::Backspace), false);
+ }
+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
+ assert_eq!(crate::core::agent::global_config::smol_model(), Ok(None));
+
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ });
+ }
+
/// `ask_timeout_secs` lives in the user-wide config, not the project's
/// agent.toml, so the row has to write across scopes, and the note says it
/// takes effect on the next run.