Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tui): ring the terminal bell when the session needs attention (#9572)
Akarshan Biswasea83436b44af
diff --git a/docs/src/pages/docs/agent/console.mdx b/docs/src/pages/docs/agent/console.mdxindex 031836853..c7ab048fb 100644--- a/docs/src/pages/docs/agent/console.mdx+++ b/docs/src/pages/docs/agent/console.mdx@@ -246,6 +246,30 @@ ask instead:You see a diff for a file change, or the exact command for a shell call. Full detail in[Tool permissions](/docs/agent/permissions).+## Getting your attention++When a permission prompt or a question is waiting on you, the console rings the terminal bell and+sets the window title to `Jan - action required`. While a turn runs the title shows a spinner, and+it reads `Jan ready` once the session is idle. The bell rings once each time the console starts+waiting on you, even when the terminal is in a background tab. Another prompt that queues behind one+already on screen does not ring again; a question asked after the previous one is answered does.++Set `bell` in `~/.jan/config.toml`, or edit the same row in `/settings`:++```toml+bell = "always"+```++| Value | Rings when |+| --- | --- |+| `attention` | A permission prompt or a question needs you. The default |+| `always` | Also when a turn finishes, unless you cancelled it with <kbd>Esc</kbd> or <kbd>Ctrl</kbd>+<kbd>C</kbd> |+| `off` | Never |++An unknown value reads as `attention`. A change applies at once, with no restart. How the+bell sounds (audible, a visual flash, a dock bounce or a tab marker) is up to your terminal. Inside+tmux, a bell from any window reaches the terminal while `bell-action` is `any`, the default.+## Getting help`/help` inside the console prints every command and keybinding. `/` alone filters the command listdiff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdxindex 7670f2acb..dcd64b972 100644--- a/docs/src/pages/docs/agent/slash-commands.mdx+++ b/docs/src/pages/docs/agent/slash-commands.mdx@@ -78,7 +78,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-| `/login` | Sign in to Tokamak and save the API key || `/config [what you want]` | View provider config (`~/.jan/config.toml`). With words, it is `/vibe-setting` || `/terminal-setup` | Configure this terminal so <kbd>Shift</kbd>+<kbd>Enter</kbd> inserts a newline and, on macOS, <kbd>Option</kbd>+<kbd>Delete</kbd> deletes a word. Writes the terminal's own config where it can (VS Code, kitty, Ghostty, tmux) and prints the manual step where it cannot. Idempotent |-| `/settings [what you want]` | With words (other than the `max_parallel_subagents N` shortcut), it is `/vibe-setting`. Bare, it opens the menu to edit settings in an interactive menu - the project's `agent.toml` (`[agent]` knobs `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `[budget]` limits, the `[tools]` / `[skills]` toggles) and user-wide `~/.jan/config.toml` keys such as `ask_timeout_secs` in the one list (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets). The leading `providers` row opens a manager for OpenAI-compatible providers in `~/.jan/config.toml`: `a` adds, Enter edits, `d` twice deletes. The `subagents` row lists each subagent with its model; Enter picks one from the model picker (the `smol` and `inherit` roles included) and `x` clears the override. The `smol_model` row opens the model picker too (see [Subagents](/docs/agent/subagents#choosing-a-subagents-model)). `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next session (or after `/reload config` for the `[agent]`/`[budget]` limits) |+| `/settings [what you want]` | With words (other than the `max_parallel_subagents N` shortcut), it is `/vibe-setting`. Bare, it opens the menu to edit settings in an interactive menu - the project's `agent.toml` (`[agent]` knobs `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `[budget]` limits, the `[tools]` / `[skills]` toggles) and user-wide `~/.jan/config.toml` keys such as `ask_timeout_secs` and `bell` in the one list (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets). The leading `providers` row opens a manager for OpenAI-compatible providers in `~/.jan/config.toml`: `a` adds, Enter edits, `d` twice deletes. The `subagents` row lists each subagent with its model; Enter picks one from the model picker (the `smol` and `inherit` roles included) and `x` clears the override. The `smol_model` row opens the model picker too (see [Subagents](/docs/agent/subagents#choosing-a-subagents-model)). `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next session (or after `/reload config` for the `[agent]`/`[budget]` limits; `bell` applies at once) || `/vibe-setting <what you want>` | Say what you want in plain words and the agent proposes the settings changes that get it. `/settings <words>` and `/config <words>` do the same. See [below](#vibe-setting) |### `/vibe-setting`diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex bcdee7dd4..11202468f 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -46,6 +46,10 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# # question's recommended option (else its# # first). 0 or unset waits forever, the# # default+# bell = "off" # TUI terminal bell: "attention" (the+# # default) rings when a permission prompt+# # or ask question needs you, "always"+# # also when a turn finishes, "off" never# terminal_hint = false # stop the startup note that offers# # /terminal-setup when this terminal is# # dropping Shift+Enter or Option+Delete.@@ -157,6 +161,11 @@ struct GlobalConfigToml {/// 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>,+ /// TUI terminal bell: `"off"`, `"attention"` or `"always"`. `None` = the+ /// default, attention. Any other string also reads as the default so a+ /// typo never silences a prompt the user asked to hear.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ bell: Option<String>,/// 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@@ -758,6 +767,13 @@ pub(crate) fn theme_setting() -> Option<String> {load_raw().ok().and_then(|config| config.theme)}+/// The TUI bell preference (`bell` in `~/.jan/config.toml`), `None` when unset.+/// Read on every status transition so a `/settings` change applies at once; an+/// unreadable config yields `None` (the default) rather than an error.+pub(crate) fn bell_setting() -> Option<String> {+ load_raw().ok().and_then(|config| config.bell)+}+/// 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@@ -787,6 +803,7 @@ const ROOT_KEYS: &[&str] = &["stream_reasoning","theme","ask_timeout_secs",+ "bell","terminal_hint","memory_cross_project","memory_auto_tidy",@@ -1160,6 +1177,19 @@ mod tests {});}+ #[test]+ fn bell_is_unset_by_default_and_reads_its_key() {+ with_temp_home(|home| {+ assert_eq!(bell_setting(), None, "missing file");+ let path = home.join(".jan").join("config.toml");+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(&path, "bell = \"always\"\n").unwrap();+ assert_eq!(bell_setting().as_deref(), Some("always"));+ std::fs::write(&path, "bell = [").unwrap();+ assert_eq!(bell_setting(), None, "fails open to the default");+ });+ }+#[test]fn hide_secrets_is_unset_by_default_and_reads_its_key() {with_temp_home(|home| {diff --git a/src-tauri/src/core/cli/agent_status.rs b/src-tauri/src/core/cli/agent_status.rsindex 7ad747b22..0e4fe0a7b 100644--- a/src-tauri/src/core/cli/agent_status.rs+++ b/src-tauri/src/core/cli/agent_status.rs@@ -10,6 +10,9 @@//! 2. **Terminal titles (OSC 2)** - a spinner glyph + `Jan` while working,//! `Jan - action required` while blocked/waiting, and `Jan ready` when idle.//!+//! 3. **Terminal bell (BEL)** - rung when the session starts needing the+//! user, per the `bell` preference ([`BellMode`]).+//!//! Orca 1.4.191 accepts Jan's OSC 9999 status, but its `tui-idle` wait does not//! consume that protocol or recognize Jan's settled titles. Jan icons and//! title-based idle recognition require Orca-side support.@@ -48,6 +51,53 @@ impl AgentStatusState {}}+/// The `bell` preference in `~/.jan/config.toml`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum BellMode {+ /// Never ring.+ Off,+ /// Ring when a permission prompt or an `ask` question needs the user.+ #[default]+ Attention,+ /// Also ring when a turn finishes.+ Always,+}++impl BellMode {+ /// Accepted values, in `/settings` order.+ pub const OPTIONS: &'static [&'static str] = &["off", "attention", "always"];++ /// Parse the config value. Unset or unknown reads as the default, so a typo+ /// never silences a prompt the user meant to hear.+ pub fn parse(value: Option<&str>) -> Self {+ match value.map(str::trim) {+ Some("off") => BellMode::Off,+ Some("always") => BellMode::Always,+ _ => BellMode::Attention,+ }+ }++ /// The mode currently configured, read fresh so `/settings` applies at once.+ fn configured() -> Self {+ Self::parse(crate::core::agent::global_config::bell_setting().as_deref())+ }++ /// Whether an emitted transition from `prev` to `next` rings. A new `ask`+ /// question while one is already showing is a new transition (its prompt+ /// changed) and rings again. `done` rings only straight out of `working`:+ /// the startup `done` and the `done` after the user answers a prompt both+ /// mean the user is already looking.+ fn rings(self, prev: Option<AgentStatusState>, next: AgentStatusState) -> bool {+ use AgentStatusState as S;+ match (self, next) {+ (BellMode::Off, _) => false,+ (_, S::Blocked | S::Waiting) => true,+ (BellMode::Always, S::Done) => prev == Some(S::Working),+ _ => false,+ }+ }+}+/// Braille frames used to animate the working title.const SPINNER_FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];@@ -139,27 +189,52 @@ impl AgentStatusReporter {////// Returns `None` when the state is unchanged and the prompt preview is/// identical (transitions are deduped), otherwise the `(status, title)`- /// sequences to write.+ /// sequences to write, with a trailing BEL on the title when the mode+ /// `bell` returns rings. `bell` runs only for an emitted transition, so a+ /// deduped call never reads the config.fn transition(&mut self,state: AgentStatusState,prompt: Option<&str>,+ bell: impl FnOnce() -> BellMode,) -> Option<(String, String)> {if self.last_state == Some(state) && self.last_prompt.as_deref() == prompt {return None;}+ let ring = bell().rings(self.last_state, state);self.last_state = Some(state);self.last_prompt = prompt.map(str::to_string);self.spinner_frame = 0;- Some((- agent_status_sequence(state, prompt),- title_sequence(state, self.spinner_frame),- ))+ let mut title = title_sequence(state, self.spinner_frame);+ if ring {+ title.push('\x07');+ }+ Some((agent_status_sequence(state, prompt), title))}- /// Report a state transition, writing OSC 9999 and the title to stdout.+ /// Report a state transition, writing OSC 9999, the title and any bell to+ /// stdout.pub fn set_state(&mut self, state: AgentStatusState, prompt: Option<&str>) {- let Some((status, title)) = self.transition(state, prompt) else {+ self.emit(state, prompt, true);+ }++ /// [`Self::set_state`] without the bell, for a transition the user just+ /// caused (Esc or Ctrl-C cancelling a turn): they are already looking.+ pub fn set_state_quietly(&mut self, state: AgentStatusState, prompt: Option<&str>) {+ self.emit(state, prompt, false);+ }++ fn emit(&mut self, state: AgentStatusState, prompt: Option<&str>, may_ring: bool) {+ // Disabled reporters never write, so skip the config read for them.+ let enabled = self.enabled;+ let bell = || {+ if enabled && may_ring {+ BellMode::configured()+ } else {+ BellMode::Off+ }+ };+ let Some((status, title)) = self.transition(state, prompt, bell) else {return;};if self.enabled {@@ -319,12 +394,13 @@ mod tests {#[test]fn transitions_dedupe_and_reset_spinner() {+ let off = || BellMode::Off;let mut reporter = AgentStatusReporter::new();- assert!(reporter.transition(AgentStatusState::Done, None).is_some());+ assert!(reporter.transition(AgentStatusState::Done, None, off).is_some());// Same state again: nothing to emit.- assert!(reporter.transition(AgentStatusState::Done, None).is_none());+ assert!(reporter.transition(AgentStatusState::Done, None, off).is_none());assert!(reporter- .transition(AgentStatusState::Working, None)+ .transition(AgentStatusState::Working, None, off).is_some());// Spinner frame survives across animate() calls and resets on// transitions.@@ -333,7 +409,66 @@ mod tests {title_sequence(AgentStatusState::Working, reporter.spinner_frame),"\x1b]2;⠙ Jan\x07");- assert!(reporter.transition(AgentStatusState::Done, None).is_some());+ assert!(reporter.transition(AgentStatusState::Done, None, off).is_some());assert_eq!(reporter.spinner_frame, 0);}++ #[test]+ fn bell_mode_parses_and_defaults_to_attention() {+ assert_eq!(BellMode::parse(None), BellMode::Attention);+ assert_eq!(BellMode::parse(Some("off")), BellMode::Off);+ assert_eq!(BellMode::parse(Some("always")), BellMode::Always);+ assert_eq!(BellMode::parse(Some("attention")), BellMode::Attention);+ assert_eq!(BellMode::parse(Some("loud")), BellMode::Attention, "typo");+ }++ /// Drive one reporter through `states` under `bell`, returning which+ /// emitted transitions ended in a BEL after the title.+ fn rings(bell: BellMode, states: &[(AgentStatusState, Option<&str>)]) -> Vec<bool> {+ let mut reporter = AgentStatusReporter::new();+ states+ .iter()+ .filter_map(|(state, prompt)| reporter.transition(*state, *prompt, || bell))+ .map(|(_, title)| title.ends_with("\x07\x07"))+ .collect()+ }++ #[test]+ fn bell_rings_only_on_the_transitions_its_mode_names() {+ use AgentStatusState as S;+ let session = [+ (S::Done, None), // startup+ (S::Working, None), // turn starts+ (S::Blocked, None), // permission prompt+ (S::Working, None), // approved+ (S::Waiting, Some("a?")), // ask+ (S::Waiting, Some("b?")), // a second question+ (S::Working, None), // answered+ (S::Done, None), // turn ends+ ];+ let attention = [false, false, true, false, true, true, false, false];+ let always = [false, false, true, false, true, true, false, true];+ assert_eq!(rings(BellMode::Attention, &session), attention);+ assert_eq!(rings(BellMode::Always, &session), always);+ assert_eq!(rings(BellMode::Off, &session), [false; 8]);+ // An answered prompt that ends the turn leaves the user already+ // looking: `done` out of `blocked` stays quiet even under always.+ assert_eq!(+ rings(BellMode::Always, &[(S::Blocked, None), (S::Done, None)]),+ [true, false]+ );+ }++ #[test]+ fn a_deduped_transition_never_reads_the_bell_mode() {+ let mut reporter = AgentStatusReporter::new();+ let mut reads = 0;+ for _ in 0..3 {+ reporter.transition(AgentStatusState::Working, None, || {+ reads += 1;+ BellMode::Always+ });+ }+ assert_eq!(reads, 1, "only the emitted transition asks for the mode");+ }}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 176a38132..814cb0a22 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -9575,6 +9575,16 @@ impl App {/// pending permission summary (what Jan is blocked on) or the active/// subagent task, matching Orca's card fields.fn publish_agent_status(&mut self) {+ self.publish_agent_status_with(true);+ }++ /// [`Self::publish_agent_status`] for a transition the user just caused:+ /// the state is reported but the bell stays quiet, as they are looking.+ fn publish_agent_status_quietly(&mut self) {+ self.publish_agent_status_with(false);+ }++ fn publish_agent_status_with(&mut self, may_ring: bool) {use super::agent_status::AgentStatusState as S;let state = match self.status {// A live prompt outranks the turn status: a session-owned child@@ -9594,7 +9604,11 @@ impl App {.map(|q| q.question.clone()),_ => None,};- self.agent_status.set_state(state, prompt.as_deref());+ if may_ring {+ self.agent_status.set_state(state, prompt.as_deref());+ } else {+ self.agent_status.set_state_quietly(state, prompt.as_deref());+ }}/// Arm the per-turn state shared by a user submit and a reminder@@ -10054,7 +10068,9 @@ impl App {// cancel must not quietly become "keep working in the background".self.stop_subagents();self.close_live_background();- self.publish_agent_status();+ // The user pressed Esc or Ctrl-C: `bell = "always"` must not ring for+ // a turn end they caused while looking at it.+ self.publish_agent_status_quietly();self.detail = "cancelled".to_string();self.scrollback = 0;self.system(Level::Warn, "cancelled");@@ -18823,6 +18839,16 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[kind: AgentSettingKind::Int { default: Some(0), min: 0 },scope: SettingScope::Global,},+ AgentSettingDef {+ key: "bell",+ label: "bell",+ desc: "terminal bell: attention rings for permission prompts and asks, always also when a turn ends",+ kind: AgentSettingKind::Enum {+ options: super::agent_status::BellMode::OPTIONS,+ default: "attention",+ },+ scope: SettingScope::Global,+ },AgentSettingDef {key: SMOL_MODEL_KEY,label: "smol_model",@@ -20060,7 +20086,12 @@ fn handle_settings_key(app: &mut App, key: KeyEvent, ctrl: bool) {} else {format!("{} = {entered} written", prompt.key)};- app.note(&format!("{what}; takes effect on the next run"));+ let when = if vibe_setting::LIVE_KEYS.contains(&prompt.key) {+ "applies now"+ } else {+ "takes effect on the next run"+ };+ app.note(&format!("{what}; {when}"));app.settings_prompt = None;}Err(e) => {@@ -35902,6 +35933,32 @@ fn a() {}});}+ /// `bell` is read on every status transition, so its note must not tell+ /// the user to wait for a next run the way other rows do.+ #[test]+ fn settings_prompt_says_bell_applies_now() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let mut app = test_app();+ std::fs::create_dir_all(&app.agent_dir).unwrap();+ let def = AGENT_SETTINGS.iter().find(|d| d.key == "bell").unwrap();+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));+ for ch in "always".chars() {+ super::handle_settings_key(&mut app, key(KeyCode::Char(ch)), false);+ }+ super::handle_settings_key(&mut app, key(KeyCode::Enter), false);++ assert_eq!(+ crate::core::agent::global_config::bell_setting().as_deref(),+ Some("always")+ );+ let note = transcript_text(&app);+ assert!(note.contains("bell = always written; applies now"), "{note}");+ assert!(!note.contains("next run"), "{note}");++ let _ = std::fs::remove_dir_all(&app.agent_dir);+ });+ }+/// The picker hint for a global row must read the global file, or every/// user-wide key would show `(unset)` however it is configured./// Sync, with a local runtime for the one keypress: `with_temp_home` swapsdiff --git a/src-tauri/src/core/cli/tui/vibe_setting.rs b/src-tauri/src/core/cli/tui/vibe_setting.rsindex a2c233dca..667be6614 100644--- a/src-tauri/src/core/cli/tui/vibe_setting.rs+++ b/src-tauri/src/core/cli/tui/vibe_setting.rs@@ -40,6 +40,11 @@ pub(super) const RELOAD_CONFIG_KEYS: &[&str] = &["send_reasoning",];+/// `/settings` keys the running session re-reads on every use, so a written one+/// applies at once: no `/reload config`, no restart. `bell` is read on each+/// agent-status transition (`agent_status::BellMode::configured`).+pub(super) const LIVE_KEYS: &[&str] = &["bell"];+/// The keys a proposal may name, in `/settings` order.pub(super) fn catalog() -> impl Iterator<Item = &'static AgentSettingDef> {AGENT_SETTINGS@@ -449,6 +454,7 @@ fn apply(app: &mut App) {};let toml_path = app.agent_dir.join("agent.toml");let mut written: Vec<String> = Vec::new();+ let mut live: Vec<String> = Vec::new();let mut reloadable: Vec<String> = Vec::new();let mut restart: Vec<String> = Vec::new();let mut failed: Vec<String> = Vec::new();@@ -456,7 +462,9 @@ fn apply(app: &mut App) {match write_setting(change.def, &toml_path, change.item.clone()) {Ok(()) => {let key = change.def.key.to_string();- if RELOAD_CONFIG_KEYS.contains(&change.def.key) {+ if LIVE_KEYS.contains(&change.def.key) {+ live.push(key);+ } else if RELOAD_CONFIG_KEYS.contains(&change.def.key) {reloadable.push(key);} else {restart.push(key);@@ -473,7 +481,7 @@ fn apply(app: &mut App) {)),}}- let when = apply_when(&reloadable, &restart);+ let when = apply_when(&live, &reloadable, &restart);if !written.is_empty() {app.note(&format!("◈ vibe-setting · wrote {} setting(s); {when}",@@ -489,8 +497,12 @@ fn apply(app: &mut App) {}/// The "when does it apply" half of the result note, one clause per bucket.-fn apply_when(reloadable: &[String], restart: &[String]) -> String {+fn apply_when(live: &[String], reloadable: &[String], restart: &[String]) -> String {let mut parts: Vec<String> = Vec::new();+ if !live.is_empty() {+ let verb = if live.len() == 1 { "applies" } else { "apply" };+ parts.push(format!("{} {verb} now", live.join(", ")));+ }if !reloadable.is_empty() {parts.push(format!("run /reload config to apply {}", reloadable.join(", ")));}@@ -603,17 +615,21 @@ mod tests {fn apply_when_names_each_bucket() {let v = |xs: &[&str]| xs.iter().map(|x| x.to_string()).collect::<Vec<_>>();assert_eq!(- apply_when(&v(&["context_window", "max_tokens"]), &[]),+ apply_when(&[], &v(&["context_window", "max_tokens"]), &[]),"run /reload config to apply context_window, max_tokens");assert_eq!(- apply_when(&[], &v(&["show_reasoning", "tools.default"])),+ apply_when(&[], &[], &v(&["show_reasoning", "tools.default"])),"show_reasoning, tools.default apply when jan restarts");assert_eq!(- apply_when(&v(&["max_tokens"]), &v(&["show_reasoning"])),+ apply_when(&[], &v(&["max_tokens"]), &v(&["show_reasoning"])),"run /reload config to apply max_tokens; show_reasoning applies when jan restarts");+ assert_eq!(+ apply_when(&v(&["bell"]), &[], &v(&["show_reasoning"])),+ "bell applies now; show_reasoning applies when jan restarts"+ );}fn unset(_: &AgentSettingDef) -> Option<String> {