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): configurable ask-tool timeout with recommended auto-select

thinhlpge334a0809789
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index 1e96fadd9..a3c404461 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -102,6 +102,12 @@ pub enum StreamEvent {
request_id: String,
request: crate::core::agent::interaction::AskRequest,
},
+ /// An `ask` request the loop resolved without a user answer (it timed out
+ /// and auto-selected). Tells a client showing the live prompt for
+ /// `request_id` to dismiss it, since no `respond` from that client is
+ /// coming. User-driven answers never emit this: the client clears its own
+ /// prompt as it responds.
+ AskResolved { request_id: String },
/// The canonical todo list changed (tool mutation or user edit in the
/// TUI). Carries the full resulting snapshot for reconstruction.
TodoUpdate {
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 9b93117b2..63f42f17f 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -29,6 +29,11 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.
# stream_reasoning = false # stop streaming reasoning into the TUI
# # live tail while it folds; only the
# # [thinking] badge shows it. On by default
+# ask_timeout_secs = 60 # auto-answer an unanswered `ask` prompt
+# # after this many seconds, choosing each
+# # question's recommended option (else its
+# # first). 0 or unset waits forever, the
+# # default
# terminal_hint = false # stop the startup note that offers
# # /terminal-setup when this terminal is
# # dropping Shift+Enter or Option+Delete.
@@ -74,6 +79,12 @@ struct GlobalConfigToml {
/// reasoning for good.
#[serde(default, skip_serializing_if = "Option::is_none")]
stream_reasoning: Option<bool>,
+ /// Auto-answer an unanswered `ask` tool prompt after this many seconds,
+ /// selecting each question's recommended option (or its first option when
+ /// none is recommended). `None` = the default, and `0` is treated the same:
+ /// wait forever, blocking the run on the ask exactly as it does today.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ ask_timeout_secs: Option<u64>,
/// Offer `/terminal-setup` at startup when a config file proves this
/// terminal is dropping a modified key. `None` = the default, on. For the
/// user who has read the note and decided to keep `Option` composing
@@ -272,6 +283,22 @@ pub(crate) fn stream_reasoning_enabled() -> bool {
.unwrap_or(true)
}
+/// How long an unanswered `ask` prompt waits before it auto-answers with each
+/// question's recommended option (`ask_timeout_secs` in `~/.jan/config.toml`).
+/// `None` -- the default -- means wait forever, preserving today's blocking
+/// behavior until the user answers; `0` is treated the same as unset so the
+/// disabling value and the absent key agree.
+///
+/// A malformed config yields `None` (wait forever) rather than an error: an
+/// unreadable preference must never be the thing that changes how a run blocks.
+pub(crate) fn ask_timeout() -> Option<std::time::Duration> {
+ load_raw()
+ .ok()
+ .and_then(|config| config.ask_timeout_secs)
+ .filter(|secs| *secs > 0)
+ .map(std::time::Duration::from_secs)
+}
+
/// The default glyph swept along the working row when `wave` is absent.
pub(crate) const WAVE_DEFAULT: &str = "👋";
@@ -769,6 +796,23 @@ mod tests {
});
}
+ #[test]
+ fn ask_timeout_defaults_off_and_treats_zero_as_unset() {
+ with_temp_home(|_| {
+ assert_eq!(ask_timeout(), None, "missing file -> wait forever");
+ let path = ensure_global_config().expect("ensure");
+ assert_eq!(ask_timeout(), None, "scaffolded file -> wait forever");
+
+ std::fs::write(&path, "ask_timeout_secs = 0\n").unwrap();
+ assert_eq!(ask_timeout(), None, "0 is the disabling value, not 0s");
+ std::fs::write(&path, "ask_timeout_secs = 30\n").unwrap();
+ assert_eq!(ask_timeout(), Some(std::time::Duration::from_secs(30)));
+
+ std::fs::write(&path, "not valid toml [[[").unwrap();
+ assert_eq!(ask_timeout(), None, "an unreadable config waits forever");
+ });
+ }
+
#[test]
fn ensure_scaffolds_and_is_idempotent() {
with_temp_home(|home| {
diff --git a/src-tauri/src/core/agent/interaction.rs b/src-tauri/src/core/agent/interaction.rs
index 51381e8be..ae5e60312 100644
--- a/src-tauri/src/core/agent/interaction.rs
+++ b/src-tauri/src/core/agent/interaction.rs
@@ -156,6 +156,26 @@ impl AskRequest {
.collect::<Vec<_>>()
.join("\n")
}
+
+ /// The results the loop falls back to when an `ask` times out with no user
+ /// answer: each question resolved to its `recommended` option, or its first
+ /// option when none is recommended. A multi-select question collapses to a
+ /// single selected label. `parse` guarantees the index is in range and that
+ /// no real option carries `OTHER_LABEL` (it is appended only for the user's
+ /// UI), so every label here is one `validate_results` accepts.
+ pub(crate) fn auto_selected_results(&self) -> Vec<QuestionResult> {
+ self.questions
+ .iter()
+ .map(|question| {
+ let index = question.recommended.unwrap_or(0);
+ QuestionResult {
+ id: question.id.clone(),
+ selected: vec![question.options[index].label.clone()],
+ custom_input: None,
+ }
+ })
+ .collect()
+ }
}
pub(crate) fn ask_tool_schema() -> Value {
@@ -308,6 +328,43 @@ mod tests {
assert!(req.validate_results(&both).is_err());
}
+ #[test]
+ fn auto_selection_follows_recommended_then_first_and_validates() {
+ // Recommended present -> that option; multi-select collapses to one.
+ let recommended = AskRequest::parse(&json!({
+ "questions": [{
+ "id": "scope",
+ "question": "Which scope?",
+ "options": [{"label": "Small"}, {"label": "Large"}, {"label": "Huge"}],
+ "multi": true,
+ "recommended": 1
+ }]
+ }))
+ .unwrap();
+ let results = recommended.auto_selected_results();
+ assert_eq!(results[0].selected, vec!["Large"]);
+ assert!(recommended.validate_results(&results).is_ok());
+
+ // No recommended -> first option.
+ let first = AskRequest::parse(&json!({
+ "questions": [{
+ "id": "scope",
+ "question": "Which scope?",
+ "options": [{"label": "Alpha"}, {"label": "Beta"}]
+ }]
+ }))
+ .unwrap();
+ let results = first.auto_selected_results();
+ assert_eq!(results[0].selected, vec!["Alpha"]);
+ assert!(first.validate_results(&results).is_ok());
+
+ // Every auto-selected label is a real option, never the UI-only OTHER.
+ for question in first.questions.iter().chain(recommended.questions.iter()) {
+ let picked = &question.options[question.recommended.unwrap_or(0)].label;
+ assert_ne!(picked, OTHER_LABEL);
+ }
+ }
+
#[tokio::test]
async fn registry_rejects_stale_response_and_cancel_drains_waiters() {
let registry = new_registry();
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index ede8ac7d9..d625714c8 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -322,6 +322,20 @@ fn resolve_sandbox(_flag: Option<bool>, _configured: Option<bool>) -> bool {
DEFAULT_SANDBOX
}
+/// The configured `ask` auto-answer timeout. The setting lives in the
+/// CLI-only `global_config` module (the desktop `ask` surface is not wired up
+/// yet), so the desktop build has no timeout and blocks on an ask forever,
+/// exactly as it does today.
+#[cfg(feature = "cli")]
+fn ask_timeout_setting() -> Option<std::time::Duration> {
+ crate::core::agent::global_config::ask_timeout()
+}
+
+#[cfg(not(feature = "cli"))]
+fn ask_timeout_setting() -> Option<std::time::Duration> {
+ None
+}
+
/// Whether `bash` would be confined in `project_root` with no `--sandbox` flag
/// passed: the answer `jan cli agent status` reports and the TUI notices on.
pub fn effective_sandbox(project_root: &std::path::Path) -> bool {
@@ -536,7 +550,34 @@ impl CompositeToolInvoker {
.await;
return "ERROR [ask_cancelled]: interactive UI disconnected".to_string();
}
- match receiver.await {
+ let outcome = match ask_timeout_setting() {
+ Some(duration) => match tokio::time::timeout(duration, receiver).await {
+ Ok(received) => received,
+ Err(_elapsed) => {
+ // No answer in time: auto-select each question's recommended
+ // (else first) option. Deregister so a late user answer is
+ // rejected, and tell the UI to drop the now-dead prompt. This
+ // is a distinct resolution from a user cancel, so it never
+ // returns the `ask_cancelled` error below.
+ let results = request.auto_selected_results();
+ let _ = crate::core::agent::interaction::respond(
+ registry,
+ &request_id,
+ Ok(results.clone()),
+ )
+ .await;
+ let _ = self.events.send(StreamEvent::AskResolved {
+ request_id: request_id.clone(),
+ });
+ return format!(
+ "NOTE [ask_timeout]: no answer within the configured ask timeout; auto-selected the recommended option(s).\n{}",
+ request.render_results(&results)
+ );
+ }
+ },
+ None => receiver.await,
+ };
+ match outcome {
Ok(Ok(results)) => match request.validate_results(&results) {
Ok(()) => request.render_results(&results),
Err(error) => format!("ERROR: invalid ask response: {error}"),
@@ -3969,6 +4010,53 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ // An unanswered ask with `ask_timeout_secs` set resolves to the
+ // auto-selected recommended option (here the first, since `ask_call` sets
+ // no recommended index), NOT to `ask_cancelled`. `with_temp_home` points
+ // HOME at the config it writes; a nested current-thread runtime runs the
+ // invoke because that helper is synchronous.
+ // `global_config` (the timeout source) is CLI-only, so this test is too.
+ #[cfg(feature = "cli")]
+ #[test]
+ fn ask_auto_selects_on_timeout_instead_of_cancelling() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let path = crate::core::agent::global_config::ensure_global_config().unwrap();
+ std::fs::write(&path, "ask_timeout_secs = 1\n").unwrap();
+
+ let rt = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let root = unique_project_root();
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let permissions: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let asks = crate::core::agent::interaction::new_registry();
+ let mut invoker = build_prompting_invoker(root.clone(), tx, permissions);
+ invoker.ask_requests = Some(asks.clone());
+
+ // No one answers: handle_ask_tool self-resolves after the timeout.
+ let out = invoker.invoke(&[ask_call()]).await.unwrap();
+ assert_eq!(out.len(), 1);
+ assert!(
+ !out[0].content.contains("ask_cancelled"),
+ "timeout is not a cancel: {}",
+ out[0].content
+ );
+ assert!(
+ out[0].content.contains("User response for \"scope\": Small"),
+ "auto-selected the first option: {}",
+ out[0].content
+ );
+ assert!(
+ asks.lock().await.is_empty(),
+ "the timed-out ask must be deregistered"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ });
+ });
+ }
+
fn todo_call(id: &str, args: serde_json::Value) -> serde_json::Value {
json!({
"id": id,
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index bb50297d2..41890cdcd 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -1350,6 +1350,8 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {
StreamEvent::AskRequest { .. } => {
eprintln!("\n\x1b[31m[error] interactive ask requires `jan agent ui`\x1b[0m")
}
+ // Headless never renders an ask prompt, so there is nothing to dismiss.
+ StreamEvent::AskResolved { .. } => {}
// The non-interactive CLI doesn't persist session state; a todo update
// is silently dropped here (mirrors MessagesUpdated below).
StreamEvent::TodoUpdate { .. } => {}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index b4e2fd0e8..5db011350 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -3998,6 +3998,12 @@ impl App {
} => self
.ask_queue
.push_back(PendingAsk::new(request_id, request)),
+ // The loop auto-answered a timed-out ask; drop its now-dead prompt.
+ // A user answer clears the queue in `resolve_front_ask` instead, so
+ // this only fires for the timeout path.
+ StreamEvent::AskResolved { request_id } => {
+ self.ask_queue.retain(|ask| ask.request_id != request_id);
+ }
StreamEvent::SubagentStart { run_id, name, task } => {
// A queued dispatch already opened a panel for this run; promote
// it to running instead of pushing a duplicate. Otherwise open a
@@ -8908,6 +8914,13 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[
},
scope: SettingScope::Global,
},
+ AgentSettingDef {
+ key: "ask_timeout_secs",
+ label: "ask_timeout_secs",
+ desc: "auto-answer an unanswered ask after N seconds with the recommended option (0 = wait forever)",
+ kind: AgentSettingKind::Int { default: Some(0), min: 0 },
+ scope: SettingScope::Global,
+ },
];
/// Docked edit prompt for one `/settings` row: value field, inline validation
@@ -15067,6 +15080,26 @@ mod tests {
assert!(app.ask_queue.is_empty());
}
+ #[test]
+ fn ask_resolved_dismisses_only_the_matching_prompt() {
+ let mut app = test_app();
+ app.apply(StreamEvent::AskRequest {
+ request_id: "keep".into(),
+ request: ask_request(false, false),
+ });
+ app.apply(StreamEvent::AskRequest {
+ request_id: "gone".into(),
+ request: ask_request(false, false),
+ });
+ assert_eq!(app.ask_queue.len(), 2);
+
+ app.apply(StreamEvent::AskResolved {
+ request_id: "gone".into(),
+ });
+ assert_eq!(app.ask_queue.len(), 1, "only the timed-out prompt is dropped");
+ assert_eq!(app.ask_queue.front().unwrap().request_id, "keep");
+ }
+
#[tokio::test]
async fn ask_keyboard_accepts_repeated_key_events() {
let mut app = test_app();