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): cap parallel subagents (default 10) with a visible TUI queue (#8607)

Thinh Leecc73fe049cf
diff --git a/docs/src/pages/docs/agent/_meta.json b/docs/src/pages/docs/agent/_meta.json
index 9337e57c4..07c1b3950 100644
--- a/docs/src/pages/docs/agent/_meta.json
+++ b/docs/src/pages/docs/agent/_meta.json
@@ -22,5 +22,6 @@
"permissions": "Tool Permissions",
"mcp": "MCP",
"reference-separator": { "title": "Reference", "type": "separator" },
- "cli": "CLI"
+ "cli": "CLI",
+ "spec-max-parallel-subagents": "Max Parallel Subagents (Spec)"
}
diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdx
index 8fffd1f7b..cd174101b 100644
--- a/docs/src/pages/docs/agent/project-config.mdx
+++ b/docs/src/pages/docs/agent/project-config.mdx
@@ -62,6 +62,7 @@ max_turns = 400
# context_window = 128000
# compaction_reserve_tokens = 16384
# max_tokens = 4096
+# max_parallel_subagents = 10 # max concurrently-running subagents per run; extra dispatches queue FIFO
instructions_file = "AGENT.md"
# [provider]
@@ -94,6 +95,7 @@ inject = "always"
| `context_window` | `128000` | Context limit in tokens |
| `compaction_reserve_tokens` | `16384` | Headroom kept free before [compaction](/docs/agent/context) |
| `max_tokens` | unset | Cap on tokens generated per response. Omitted from the request when unset |
+| `max_parallel_subagents` | `10` | Subagents that may run at once (min 1); extra dispatches queue FIFO |
| `instructions_file` | `AGENT.md` | Markdown injected into the system prompt |
### `[provider]`
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index 89654a450..7cf1860fa 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -43,6 +43,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-
| `/mcp` | Enable or disable MCP servers |
| `/login` | Sign in to Tokamak and save the API key |
| `/config` | View provider config (`~/.jan/config.toml`) |
+| `/settings [max_parallel_subagents N]` | Edit `agent.toml` settings in an interactive menu - `[agent]` knobs (`max_turns`, `context_window`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `instructions_file`), `[budget]` limits, and the `[tools]` / `[skills]` toggles (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets). `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next run |
See [Providers](/docs/agent/providers) and [MCP](/docs/agent/mcp).
diff --git a/docs/src/pages/docs/agent/spec-max-parallel-subagents.md b/docs/src/pages/docs/agent/spec-max-parallel-subagents.md
new file mode 100644
index 000000000..1cdf5c7fb
--- /dev/null
+++ b/docs/src/pages/docs/agent/spec-max-parallel-subagents.md
@@ -0,0 +1,95 @@
+---
+title: Max Parallel Subagents - Design Spec
+description: Design for capping concurrent subagents with a visible TUI queue.
+keywords:
+ [Jan, Jan Agent, subagents, parallelism, queue, max_parallel_subagents, design spec]
+---
+
+# Max Parallel Subagents - Design Spec
+
+## Problem
+
+`dispatch_subagent` spawns one background task per call with no concurrency limit
+(`src/core/agent/subagent.rs` - `spawn_subagent` calls `tokio::spawn`
+unconditionally; `BackgroundSubagents` only supports teardown via
+`abort_all`/`join_all`). A model that dispatches 10+ subagents launches all of
+them at once; each competes for provider rate limits, context, and turn budget,
+so high fan-out stalls or times out. There is no knob to bound it and no way to
+see the resulting contention.
+
+## Design
+
+### Config
+
+New `[agent]` key in `agent.toml`: `max_parallel_subagents`, default `10`.
+
+Semantics: at most N subagents of a single parent run may be running (spawned
+task) at once. Requests beyond N queue; they never error for being over the cap.
+
+The cap is snapshot at run start. Re-reading `agent.toml` mid-run does not
+reshuffle the queue; the new value applies to the next run.
+
+### Admission control
+
+`spawn_subagent` becomes two-phase:
+
+1. Resolve the request exactly as today (registry lookup, permission check,
+ `run_id` allocation, oneshot channel creation).
+2. If running count < cap: spawn the task immediately and register in
+ `BackgroundSubagents` as `Running`.
+3. Else: register as `Queued` (FIFO) and return the `run_id` immediately. The
+ task body does not start.
+
+A slot frees when a child finishes, is collected by `await_subagent`, or is
+aborted. When a slot frees, dequeue the oldest queued child and spawn it.
+
+The queue is per-parent-run. Subagents cannot spawn grandchildren
+(`loop.rs`), so there is exactly one level to police.
+
+### Queue state in `BackgroundSubagents`
+
+`BackgroundEntry` gains a `Queued` variant (or a `queued: bool` + pending
+request). Running children keep the current `result`/`abort` fields; queued
+children hold the resolved request until promoted.
+
+- `abort_all`: abort running children and drop queued ones (emit the closing
+ `SubagentEnd` for each, exactly as running aborts do).
+- `join_all`: wait on running children; queued children never started, so they
+ are simply dropped on clean exit - but must still emit `SubagentEnd` so the
+ transcript never sees an unbracketed `SubagentStart`.
+
+### `await_subagent` on a queued run
+
+`await_subagent(run_id)` on a queued child must block until a slot frees, then
+run to completion. It must not deadlock: awaiting a queued child that sits
+behind a running child that is itself awaited by the same parent is the
+model's job to sequence; we only guarantee the await resolves once the child
+actually runs. `await_subagent` on a queued child does not promote it early -
+the FIFO order is preserved.
+
+### TUI
+
+`SubagentBlock` (tui.rs) currently renders running children with a live
+tool-call window. Add a distinct `queued` state:
+
+- Queued children render `queued (n waiting)` with a different glyph/status
+ from `working`, so a stalled run reads as "waiting for a slot", not stuck.
+- The block's live-update path already receives `SubagentStart`; queued
+ children get their own synthetic row that flips to the running render when
+ promoted.
+
+### TUI settings surface
+
+Today `/config` is read-only and shows only `~/.jan/config.toml` providers.
+Extend it (or add `/settings`) to edit `[agent]` keys, starting with
+`max_parallel_subagents`, ideally the full set (`max_turns`,
+`context_window`, `compaction_reserve_tokens`, `max_tokens`,
+`instructions_file`). Writes go through the same `agent.toml` writer the CLI
+uses; input validated (integer, >= 1).
+
+## Out of scope
+
+- Cross-run (process-wide) concurrency limiting.
+- Rejecting dispatches instead of queueing.
+- Any web-app / desktop settings changes (TUI only).
+- Changing the cap for already-running children when config changes mid-run.
diff --git a/docs/src/pages/docs/agent/subagents.mdx b/docs/src/pages/docs/agent/subagents.mdx
index 85e5eebc9..8fc165eea 100644
--- a/docs/src/pages/docs/agent/subagents.mdx
+++ b/docs/src/pages/docs/agent/subagents.mdx
@@ -64,6 +64,26 @@ Context share is the one to watch: an agent climbing toward 100% is about to run
Dispatch is non-blocking, which is what makes parallel fan-out possible: the main agent dispatches
several, then awaits each one. Each `run_id` can be awaited once.
+## Parallelism and queueing
+
+Up to `max_parallel_subagents` subagents run at the same time (default `10`, minimum `1`, set in
+`agent.toml` under `[agent]` - or from the console with `/settings max_parallel_subagents N`).
+Dispatches beyond the cap are queued FIFO and start as a running child finishes.
+
+A queued run still returns a `run_id` immediately, and `await_subagent` on it simply blocks until a
+slot frees and the run completes - no deadlock, no premature promotion. `abort_all` cancels queued
+runs too.
+
+In the console, a queued subagent shows as `queued (N waiting)` in its panel, where `N` is its
+position in line (`1` = next to start). The panel turns into a normal running row once its slot
+opens.
+
+The cap is snapshotted when a run starts, so changing it mid-run takes effect on the next run.
+
+<Callout type="info">
+A queue is not an error signal. The main agent keeps dispatching; runs just wait their turn.
+</Callout>
+
## Isolation
A subagent does not see your conversation. It gets only the task it was handed, so that description
diff --git a/src-tauri/src/core/agent/commands.rs b/src-tauri/src/core/agent/commands.rs
index 9f47f96ae..a5e7a84b7 100644
--- a/src-tauri/src/core/agent/commands.rs
+++ b/src-tauri/src/core/agent/commands.rs
@@ -70,6 +70,7 @@ fn build_orchestration_args<R: Runtime>(
todo_registry: None,
system_prompt_override: None,
subagents_enabled: true,
+ max_parallel_subagents: crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,
yolo: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
}
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index 672943b88..4e44ac6c8 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -57,6 +57,19 @@ pub enum StreamEvent {
#[serde(default, skip_serializing_if = "Option::is_none")]
task: Option<String>,
},
+ /// A backgrounded subagent dispatch found the parent run's concurrency cap
+ /// (`max_parallel_subagents`) exhausted and queued the child in FIFO order.
+ /// `waiting` is the child's 1-based position in the queue (1 = next to
+ /// start). The child's `SubagentStart` follows once a slot frees; a queued
+ /// child aborted at parent teardown is closed by `SubagentEnd` like any
+ /// other.
+ SubagentQueued {
+ run_id: String,
+ name: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ task: Option<String>,
+ waiting: u32,
+ },
/// A backgrounded subagent run finished (success or error). Pairs with the
/// `SubagentStart` of the same `run_id`.
SubagentEnd { run_id: String, name: String },
@@ -375,6 +388,22 @@ mod tests {
start,
json!({ "type": "subagent_start", "run_id": "sub-1", "name": "rust-reviewer" })
);
+ let queued = serde_json::to_value(StreamEvent::SubagentQueued {
+ run_id: "sub-2".into(),
+ name: "rust-reviewer".into(),
+ task: None,
+ waiting: 2,
+ })
+ .unwrap();
+ assert_eq!(
+ queued,
+ json!({
+ "type": "subagent_queued",
+ "run_id": "sub-2",
+ "name": "rust-reviewer",
+ "waiting": 2
+ })
+ );
let end = serde_json::to_value(StreamEvent::SubagentEnd {
run_id: "sub-1".into(),
name: "rust-reviewer".into(),
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index d8e573016..85b588a2d 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -77,6 +77,10 @@ pub(crate) struct OrchestrationArgs {
/// Whether this run may dispatch subagents. `false` for child runs, which
/// caps recursion depth at one (a subagent cannot spawn grandchildren).
pub subagents_enabled: bool,
+ /// Cap on concurrently-running background subagents for this run
+ /// (`[agent].max_parallel_subagents` in agent.toml, default 10). Snapshot
+ /// taken at run start: a mid-run config edit affects the *next* run only.
+ pub max_parallel_subagents: u32,
/// `--yolo`: disable the sandbox/permission gate and auto-allow every tool
/// call (built-in reads/writes/exec and MCP) without prompting. Inherited by
/// dispatched subagents via the cloned parent args.
@@ -774,6 +778,7 @@ pub(crate) async fn run_server_side_openai_orchestration(
todo_registry: None,
system_prompt_override: None,
subagents_enabled: false,
+ max_parallel_subagents: crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,
yolo: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
};
@@ -1001,6 +1006,7 @@ async fn orchestrate_inner(
todo_registry,
system_prompt_override,
subagents_enabled,
+ max_parallel_subagents,
yolo,
run_mode,
} = args;
@@ -1192,7 +1198,9 @@ async fn orchestrate_inner(
if args.subagents_enabled && run_mode != crate::core::agent::plan::RunMode::Plan {
if let Some(root) = project_root {
let registry = crate::core::agent::subagent::SubagentRegistry::load(root);
- for schema in crate::core::agent::subagent::subagent_tool_schemas(&registry) {
+ for schema in
+ crate::core::agent::subagent::subagent_tool_schemas(&registry, *max_parallel_subagents)
+ {
let name = schema["function"]["name"].as_str().unwrap_or_default();
if permissions.is_denied(name) {
continue;
@@ -1270,7 +1278,10 @@ async fn orchestrate_inner(
}
// Background subagents are scoped to this run: `_bg_guard` aborts any
// still-running child when `orchestrate_inner` returns or is cancelled.
- let bg = std::sync::Arc::new(crate::core::agent::subagent::BackgroundSubagents::default());
+ // The cap (`max_parallel_subagents`) is snapshotted here, at run start.
+ let bg = std::sync::Arc::new(crate::core::agent::subagent::BackgroundSubagents::new(
+ *max_parallel_subagents,
+ ));
let _bg_guard = crate::core::agent::subagent::AbortOnDrop(bg.clone());
let subagents = args.subagents_enabled.then(|| SubagentContext {
parent_args: args.clone(),
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index ea4556909..ec975846f 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -75,6 +75,12 @@ pub(crate) struct AgentSection {
/// single response. Omitted from the request when unset (model default).
#[serde(default)]
pub max_tokens: Option<u64>,
+ /// Cap on concurrently-running background subagents for a run (defaults to
+ /// 10 if unset). Dispatches beyond the cap queue FIFO and start as running
+ /// ones finish. Snapshot at run start: a mid-run change affects the next
+ /// run only.
+ #[serde(default)]
+ pub max_parallel_subagents: Option<u32>,
}
#[derive(Debug, Clone, Default, Deserialize)]
@@ -95,6 +101,7 @@ max_turns = 400
# context_window = 128000 # tokens; defaults to 128K if unset
# compaction_reserve_tokens = 16384 # headroom before auto-compaction; defaults to 16K
# max_tokens = 4096 # cap on tokens the model generates per response (OpenAI max_tokens); omitted if unset
+# max_parallel_subagents = 10 # max concurrently-running subagents per run; extra dispatches queue FIFO
instructions_file = "AGENT.md"
# Project-local provider override. Wins over ~/.jan/config.toml and any
@@ -207,6 +214,43 @@ 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 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
+/// `[skills]` scalars alike. `None` removes the key (default applies).
+#[cfg(feature = "cli")]
+pub(crate) fn set_agent_key(
+ path: &Path,
+ key: &str,
+ value: Option<toml_edit::Item>,
+) -> Result<(), String> {
+ let raw = std::fs::read_to_string(path)
+ .map_err(|e| 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()))?;
+
+ let (section, key) = match key.split_once('.') {
+ Some((section, key)) => (section, key),
+ None => ("agent", key),
+ };
+
+ match value {
+ Some(v) => {
+ let table = doc[section].or_insert(toml_edit::Item::Table(toml_edit::Table::new()));
+ table[key] = v;
+ }
+ None => {
+ if let Some(table) = doc.get_mut(section).and_then(|t| t.as_table_mut()) {
+ table.remove(key);
+ }
+ }
+ }
+
+ std::fs::write(path, doc.to_string())
+ .map_err(|e| format!("Failed to write {}: {e}", path.display()))
+}
+
/// Persist `[skills].enabled` into the agent.toml at `path`, format-preserving
/// (comments kept). An empty list clears the whitelist (= all skills enabled).
#[cfg(any(not(feature = "cli"), test))]
@@ -319,6 +363,42 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ #[cfg(feature = "cli")]
+ #[test]
+ fn max_parallel_subagents_parses_and_defaults_to_none() {
+ let root = unique_root("max_parallel");
+ ensure_project(&root).expect("scaffold");
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.agent.max_parallel_subagents, None, "template leaves it unset");
+
+ // Explicit value round-trips through the /settings writer; unset removes.
+ let path = agent_toml_path(&root);
+ set_agent_key(&path, "max_parallel_subagents", Some(toml_edit::value(4i64)))
+ .expect("write");
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.agent.max_parallel_subagents, Some(4));
+ set_agent_key(&path, "max_parallel_subagents", None).expect("unset");
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.agent.max_parallel_subagents, None);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn dotted_keys_write_and_remove_under_their_section() {
+ let root = unique_root("dotted");
+ ensure_project(&root).expect("scaffold");
+ let path = agent_toml_path(&root);
+
+ set_agent_key(&path, "budget.max_steps", Some(toml_edit::value(60i64))).expect("write");
+ let raw = std::fs::read_to_string(&path).unwrap();
+ assert!(raw.contains("max_steps = 60"), "written under [budget]: {raw}");
+
+ set_agent_key(&path, "budget.max_steps", None).expect("unset");
+ let raw = std::fs::read_to_string(&path).unwrap();
+ assert!(!raw.contains("max_steps = 60"), "removed: {raw}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[test]
fn full_template_parses_ignoring_deferred_sections() {
let root = unique_root("full");
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index 820cebce5..b2f794ce8 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -406,12 +406,42 @@ struct BackgroundEntry {
/// Registry of a single parent run's background subagents, keyed by `run_id`.
/// Dropped when the parent run ends (see `AbortOnDrop`), aborting any child that
/// was never collected so a finished/cancelled parent leaves no orphan runs.
-#[derive(Default)]
pub(crate) struct BackgroundSubagents {
inner: std::sync::Mutex<std::collections::HashMap<String, BackgroundEntry>>,
+ /// Admission gate: `max_parallel_subagents` permits, one per child that is
+ /// *running* (as opposed to merely dispatched). A dispatch beyond the cap
+ /// parks on `acquire_owned` in FIFO order inside its spawned task, so the
+ /// queue is exactly the tokio semaphore waitlist -- no separate queue
+ /// structure that could drift from reality.
+ semaphore: std::sync::Arc<tokio::sync::Semaphore>,
+ /// Number of children currently parked on the semaphore waiting for a slot
+ /// (a dispatch reported `SubagentQueued` and its task has not started yet).
+ /// Used to report each queued child's 1-based position; decremented by the
+ /// task itself the moment it acquires its permit.
+ queued: std::sync::atomic::AtomicUsize,
+}
+
+/// Default cap on concurrently *running* subagents per parent run when
+/// `agent.toml` does not set `max_parallel_subagents`.
+pub(crate) const DEFAULT_MAX_PARALLEL_SUBAGENTS: u32 = 10;
+
+impl Default for BackgroundSubagents {
+ fn default() -> Self {
+ Self::new(DEFAULT_MAX_PARALLEL_SUBAGENTS)
+ }
}
impl BackgroundSubagents {
+ /// Create a registry admitting at most `cap` concurrently-running children.
+ /// Clamped to at least 1: a cap of 0 would make every dispatch queue
+ /// forever with nothing ever releasing a permit.
+ pub(crate) fn new(cap: u32) -> Self {
+ Self {
+ inner: std::sync::Mutex::new(std::collections::HashMap::new()),
+ semaphore: std::sync::Arc::new(tokio::sync::Semaphore::new(cap.max(1) as usize)),
+ queued: std::sync::atomic::AtomicUsize::new(0),
+ }
+ }
/// Abort and forget every registered child. Called on parent teardown when
/// the run is cancelled. Emits a closing `SubagentEnd` for each aborted
/// child (its own task is cancelled inside its await and never reaches its
@@ -551,6 +581,12 @@ async fn run_subagent(
/// [`await_subagent`]. Registered in `bg` so the parent run can abort it on
/// teardown. Resolution (name lookup, permission intersection) happens
/// synchronously, so a bad request errors here rather than in the background.
+///
+/// Admission: up to `max_parallel_subagents` children run at once; a dispatch
+/// beyond the cap is queued (FIFO) and its task parks on the shared semaphore
+/// until a running child finishes. A queued dispatch still returns its `run_id`
+/// right away, and `await_subagent` on a queued run blocks until it gets a slot
+/// and runs to completion -- never errors, never starts out of turn.
pub(crate) fn spawn_subagent(
bg: &Arc<BackgroundSubagents>,
parent_args: &crate::core::agent::r#loop::OrchestrationArgs,
@@ -559,6 +595,9 @@ pub(crate) fn spawn_subagent(
budget_remaining: Option<u64>,
events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
) -> Result<String, SubagentError> {
+ use crate::core::agent::events::StreamEvent;
+ use std::sync::atomic::Ordering;
+
if !parent_args.subagents_enabled {
return Err(SubagentError::PermissionDenied(
"subagents cannot dispatch nested subagents".to_string(),
@@ -575,13 +614,47 @@ pub(crate) fn spawn_subagent(
let run_id = next_subagent_run_id(&name);
let (tx, rx) = tokio::sync::oneshot::channel();
+ // Try to grab a permit at dispatch time. On success the child is admitted
+ // immediately; on exhaustion it joins the semaphore waitlist (FIFO) and is
+ // reported as queued. The permit is held by the task for its whole run and
+ // dropped when the task ends, so completion -- not collection -- releases
+ // the slot to the next queued child.
+ let semaphore = bg.semaphore.clone();
+ let admitted = semaphore.clone().try_acquire_owned();
+ let waiting = if admitted.is_err() {
+ bg.queued.fetch_add(1, Ordering::SeqCst) as u32 + 1
+ } else {
+ 0
+ };
+ if waiting > 0 {
+ let _ = events.send(StreamEvent::SubagentQueued {
+ run_id: run_id.clone(),
+ name: name.clone(),
+ task: Some(req.description.clone()),
+ waiting,
+ });
+ }
+
let parent_args = parent_args.clone();
let task_events = events.clone();
let entry_events = events.clone();
let model = parent_model.to_string();
let description = req.description.clone();
let run_id_task = run_id.clone();
+ let queued_counter = bg.clone();
let handle = tokio::spawn(async move {
+ let permit = match admitted {
+ Ok(p) => p,
+ Err(_) => {
+ let p = semaphore
+ .acquire_owned()
+ .await
+ .expect("subagent semaphore is never closed");
+ queued_counter.queued.fetch_sub(1, Ordering::SeqCst);
+ p
+ }
+ };
+ let _permit = permit;
let result = run_subagent(
parent_args,
resolved,
@@ -665,7 +738,10 @@ pub fn format_subagent_list(registry: &SubagentRegistry) -> String {
/// OpenAI tool schemas for the subagent tools. The dispatch tool's description
/// lists the currently-resolvable subagent names so the model can pick one
/// without a separate discovery call.
-pub fn subagent_tool_schemas(registry: &SubagentRegistry) -> Vec<serde_json::Value> {
+pub fn subagent_tool_schemas(
+ registry: &SubagentRegistry,
+ max_parallel: u32,
+) -> Vec<serde_json::Value> {
use serde_json::json;
let available: Vec<&str> = {
let mut names: Vec<&str> = registry.list().iter().map(|d| d.name.as_str()).collect();
@@ -674,7 +750,7 @@ pub fn subagent_tool_schemas(registry: &SubagentRegistry) -> Vec<serde_json::Val
names
};
let one_off = " For a one-off subagent, pass system_prompt inline (with a descriptive subagent_name); use create_subagent only to save a reusable definition.";
- let bg = " Runs in the BACKGROUND and returns a run_id immediately; keep working, dispatch more, then call await_subagent(run_id) to collect each result. Several can run concurrently.";
+ let bg = format!(" Runs in the BACKGROUND and returns a run_id immediately; keep working, dispatch more, then call await_subagent(run_id) to collect each result. Up to {max_parallel} run concurrently (max_parallel_subagents in agent.toml); dispatches beyond that are queued FIFO and start as running ones finish.");
let dispatch_desc = if available.is_empty() {
format!("Start a subagent: a nested, isolated agent with its own system prompt and narrowed tools.{bg}{one_off} No saved subagents yet.")
} else {
@@ -1405,11 +1481,226 @@ mod tests {
assert!(bg.inner.lock().unwrap().is_empty(), "teardown drained the map");
}
+ // ── max-parallel admission (semaphore queue) ───────────────────────────
+
+ /// Minimal run args for queue tests: empty providers (so dispatched
+ /// children fail fast instead of hanging), a real project root holding the
+ /// subagent def, subagents enabled, cap 1.
+ #[cfg(feature = "cli")]
+ fn max_par_args(root: &std::path::Path) -> crate::core::agent::r#loop::OrchestrationArgs {
+ use crate::core::agent::permissions::ToolPermissions;
+ use crate::core::agent::r#loop::OrchestrationArgs;
+ use crate::core::mcp::models::McpSettings;
+ use crate::core::state::ProviderConfig;
+ use std::collections::HashMap;
+ use std::sync::{Arc, Mutex};
+ OrchestrationArgs {
+ client: reqwest::Client::new(),
+ provider_configs: Arc::new(tokio::sync::Mutex::new(
+ HashMap::<String, ProviderConfig>::new(),
+ )),
+ mcp_servers: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
+ mcp_settings: Arc::new(tokio::sync::Mutex::new(McpSettings::default())),
+ jan_data_folder: std::env::temp_dir().to_string_lossy().into_owned(),
+ permissions: ToolPermissions::allow_all(),
+ project_root: Some(root.to_path_buf()),
+ permission_requests: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
+ ask_requests: None,
+ todo_registry: None,
+ system_prompt_override: None,
+ subagents_enabled: true,
+ max_parallel_subagents: 1,
+ yolo: false,
+ run_mode: crate::core::agent::plan::RunMode::Normal,
+ }
+ }
+
+ #[test]
+ fn subagent_cap_is_clamped_to_at_least_one() {
+ let bg = BackgroundSubagents::new(0);
+ assert_eq!(bg.semaphore.available_permits(), 1);
+ assert_eq!(BackgroundSubagents::new(3).semaphore.available_permits(), 3);
+ assert_eq!(
+ BackgroundSubagents::default().semaphore.available_permits(),
+ DEFAULT_MAX_PARALLEL_SUBAGENTS as usize
+ );
+ }
+
+ #[test]
+ fn queued_dispatches_wait_for_a_permit_in_fifo_order() {
+ let rt = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let bg = Arc::new(BackgroundSubagents::new(1));
+ // Occupy the single permit as if one child were running.
+ let running = bg.semaphore.clone().try_acquire_owned().unwrap();
+
+ let order = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let mut handles = Vec::new();
+ for i in 0..3 {
+ let sem = bg.semaphore.clone();
+ let order = order.clone();
+ handles.push(tokio::spawn(async move {
+ let _permit = sem.acquire_owned().await.unwrap();
+ order.lock().unwrap().push(i);
+ }));
+ // Let the new task register its acquire before spawning the
+ // next, mirroring the real loop where each spawn_subagent
+ // dispatch runs synchronously (dispatch order == waiter order).
+ tokio::task::yield_now().await;
+ }
+ // All three parked: none can start while the permit is held.
+ tokio::task::yield_now().await;
+ assert!(order.lock().unwrap().is_empty(), "cap holds while a child runs");
+ drop(running);
+ for h in handles {
+ h.await.unwrap();
+ }
+ assert_eq!(
+ *order.lock().unwrap(),
+ vec![0, 1, 2],
+ "FIFO: dispatch order is start order"
+ );
+ });
+ }
+
+ #[cfg(feature = "cli")]
+ #[tokio::test]
+ async fn dispatches_beyond_cap_emit_subagent_queued_and_promote_fifo() {
+ use crate::core::agent::events::StreamEvent;
+
+ let root = unique_root("maxpar");
+ let sub_dir = project_subagents_dir(&root);
+ write_def(&sub_dir, "reviewer", "");
+ let args = max_par_args(&root);
+
+ let bg = Arc::new(BackgroundSubagents::new(1));
+ let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel();
+ let mut starts = Vec::new();
+
+ let r1 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+ let r2 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+ let r3 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+ assert_ne!(r1, r2);
+ assert_ne!(r2, r3);
+
+ // The two beyond-cap dispatches must be reported queued, with their
+ // 1-based queue positions in dispatch order.
+ let mut queued = Vec::new();
+ while let Ok(ev) = events_rx.try_recv() {
+ if let StreamEvent::SubagentQueued { run_id, waiting, .. } = ev {
+ queued.push((run_id, waiting));
+ }
+ }
+ assert_eq!(queued.len(), 2, "two dispatches exceeded the cap of 1");
+ assert_eq!(queued[0], (r2.clone(), 1), "second dispatch queues first");
+ assert_eq!(queued[1], (r3.clone(), 2), "third dispatch queues behind it");
+
+ // The first dispatch is admitted immediately: it starts without a
+ // queued event (children fail fast without a provider, which is fine --
+ // we only assert the queueing/ordering contract here).
+ let out1 = await_subagent(&bg, &r1).await;
+ let out2 = await_subagent(&bg, &r2).await;
+ let out3 = await_subagent(&bg, &r3).await;
+ assert!(out1.is_err(), "child run fails without a provider (expected)");
+ assert!(out2.is_err() && out3.is_err(), "queued children also complete");
+
+ // Promotion must be FIFO: r2 started before r3.
+ while let Ok(ev) = events_rx.try_recv() {
+ if let StreamEvent::SubagentStart { run_id, .. } = ev {
+ starts.push(run_id);
+ }
+ }
+ let pos = |id: &str| starts.iter().position(|s| s == id);
+ assert!(
+ pos(&r2).unwrap() < pos(&r3).unwrap(),
+ "FIFO promotion: {starts:?}"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[cfg(feature = "cli")]
+ #[tokio::test]
+ async fn await_on_queued_run_blocks_until_a_slot_frees() {
+ use crate::core::agent::events::StreamEvent;
+
+ let root = unique_root("maxpar_await");
+ write_def(&project_subagents_dir(&root), "reviewer", "");
+ let args = max_par_args(&root);
+
+ let bg = Arc::new(BackgroundSubagents::new(1));
+ let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel();
+ // Occupy the only slot BEFORE dispatching, so every dispatch queues and
+ // the await below is deterministic: nothing can start while held.
+ let _running = bg.semaphore.clone().try_acquire_owned().unwrap();
+ let r1 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+ let r2 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+
+ // r2 is queued (not started), and awaiting it must NOT start it: the
+ // slot is still held, so the await parks. Assert via the events: no
+ // SubagentStart for either child yet.
+ let bg2 = bg.clone();
+ let r2b = r2.clone();
+ let awaited = tokio::spawn(async move { await_subagent(&bg2, &r2b).await });
+ tokio::task::yield_now().await;
+ tokio::task::yield_now().await;
+ assert!(!awaited.is_finished(), "await on a queued run must block");
+ while let Ok(ev) = events_rx.try_recv() {
+ assert!(
+ !matches!(ev, StreamEvent::SubagentStart { run_id, .. } if run_id == r2),
+ "awaiting a queued run must not start it early"
+ );
+ }
+
+ drop(_running); // free the slot: r1 promotes first (FIFO), then r2
+ assert!(
+ awaited.await.unwrap().is_err(),
+ "awaited queued run resolves once it gets a slot"
+ );
+ let _ = await_subagent(&bg, &r1).await;
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[cfg(feature = "cli")]
+ #[tokio::test]
+ async fn abort_all_cancels_queued_dispatches_too() {
+ use crate::core::agent::events::StreamEvent;
+
+ let root = unique_root("maxpar_abort");
+ write_def(&project_subagents_dir(&root), "reviewer", "");
+ let args = max_par_args(&root);
+
+ let bg = Arc::new(BackgroundSubagents::new(1));
+ let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel();
+ // Hold the slot before dispatching so r1, r2, r3 all queue (parked on
+ // the semaphore) -- the interesting teardown case.
+ let _running = bg.semaphore.clone().try_acquire_owned().unwrap();
+ let r1 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+ let r2 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+ let r3 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+
+ AbortOnDrop(bg.clone()); // teardown with queued children parked
+
+ let mut ends = Vec::new();
+ while let Ok(ev) = events_rx.try_recv() {
+ if let StreamEvent::SubagentEnd { run_id, .. } = ev {
+ ends.push(run_id);
+ }
+ }
+ assert!(ends.contains(&r2) && ends.contains(&r3), "queued children get SubagentEnd: {ends:?}");
+ assert!(
+ bg.inner.lock().unwrap().is_empty(),
+ "abort_all drains queued dispatches too"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[test]
fn schemas_list_available_names_in_dispatch_description() {
let reg = registry_with("reviewer", None);
- let schemas = subagent_tool_schemas(&reg);
- assert_eq!(schemas.len(), 4);
+ let schemas = subagent_tool_schemas(&reg, DEFAULT_MAX_PARALLEL_SUBAGENTS); assert_eq!(schemas.len(), 4);
let names: Vec<&str> = schemas
.iter()
.map(|s| s["function"]["name"].as_str().unwrap())
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 1d2224798..d5cd56b1c 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -523,6 +523,7 @@ fn build_cli_orchestration_args(
permission_requests: PermissionRegistry,
yolo: bool,
plan: bool,
+ max_parallel_subagents: u32,
) -> OrchestrationArgs {
OrchestrationArgs {
client: reqwest::Client::new(),
@@ -537,6 +538,7 @@ fn build_cli_orchestration_args(
todo_registry: None,
system_prompt_override: None,
subagents_enabled: true,
+ max_parallel_subagents,
yolo,
run_mode: if plan {
crate::core::agent::plan::RunMode::Plan
@@ -716,6 +718,10 @@ fn prepare_agent_session(
};
let permission_requests: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let max_parallel_subagents = cfg
+ .agent
+ .max_parallel_subagents
+ .unwrap_or(crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS);
let args = build_cli_orchestration_args(
project_root,
permissions,
@@ -725,6 +731,7 @@ fn prepare_agent_session(
permission_requests.clone(),
yolo,
plan,
+ max_parallel_subagents,
);
Ok(AgentSession {
@@ -998,6 +1005,9 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {
StreamEvent::SubagentStart { name, .. } => {
eprintln!("\x1b[2m[subagent:{name}] started (background)\x1b[0m")
}
+ StreamEvent::SubagentQueued { name, waiting, .. } => {
+ eprintln!("\x1b[2m[subagent:{name}] queued ({waiting} waiting)\x1b[0m")
+ }
StreamEvent::SubagentEnd { name, .. } => {
eprintln!("\x1b[2m[subagent:{name}] finished\x1b[0m")
}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index eec3da888..f2840303d 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -150,7 +150,7 @@ impl Pending {
}
/// What a highlighted picker row does on Enter.
-#[derive(PartialEq, Clone, Copy)]
+#[derive(PartialEq, Clone, Copy, Debug)]
enum PickerKind {
ResumeThread,
SelectModel,
@@ -161,6 +161,9 @@ enum PickerKind {
RewindScope,
/// Read-only view of `~/.jan/config.toml` providers (`/config`). Enter closes.
ViewConfig,
+ /// `/settings`: browse editable `[agent]` keys from agent.toml; Enter opens
+ /// a docked edit prompt for the selected row.
+ AgentSettings,
/// `/todo` editor: browse the phased list and mutate the selected task
/// (done/drop/rm) through the same canonical `TodoList` the model uses.
Todo,
@@ -183,6 +186,7 @@ impl Picker {
PickerKind::RewindMessage => " rewind to message ",
PickerKind::RewindScope => " restore ",
PickerKind::ViewConfig => " provider config ",
+ PickerKind::AgentSettings => " agent settings ",
PickerKind::Todo => " todo ",
}
}
@@ -195,6 +199,7 @@ impl Picker {
PickerKind::RewindMessage => " ↑/↓ select Enter choose Esc cancel",
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::Todo => " ↑/↓ select d done x abandon r remove Esc close",
}
}
@@ -567,6 +572,10 @@ struct App {
picker: Option<Picker>,
/// Active `/login` prompt; owns the keyboard while open.
login: Option<LoginPrompt>,
+ /// Active `/settings` edit prompt (docked like `/login`); owns the
+ /// keyboard while open. Holds the setting being edited and any validation
+ /// error; writes go straight to agent.toml on Enter.
+ settings_prompt: Option<SettingsPrompt>,
/// Key handed off to the loop to verify off the render loop. Taken once.
login_submit: Option<String>,
/// `/update` handed off to the loop, which spawns the install. Taken once.
@@ -699,6 +708,14 @@ struct SubagentPanel {
/// request -- no completed tool call yet, so a stats line frozen at
/// "0 tools" and an activity line stuck on "starting…".
active: Option<StartingCall>,
+ /// True while the dispatch is parked on the parent run's
+ /// `max_parallel_subagents` cap (reported via `SubagentQueued`); flipped
+ /// off when the child's `SubagentStart` arrives. Queued panels render
+ /// "queued (N waiting)" instead of live stats, so a capped fan-out reads
+ /// as a queue rather than a wall of silently-idle agents.
+ queued: bool,
+ /// 1-based position in the queue at the time the child was queued.
+ waiting: u32,
}
/// A committed finished-subagent summary row, folded to one line but retaining
@@ -800,6 +817,7 @@ impl App {
ask_queue: std::collections::VecDeque::new(),
picker: None,
login: None,
+ settings_prompt: None,
login_submit: None,
update_requested: false,
update_installing: false,
@@ -1761,7 +1779,36 @@ impl App {
.ask_queue
.push_back(PendingAsk::new(request_id, request)),
StreamEvent::SubagentStart { run_id, name, task } => {
- // Open a live rolling panel for this run; several may be active.
+ // A queued dispatch already opened a panel for this run; promote
+ // it to running instead of pushing a duplicate. Otherwise open a
+ // fresh live panel (several may be active).
+ if let Some(panel) = self.subagents.iter_mut().find(|p| p.run_id == run_id) {
+ panel.queued = false;
+ } else {
+ self.finalize_tool_group();
+ self.flush_assistant();
+ self.subagents.push(SubagentPanel {
+ run_id,
+ name,
+ task: task.unwrap_or_default(),
+ calls: Vec::new(),
+ requests: 0,
+ prompt_tokens: 0,
+ active: None,
+ queued: false,
+ waiting: 0,
+ });
+ }
+ }
+ StreamEvent::SubagentQueued {
+ run_id,
+ name,
+ task,
+ waiting,
+ } => {
+ // The cap is exhausted; this dispatch will start when a running
+ // child finishes. Open its panel now, marked queued, so the
+ // fan-out shows the queue instead of hiding dispatches.
self.finalize_tool_group();
self.flush_assistant();
self.subagents.push(SubagentPanel {
@@ -1772,6 +1819,8 @@ impl App {
requests: 0,
prompt_tokens: 0,
active: None,
+ queued: true,
+ waiting,
});
}
StreamEvent::SubagentEnd { run_id, name } => {
@@ -3938,6 +3987,12 @@ async fn handle_key(
return;
}
+ // The `/settings` edit dock owns the keyboard while open, same as `/login`.
+ if app.settings_prompt.is_some() {
+ handle_settings_key(app, key, ctrl);
+ return;
+ }
+
// A pending permission prompt captures y/a/n; Ctrl-C cancels the run and
// Ctrl-D quits, so it can't be wedged waiting on an unanswered prompt.
// Several subagents can have requests queued at once (see `pending_queue`),
@@ -4052,6 +4107,27 @@ async fn handle_key(
}
}
}
+ // `/settings` picker: `x` restores the selected key to its default
+ // by removing it from agent.toml - same write as clearing the
+ // field in the edit dock, one keypress instead of two.
+ KeyCode::Char('x') if picker.kind == PickerKind::AgentSettings => {
+ let key = picker.items[picker.selected].value.clone();
+ // (picker borrow ends here; nothing below reads it before rebuild)
+ let toml_path = app.agent_dir.join("agent.toml");
+ match crate::core::agent::project::set_agent_key(&toml_path, &key, None) {
+ Ok(()) => {
+ app.note(&format!(
+ "{key} unset (default applies); takes effect on the next run"
+ ));
+ if let Some(picker) = app.picker.as_mut() {
+ picker.items = build_agent_settings_items(&toml_path);
+ picker.selected =
+ picker.selected.min(picker.items.len().saturating_sub(1));
+ }
+ }
+ Err(e) => app.note(&format!("failed to write {}: {e}", toml_path.display())),
+ }
+ }
KeyCode::Enter => {
let kind = picker.kind;
let value = picker.items[picker.selected].value.clone();
@@ -4071,6 +4147,15 @@ async fn handle_key(
}
}
PickerKind::ViewConfig => {}
+ // `/settings`: open the edit dock for the selected row.
+ PickerKind::AgentSettings => {
+ if let Some(def) = AGENT_SETTINGS.iter().find(|d| d.key == value) {
+ let toml_path = app.agent_dir.join("agent.toml");
+ let current = current_agent_value(&toml_path, def.key);
+ app.settings_prompt =
+ Some(SettingsPrompt::new(def, current.as_deref()));
+ }
+ }
// Todo Enter is handled by the guarded action arm above.
PickerKind::Todo => {}
}
@@ -4334,6 +4419,11 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
hint: "",
description: "View provider config (~/.jan/config.toml)",
},
+ SlashCommand {
+ name: "/settings",
+ hint: "[max_parallel_subagents N]",
+ description: "Edit [agent] settings from agent.toml (menu); takes effect next run",
+ },
SlashCommand {
name: "/update",
hint: "",
@@ -4455,6 +4545,7 @@ async fn run_command(app: &mut App, line: &str) {
"login" => open_login_prompt(app),
"update" => update_command(app),
"config" => open_config_screen(app),
+ "settings" => settings_command(app, arg),
"goal" => goal_command(app, arg),
"plan" => plan_command(app, arg),
"todo" => todo_command(app, arg).await,
@@ -4518,6 +4609,292 @@ fn goal_command(app: &mut App, arg: &str) {
}
}
+/// One editable `[agent]` key surfaced by `/settings`. Mirrors the template's
+/// knobs; defaults match `load_agent_config`. `model` is deliberately absent:
+/// it has its own `/model` picker.
+struct AgentSettingDef {
+ key: &'static str,
+ label: &'static str,
+ desc: &'static str,
+ kind: AgentSettingKind,
+}
+
+enum AgentSettingKind {
+ Int { default: Option<u64>, min: u64 },
+ Text { default: &'static str },
+ /// Exact-match choice: Enter writes one of `options`, cleared field
+ /// unsets. Covers the `read-only | deny | allow` and `always | relevance`
+ /// toggles that hand-editing agent.toml previously required.
+ Enum { options: &'static [&'static str], default: &'static str },
+}
+
+const AGENT_SETTINGS: &[AgentSettingDef] = &[
+ AgentSettingDef {
+ key: "max_turns",
+ label: "max_turns",
+ desc: "turns per message, clamped 1-400",
+ kind: AgentSettingKind::Int { default: Some(400), min: 1 },
+ },
+ AgentSettingDef {
+ key: "context_window",
+ label: "context_window",
+ desc: "context limit in tokens",
+ kind: AgentSettingKind::Int { default: Some(128000), min: 1 },
+ },
+ AgentSettingDef {
+ key: "compaction_reserve_tokens",
+ label: "compaction_reserve_tokens",
+ desc: "headroom kept free before compaction",
+ kind: AgentSettingKind::Int { default: Some(16384), min: 0 },
+ },
+ AgentSettingDef {
+ key: "max_tokens",
+ label: "max_tokens",
+ desc: "cap on tokens generated per response (omitted when unset)",
+ kind: AgentSettingKind::Int { default: None, min: 1 },
+ },
+ AgentSettingDef {
+ key: "max_parallel_subagents",
+ label: "max_parallel_subagents",
+ desc: "subagents that may run at once; extra dispatches queue FIFO",
+ kind: AgentSettingKind::Int { default: Some(10), min: 1 },
+ },
+ AgentSettingDef {
+ key: "instructions_file",
+ label: "instructions_file",
+ desc: "markdown injected into the system prompt",
+ kind: AgentSettingKind::Text { default: "AGENT.md" },
+ },
+ AgentSettingDef {
+ key: "budget.max_steps",
+ label: "budget.max_steps",
+ desc: "max tool-call steps per run",
+ kind: AgentSettingKind::Int { default: Some(40), min: 1 },
+ },
+ AgentSettingDef {
+ key: "budget.max_tokens",
+ label: "budget.max_tokens",
+ desc: "max tokens budget per run",
+ kind: AgentSettingKind::Int { default: Some(200000), min: 1 },
+ },
+ AgentSettingDef {
+ key: "tools.default",
+ label: "tools.default",
+ desc: "tool permission mode; deny locks down MCP tools",
+ kind: AgentSettingKind::Enum {
+ options: &["read-only", "deny", "allow"],
+ default: "read-only",
+ },
+ },
+ AgentSettingDef {
+ key: "skills.inject",
+ label: "skills.inject",
+ desc: "when project skills are injected into the prompt",
+ kind: AgentSettingKind::Enum {
+ options: &["always", "relevance"],
+ default: "always",
+ },
+ },
+];
+
+/// Docked edit prompt for one `/settings` row: value field, inline validation
+/// error, Enter saves / Esc cancels / cleared field unsets.
+struct SettingsPrompt {
+ key: &'static str,
+ input: String,
+ error: Option<String>,
+}
+
+impl SettingsPrompt {
+ fn new(def: &AgentSettingDef, current: Option<&str>) -> Self {
+ Self {
+ key: def.key,
+ input: current.unwrap_or_default().to_string(),
+ error: None,
+ }
+ }
+
+ fn def(&self) -> &'static AgentSettingDef {
+ AGENT_SETTINGS
+ .iter()
+ .find(|d| d.key == self.key)
+ .expect("settings prompt always opens for a def row")
+ }
+}
+
+/// Value of an `[agent]` key in `agent.toml` as a display string, `None` when
+/// unset or the file is unreadable. Reads the inner value directly so the
+/// display is not padded by the document's alignment.
+fn current_agent_value(toml_path: &std::path::Path, key: &str) -> Option<String> {
+ let raw = std::fs::read_to_string(toml_path).ok()?;
+ let doc = raw.parse::<toml_edit::DocumentMut>().ok()?;
+ let (section, key) = match key.split_once('.') {
+ Some((section, key)) => (section, key),
+ None => ("agent", key),
+ };
+ let item = doc.get(section)?.get(key)?;
+ Some(match item.as_value() {
+ Some(toml_edit::Value::Integer(i)) => i.value().to_string(),
+ Some(toml_edit::Value::String(s)) => s.value().to_string(),
+ Some(toml_edit::Value::Boolean(b)) => b.value().to_string(),
+ _ => item.to_string(),
+ })
+}
+
+/// `/settings` dispatcher: bare opens the interactive settings menu (an
+/// `AgentSettings` picker over the `[agent]` keys; Enter on a row docks an edit
+/// prompt); `max_parallel_subagents <N>` still works as a one-shot shortcut.
+/// Writes are format-preserving and take effect on the next run (the current
+/// run snapshotted its config at start). Runs only while idle, like every
+/// command.
+fn settings_command(app: &mut App, arg: &str) {
+ let toml_path = app.agent_dir.join("agent.toml");
+ let arg = arg.trim();
+ let Some((key, value)) = arg.split_once(char::is_whitespace) else {
+ return open_settings_screen(app);
+ };
+ match key {
+ "max_parallel_subagents" => {
+ let n: u64 = match value.parse() {
+ Ok(n) => n,
+ Err(_) => return app.note(&format!("'{value}' is not an integer")),
+ };
+ if n < 1 {
+ return app.note("max_parallel_subagents must be at least 1");
+ }
+ match crate::core::agent::project::set_agent_key(
+ &toml_path,
+ key,
+ Some(toml_edit::value(n as i64)),
+ ) {
+ Ok(()) => app.note(&format!(
+ "max_parallel_subagents = {n} written; takes effect on the next run"
+ )),
+ Err(e) => app.note(&format!("failed to write {}: {e}", toml_path.display())),
+ }
+ }
+ other => app.note(&format!(
+ "unknown setting '/settings {other}' (bare /settings opens the menu)"
+ )),
+ }
+}
+
+/// One picker row per `[agent]` def; the hint carries the current on-disk
+/// value (`= 400`) or `(unset)` when the default applies. `value` is the key
+/// so the edit dock and the `x` unset shortcut can act on it.
+fn build_agent_settings_items(toml_path: &std::path::Path) -> Vec<PickerItem> {
+ AGENT_SETTINGS
+ .iter()
+ .map(|def| {
+ let current = current_agent_value(toml_path, def.key);
+ PickerItem {
+ value: def.key.to_string(),
+ label: def.label.to_string(),
+ hint: Some(match &current {
+ Some(v) => format!("= {v}"),
+ None => "(unset)".to_string(),
+ }),
+ checkbox: None,
+ }
+ })
+ .collect()
+}
+
+/// Open the `/settings` menu: a picker row per `[agent]` key, hint showing the
+/// current value (or `unset`), Enter docking the edit prompt for that row, `x`
+/// removing the key so its default applies again.
+fn open_settings_screen(app: &mut App) {
+ let toml_path = app.agent_dir.join("agent.toml");
+ app.picker = Some(Picker {
+ kind: PickerKind::AgentSettings,
+ items: build_agent_settings_items(&toml_path),
+ selected: 0,
+ });
+}
+
+/// Keyboard for the `/settings` edit dock: chars/backspace edit the field,
+/// Enter validates and writes (empty clears the key), Esc cancels. Mirrors
+/// `handle_login_key`, minus the secret/verify machinery.
+fn handle_settings_key(app: &mut App, key: KeyEvent, ctrl: bool) {
+ if (key.code == KeyCode::Esc || (ctrl && key.code == KeyCode::Char('c'))) && app.settings_prompt.is_some()
+ {
+ app.settings_prompt = None;
+ return;
+ }
+ let Some(prompt) = app.settings_prompt.as_mut() else {
+ return;
+ };
+ 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::Text { .. } => {
+ if prompt.input.trim().is_empty() {
+ None
+ } else {
+ Some(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;
+ }
+ }
+ };
+ match crate::core::agent::project::set_agent_key(&toml_path, prompt.key, value) {
+ Ok(()) => {
+ let what = if prompt.input.trim().is_empty() {
+ format!("{} unset (default applies)", prompt.key)
+ } else {
+ format!("{} = {} written", prompt.key, prompt.input.trim())
+ };
+ app.note(&format!("{what}; takes effect on the next run"));
+ app.settings_prompt = None;
+ }
+ Err(e) => {
+ prompt.error = Some(format!("failed to write {}: {e}", toml_path.display()));
+ }
+ }
+ }
+ KeyCode::Backspace => {
+ prompt.input.pop();
+ }
+ KeyCode::Char(ch) if !ctrl => prompt.input.push(ch),
+ _ => {}
+ }
+}
+
/// `/plan` dispatcher: bare enters read-only plan mode, `/plan exit` leaves
/// it, and `/plan <text>` enters plan mode (if not already in it) and
/// immediately submits `<text>` as the first message to investigate — same
@@ -5587,7 +5964,8 @@ fn draw(f: &mut Frame, app: &mut App) {
if let Some(picker) = &app.picker {
app.row_index.clear();
- draw_picker(f, chunks[1], picker);
+ let toml_path = app.agent_dir.join("agent.toml");
+ draw_picker(f, chunks[1], picker, &toml_path);
f.render_widget(input_box(app), chunks[2]);
f.render_widget(path_line(app), chunks[3]);
f.render_widget(footer(app), chunks[4]);
@@ -5794,6 +6172,17 @@ fn draw(f: &mut Frame, app: &mut App) {
height,
};
draw_login(f, rect, prompt);
+ } else if let Some(prompt) = &app.settings_prompt {
+ let height = (5 + u16::from(prompt.error.is_some())).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,
+ };
+ let toml_path = app.agent_dir.join("agent.toml");
+ draw_settings_prompt(f, rect, prompt, &toml_path);
} else if !app.ask_queue.is_empty() {
let queue_len = app.ask_queue.len();
let ask = app.ask_queue.front_mut().expect("checked non-empty above");
@@ -6017,6 +6406,69 @@ fn draw_login(f: &mut Frame, area: ratatui::layout::Rect, prompt: &LoginPrompt)
f.render_widget(Paragraph::new(lines), inner);
}
+/// Docked `/settings` edit prompt, styled like the `/login` dock: description,
+/// the current on-disk value, the field being edited, an inline validation
+/// error when one fired, and the save/cancel keys.
+fn draw_settings_prompt(
+ f: &mut Frame,
+ area: ratatui::layout::Rect,
+ prompt: &SettingsPrompt,
+ toml_path: &std::path::Path,
+) {
+ use ratatui::widgets::Clear;
+
+ let dim = Style::new().dark_gray();
+ let def = prompt.def();
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .border_style(Style::new().cyan())
+ .title(Span::styled(
+ format!(" agent settings: {} ", def.key),
+ Style::new().on_cyan().black().bold(),
+ ));
+
+ let mut lines = vec![Line::from(vec![
+ Span::styled(def.desc, dim),
+ Span::styled(" current: ", dim),
+ Span::styled(
+ current_agent_value(toml_path, def.key).unwrap_or_else(|| "unset".to_string()),
+ Style::new().cyan(),
+ ),
+ ])];
+ lines.push(Line::styled(
+ match def.kind {
+ AgentSettingKind::Int { default, min } => {
+ let d = default
+ .map(|d| d.to_string())
+ .unwrap_or_else(|| "unset".to_string());
+ format!("default: {d} · valid: >= {min}")
+ }
+ AgentSettingKind::Text { default } => format!("default: {default}"),
+ AgentSettingKind::Enum { options, default } => {
+ format!("default: {default} · valid: {}", options.join(" | "))
+ }
+ },
+ dim,
+ ));
+ if let Some(error) = &prompt.error {
+ lines.push(Line::styled(error.clone(), Style::new().red()));
+ }
+ lines.push(Line::from(vec![
+ Span::styled("value: ", Style::new().bold()),
+ Span::raw(prompt.input.clone()),
+ Span::styled("█", Style::new().cyan()),
+ ]));
+ lines.push(Line::styled(
+ "Enter save · Esc cancel · clear field to unset (default applies)".to_string(),
+ dim,
+ ));
+
+ f.render_widget(Clear, area);
+ let inner = block.inner(area);
+ f.render_widget(block, area);
+ f.render_widget(Paragraph::new(lines), inner);
+}
+
/// Slash-command hint popup: one row per match (`/name [hint] description`),
/// the highlighted row reversed. Docked above the input box.
fn draw_slash_hints(
@@ -6169,7 +6621,12 @@ fn draw_permission(f: &mut Frame, area: ratatui::layout::Rect, pending: &Pending
f.render_stateful_widget(list, rows[2], &mut state);
}
-fn draw_picker(f: &mut Frame, area: ratatui::layout::Rect, picker: &Picker) {
+fn draw_picker(
+ f: &mut Frame,
+ area: ratatui::layout::Rect,
+ picker: &Picker,
+ toml_path: &std::path::Path,
+) {
use ratatui::widgets::{List, ListItem, ListState};
let items: Vec<ListItem> = picker
@@ -6198,7 +6655,57 @@ fn draw_picker(f: &mut Frame, area: ratatui::layout::Rect, picker: &Picker) {
.highlight_symbol("▶ ");
let mut state = ListState::default();
state.select(Some(picker.selected));
- f.render_stateful_widget(list, area, &mut state);
+
+ // The settings menu keeps two rows under the list for the selected
+ // setting's description, default, valid range, and current value - the
+ // rows themselves stay terse (`key = value`) because the detail footer
+ // explains what each knob does.
+ if picker.kind == PickerKind::AgentSettings {
+ let list_area = Rect {
+ height: area.height.saturating_sub(2),
+ ..area
+ };
+ f.render_stateful_widget(list, list_area, &mut state);
+ if let Some(def) = picker
+ .items
+ .get(picker.selected)
+ .and_then(|it| AGENT_SETTINGS.iter().find(|d| d.key == it.value))
+ {
+ let current = current_agent_value(toml_path, def.key)
+ .unwrap_or_else(|| "unset".to_string());
+ let meta = match def.kind {
+ AgentSettingKind::Int { default, min } => {
+ let d = default
+ .map(|d| d.to_string())
+ .unwrap_or_else(|| "unset".to_string());
+ format!("default: {d} · valid: >= {min} · current: {current}")
+ }
+ AgentSettingKind::Text { default } => {
+ format!("default: {default} · current: {current}")
+ }
+ AgentSettingKind::Enum { options, default } => {
+ format!(
+ "default: {default} · valid: {} · current: {current}",
+ options.join(" | ")
+ )
+ }
+ };
+ let dim = Style::new().dark_gray();
+ f.render_widget(
+ Paragraph::new(vec![
+ Line::styled(def.desc.to_string(), dim),
+ Line::styled(meta, dim),
+ ]),
+ Rect {
+ y: list_area.y + list_area.height,
+ height: area.height - list_area.height,
+ ..area
+ },
+ );
+ }
+ } else {
+ f.render_stateful_widget(list, area, &mut state);
+ }
}
/// Render a duration as a compact `"12s"` / `"3m12s"` / `"1h04m"` label.
@@ -6244,9 +6751,37 @@ fn subagent_panel_lines(
let mut spans = vec![
Span::styled(" • ", Style::new().magenta()),
Span::styled(panel.name.clone(), Style::new().magenta()),
- Span::styled(format!(" {}", pluralize("tool", panel.calls.len())), dim),
- Span::styled(format!(" · {} req", panel.requests), dim),
];
+ if panel.queued {
+ // Parked on the `max_parallel_subagents` cap; the child has not
+ // started, so there are no live stats to show -- render its queue
+ // position and task instead.
+ spans.push(Span::styled(
+ format!(" queued ({} waiting)", panel.waiting),
+ Style::new().yellow(),
+ ));
+ out.push(Line::from(spans));
+ for (written, raw) in panel
+ .task
+ .lines()
+ .filter(|l| !l.trim().is_empty())
+ .enumerate()
+ {
+ if written == task_lines {
+ break;
+ }
+ out.push(indented_row(
+ truncate(raw.trim(), task_width),
+ Style::new().dim().italic(),
+ ));
+ }
+ continue;
+ }
+ spans.push(Span::styled(
+ format!(" {}", pluralize("tool", panel.calls.len())),
+ dim,
+ ));
+ spans.push(Span::styled(format!(" · {} req", panel.requests), dim));
// Only once the child has reported usage; "0.0%" before its first
// response would read as a stalled agent rather than a starting one.
if panel.prompt_tokens > 0 && context_window > 0 {
@@ -6825,7 +7360,7 @@ mod tests {
tool_activity, tool_finished,
transcript_top_padding,
user_content_parts, App, CurrentRun, Pending, PendingImage, PickerKind, ResumeTarget,
- SnapshotJob, Status, DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS, DIFF_PREVIEW_MAX_ROWS,
+ SnapshotJob, Status, AGENT_SETTINGS, DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS, DIFF_PREVIEW_MAX_ROWS,
KEY_BINDINGS, SLASH_COMMANDS, SPINNER,
SPINNER_ADVANCE_MS,
};
@@ -6843,6 +7378,11 @@ mod tests {
use std::collections::HashMap;
use std::sync::Arc;
+ /// A bare key press with no modifiers.
+ fn key(code: KeyCode) -> KeyEvent {
+ KeyEvent::new(code, KeyModifiers::NONE)
+ }
+
fn test_app() -> App {
// Persist into a unique temp dir so tests that save threads never
// dirty the working tree (src-tauri/threads/).
@@ -8392,6 +8932,299 @@ mod tests {
assert!(beta.calls.last().unwrap().contains("beta-cmd"));
}
+ #[test]
+ fn queued_panel_promotes_to_running_without_duplicate() {
+ let mut app = test_app();
+ app.apply(StreamEvent::SubagentQueued {
+ run_id: "r1".into(),
+ name: "reviewer".into(),
+ task: Some("queue up".into()),
+ waiting: 2,
+ });
+ let queued = app.subagents.iter().find(|p| p.run_id == "r1").expect("queued panel");
+ assert!(queued.queued, "dispatch beyond the cap opens a queued panel");
+ assert_eq!(queued.waiting, 2);
+
+ // The child's later SubagentStart must flip the same panel to running,
+ // not push a duplicate.
+ app.apply(StreamEvent::SubagentStart {
+ run_id: "r1".into(),
+ name: "reviewer".into(),
+ task: None,
+ });
+ assert_eq!(app.subagents.len(), 1, "no duplicate panel on promotion");
+ let promoted = app.subagents.iter().find(|p| p.run_id == "r1").unwrap();
+ assert!(!promoted.queued, "promoted panel is now running");
+ }
+
+ #[test]
+ fn queued_panel_renders_queue_position() {
+ let mut app = test_app();
+ app.apply(StreamEvent::SubagentQueued {
+ run_id: "r1".into(),
+ name: "reviewer".into(),
+ task: Some("task".into()),
+ waiting: 3,
+ });
+ let rows = render_rows(&mut app, 80, 20);
+ assert!(
+ rows.iter().any(|r| r.contains("queued (3 waiting)")),
+ "queued panel shows its position: {rows:?}"
+ );
+ }
+
+ #[test]
+ fn settings_command_bare_opens_picker_and_inline_set_writes_toml() {
+ let mut app = test_app();
+ // A minimal agent.toml so the picker shows a real current value.
+ std::fs::create_dir_all(&app.agent_dir).unwrap();
+ let toml_path = app.agent_dir.join("agent.toml");
+ std::fs::write(&toml_path, "[agent]\nmax_turns = 8\n").unwrap();
+
+ super::settings_command(&mut app, "max_parallel_subagents 20");
+ let doc = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(
+ doc.contains("max_parallel_subagents = 20"),
+ "key written: {doc}"
+ );
+ assert!(doc.contains("max_turns = 8"), "other keys preserved: {doc}");
+
+ // Zero is invalid: rejected, file unchanged.
+ super::settings_command(&mut app, "max_parallel_subagents 0");
+ let doc = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(
+ doc.contains("max_parallel_subagents = 20"),
+ "rejected write must not clobber: {doc}"
+ );
+ assert!(transcript_text(&app).contains("must be at least 1"));
+
+ // Bare opens the settings picker with a row per def, hints carrying
+ // the on-disk current value (no key prefix; the label is the key).
+ super::settings_command(&mut app, "");
+ let picker = app.picker.as_ref().expect("bare /settings opens picker");
+ assert_eq!(picker.kind, PickerKind::AgentSettings);
+ assert_eq!(picker.items.len(), AGENT_SETTINGS.len());
+ let row = picker
+ .items
+ .iter()
+ .find(|i| i.value == "max_turns")
+ .expect("max_turns row present");
+ assert_eq!(row.hint.as_deref(), Some("= 8"));
+ let row = picker
+ .items
+ .iter()
+ .find(|i| i.value == "max_parallel_subagents")
+ .expect("max_parallel_subagents row present");
+ assert_eq!(row.hint.as_deref(), Some("= 20"));
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
+ #[tokio::test]
+ async fn settings_picker_x_unsets_selected_key() {
+ 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]\nmax_turns = 8\n").unwrap();
+
+ super::settings_command(&mut app, "");
+ // Select the max_turns row (index 0) and press x: the key must be
+ // removed, the row hint flip back to (unset), the note rendered.
+ press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE).await;
+ let doc = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(!doc.contains("max_turns = 8"), "key removed: {doc}");
+ assert!(transcript_text(&app).contains("max_turns unset"));
+ let picker = app.picker.as_ref().expect("picker stays open");
+ let row = picker
+ .items
+ .iter()
+ .find(|i| i.value == "max_turns")
+ .expect("max_turns row present");
+ assert_eq!(row.hint.as_deref(), Some("(unset)"));
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
+ #[test]
+ fn settings_command_rejects_non_integer_and_unknown_keys() {
+ 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();
+
+ super::settings_command(&mut app, "max_parallel_subagents lots");
+ assert!(transcript_text(&app).contains("is not an integer"));
+ super::settings_command(&mut app, "warp_drive 5");
+ assert!(transcript_text(&app).contains("unknown setting"));
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
+ #[test]
+ fn settings_prompt_enter_writes_and_closes() {
+ 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 == "max_parallel_subagents")
+ .unwrap();
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));
+ super::handle_settings_key(&mut app, key(KeyCode::Char('3')), false);
+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
+ assert!(app.settings_prompt.is_none(), "Enter closes the dock");
+ let doc = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(doc.contains("max_parallel_subagents = 3"), "{doc}");
+ assert!(transcript_text(&app).contains("max_parallel_subagents = 3 written"));
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
+ #[test]
+ fn settings_prompt_esc_cancels_without_writing() {
+ 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]\nmax_parallel_subagents = 7\n").unwrap();
+
+ let def = AGENT_SETTINGS
+ .iter()
+ .find(|d| d.key == "max_parallel_subagents")
+ .unwrap();
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, Some("7")));
+ super::handle_settings_key(&mut app, key(KeyCode::Char('9')), false);
+ super::handle_settings_key(&mut app, key(KeyCode::Esc), false);
+ assert!(app.settings_prompt.is_none());
+ let doc = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(doc.contains("max_parallel_subagents = 7"), "unchanged: {doc}");
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
+ #[test]
+ fn settings_prompt_cleared_field_unsets_key() {
+ 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]\nmax_turns = 8\n").unwrap();
+
+ let def = AGENT_SETTINGS.iter().find(|d| d.key == "max_turns").unwrap();
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, Some("8")));
+ super::handle_settings_key(&mut app, key(KeyCode::Backspace), false);
+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
+ assert!(app.settings_prompt.is_none());
+ let doc = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(!doc.contains("max_turns = 8"), "key removed: {doc}");
+ assert!(transcript_text(&app).contains("max_turns unset"));
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
+ #[test]
+ fn settings_prompt_rejects_below_min_and_garbage() {
+ 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 == "max_parallel_subagents")
+ .unwrap();
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));
+ super::handle_settings_key(&mut app, key(KeyCode::Char('0')), false);
+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
+ assert!(app.settings_prompt.is_some(), "dock stays open on error");
+ let err = app
+ .settings_prompt
+ .as_ref()
+ .and_then(|p| p.error.clone())
+ .expect("error recorded");
+ assert!(err.contains("at least 1"), "{err}");
+ assert_eq!(std::fs::read_to_string(&toml_path).unwrap(), "[agent]\n");
+
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));
+ super::handle_settings_key(&mut app, key(KeyCode::Char('x')), false);
+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
+ let err = app
+ .settings_prompt
+ .as_ref()
+ .and_then(|p| p.error.clone())
+ .expect("error recorded");
+ assert!(err.contains("not an integer"), "{err}");
+ assert_eq!(std::fs::read_to_string(&toml_path).unwrap(), "[agent]\n");
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
+ #[test]
+ fn settings_prompt_edits_text_key() {
+ 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 == "instructions_file")
+ .unwrap();
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));
+ for ch in "AGENTS.md".chars() {
+ super::handle_settings_key(&mut app, key(KeyCode::Char(ch)), false);
+ }
+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
+ assert!(app.settings_prompt.is_none());
+ let doc = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(doc.contains("instructions_file = \"AGENTS.md\""), "{doc}");
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
+ #[test]
+ fn settings_prompt_edits_enum_key() {
+ 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[tools]\ndefault = \"read-only\"\n").unwrap();
+
+ let def = AGENT_SETTINGS
+ .iter()
+ .find(|d| d.key == "tools.default")
+ .unwrap();
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));
+ for ch in "deny".chars() {
+ super::handle_settings_key(&mut app, key(KeyCode::Char(ch)), false);
+ }
+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
+ assert!(app.settings_prompt.is_none());
+ let doc = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(doc.contains("default = \"deny\""), "written under [tools]: {doc}");
+ assert!(transcript_text(&app).contains("tools.default = deny written"));
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
+ #[test]
+ fn settings_prompt_rejects_enum_garbage() {
+ 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[tools]\ndefault = \"read-only\"\n").unwrap();
+
+ let def = AGENT_SETTINGS
+ .iter()
+ .find(|d| d.key == "tools.default")
+ .unwrap();
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));
+ for ch in "aggressive".chars() {
+ super::handle_settings_key(&mut app, key(KeyCode::Char(ch)), false);
+ }
+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
+ assert!(app.settings_prompt.is_some(), "dock stays open on error");
+ let err = app
+ .settings_prompt
+ .as_ref()
+ .and_then(|p| p.error.clone())
+ .expect("error recorded");
+ assert!(err.contains("read-only | deny | allow"), "{err}");
+ let doc = std::fs::read_to_string(&toml_path).unwrap();
+ assert!(doc.contains("default = \"read-only\""), "unchanged: {doc}");
+ let _ = std::fs::remove_dir_all(&app.agent_dir);
+ }
+
#[test]
fn finished_subagent_summary_expands_full_call_list_via_ctrl_o() {
let mut app = test_app();