Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): emit agent status (OSC 9999 + titles) for Orca integration
thinhlpg24cc3d6d3586
diff --git a/src-tauri/src/core/cli/agent_status.rs b/src-tauri/src/core/cli/agent_status.rsnew file mode 100644index 000000000..4dc6fe81c--- /dev/null+++ b/src-tauri/src/core/cli/agent_status.rs@@ -0,0 +1,284 @@+//! Agent-status emission for terminal integrations (Orca, #8819).+//!+//! Two evidence layers are produced, both written straight to the PTY (raw+//! stdout) rather than through the ratatui frame buffer, so status reaches+//! the host terminal even when no terminal view is rendered:+//!+//! 1. **OSC 9999 agent-status protocol** — `\x1b]9999;{json}\x07` with a JSON+//! payload carrying `agentType` and `state` (`working` | `blocked` |+//! [`waiting`] | `done`). This is the primary signal Orca's stateful+//! PTY parser consumes.+//! 2. **Terminal titles (OSC 2)** — a fallback matching Orca's+//! title-classification conventions: a spinner glyph + `Jan` while+//! working, `Jan - action required` while blocked/waiting, and+//! `Jan ready` when idle.++use std::io::{self, Write};++/// `agentType` value reported to status consumers.+const AGENT_TYPE: &str = "jan";+/// OSC 9999 introducer; the payload is terminated by BEL (or ST, not used here).+const OSC_9999_PREFIX: &str = "\x1b]9999;";+/// OSC 2 sets the window title.+const OSC_TITLE_PREFIX: &str = "\x1b]2;";++/// Agent states understood by the OSC 9999 protocol.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AgentStatusState {+ /// A turn is in progress.+ Working,+ /// A permission prompt needs a decision.+ Blocked,+ /// The agent asked a question and awaits the user's answer.+ Waiting,+ /// No turn is running; the session is idle.+ Done,+}++impl AgentStatusState {+ /// Wire representation of the state.+ pub fn as_str(self) -> &'static str {+ match self {+ AgentStatusState::Working => "working",+ AgentStatusState::Blocked => "blocked",+ AgentStatusState::Waiting => "waiting",+ AgentStatusState::Done => "done",+ }+ }+}++/// Braille frames used to animate the working title.+const SPINNER_FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];++/// Title shown while a turn is running (spinner frame + agent name).+fn working_title(frame: usize) -> String {+ format!("{} Jan", SPINNER_FRAMES[frame % SPINNER_FRAMES.len()])+}++/// Title shown for terminal states, per Orca's synthetic-title conventions.+fn settled_title(state: AgentStatusState) -> &'static str {+ match state {+ AgentStatusState::Blocked | AgentStatusState::Waiting => "Jan - action required",+ AgentStatusState::Working | AgentStatusState::Done => "Jan ready",+ }+}++/// Build the OSC 9999 escape sequence for a state transition.+///+/// The payload is a single-line JSON object; BEL terminates the sequence.+/// `prompt` is the optional activity preview Orca renders on its cards; it is+/// truncated to 160 chars, matching Orca's `toolInput` bound.+pub fn agent_status_sequence(state: AgentStatusState, prompt: Option<&str>) -> String {+ let prompt = prompt+ .map(|p| {+ let mut p: String = p.chars().take(160).collect();+ p = p.replace(['\\', '"'], " ");+ p = p.replace('\n', " ");+ p+ })+ .unwrap_or_default();+ if prompt.is_empty() {+ format!(+ "{OSC_9999_PREFIX}{{\"agentType\":\"{AGENT_TYPE}\",\"state\":\"{}\"}}\x07",+ state.as_str()+ )+ } else {+ format!(+ "{OSC_9999_PREFIX}{{\"agentType\":\"{AGENT_TYPE}\",\"state\":\"{}\",\"prompt\":\"{prompt}\"}}\x07",+ state.as_str()+ )+ }+}++/// Build the OSC 2 window-title sequence for a state.+///+/// `spinner_frame` selects the animated indicator used while working; it is+/// ignored for terminal states.+pub fn title_sequence(state: AgentStatusState, spinner_frame: usize) -> String {+ let title = match state {+ AgentStatusState::Working => working_title(spinner_frame),+ _ => settled_title(state).to_string(),+ };+ format!("{OSC_TITLE_PREFIX}{title}\x07")+}++/// Tracks the last reported state and writes transitions to the PTY.+///+/// Every state change is emitted exactly once (deduped), as an OSC 9999+/// payload plus an OSC 2 title. Writes happen directly on stdout, outside the+/// ratatui frame, so hidden/background sessions are tracked too. Until+/// [`AgentStatusReporter::enable`] is called the reporter is inert: no bytes+/// reach stdout, which keeps test-driven state machines quiet.+#[derive(Debug, Default)]+pub struct AgentStatusReporter {+ enabled: bool,+ last_state: Option<AgentStatusState>,+ last_prompt: Option<String>,+ spinner_frame: usize,+}++impl AgentStatusReporter {+ /// Create a disabled reporter (emits nothing until enabled).+ pub fn new() -> Self {+ Self::default()+ }++ /// Start emitting to stdout. Called by the real TUI once the terminal is+ /// set up; unit tests construct `App` through paths that leave it off.+ pub fn enable(&mut self) {+ self.enabled = true;+ }++ /// Compute the sequences for a state transition.+ ///+ /// Returns `None` when the state is unchanged and the prompt preview is+ /// identical (transitions are deduped), otherwise the `(status, title)`+ /// sequences to write.+ fn transition(+ &mut self,+ state: AgentStatusState,+ prompt: Option<&str>,+ ) -> Option<(String, String)> {+ if self.last_state == Some(state) && self.last_prompt.as_deref() == prompt {+ return None;+ }+ 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),+ ))+ }++ /// Report a state transition, writing OSC 9999 and the title to stdout.+ pub fn set_state(&mut self, state: AgentStatusState, prompt: Option<&str>) {+ let Some((status, title)) = self.transition(state, prompt) else {+ return;+ };+ if self.enabled {+ write_raw(&status);+ write_raw(&title);+ }+ }++ /// Advance the animated working title by one frame.+ ///+ /// No-op unless currently `working`. Call from the render tick; the deduped+ /// OSC 9999 payload is not re-sent. The frame advances even when disabled+ /// (so test state machines track it); only the stdout write is gated.+ pub fn animate(&mut self) {+ if self.last_state != Some(AgentStatusState::Working) {+ return;+ }+ self.spinner_frame = (self.spinner_frame + 1) % SPINNER_FRAMES.len();+ if self.enabled {+ write_raw(&title_sequence(+ AgentStatusState::Working,+ self.spinner_frame,+ ));+ }+ }+}++/// Write a raw escape sequence to stdout and flush, ignoring errors the way+/// the clipboard OSC 52 write does: a failed PTY write must never take down+/// the TUI.+fn write_raw(sequence: &str) {+ let mut out = io::stdout();+ let _ = out.write_all(sequence.as_bytes());+ let _ = out.flush();+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn payload_carries_agent_type_and_state() {+ assert_eq!(+ agent_status_sequence(AgentStatusState::Working, None),+ "\x1b]9999;{\"agentType\":\"jan\",\"state\":\"working\"}\x07"+ );+ assert_eq!(+ agent_status_sequence(AgentStatusState::Done, None),+ "\x1b]9999;{\"agentType\":\"jan\",\"state\":\"done\"}\x07"+ );+ assert_eq!(+ agent_status_sequence(AgentStatusState::Blocked, None),+ "\x1b]9999;{\"agentType\":\"jan\",\"state\":\"blocked\"}\x07"+ );+ assert_eq!(+ agent_status_sequence(AgentStatusState::Waiting, None),+ "\x1b]9999;{\"agentType\":\"jan\",\"state\":\"waiting\"}\x07"+ );+ }++ #[test]+ fn prompt_preview_is_sanitized_and_truncated() {+ let long = "x".repeat(500);+ let seq = agent_status_sequence(AgentStatusState::Working, Some(&long));+ assert!(seq.matches('x').count() <= 160);+ let seq = agent_status_sequence(+ AgentStatusState::Working,+ Some("line\nbreak \"quoted\" \\path"),+ );+ assert_eq!(+ seq,+ "\x1b]9999;{\"agentType\":\"jan\",\"state\":\"working\",\"prompt\":\"line break quoted path\"}\x07"+ );+ }++ #[test]+ fn title_matches_orca_classification() {+ // Working: animated indicator + "Jan".+ assert!(title_sequence(AgentStatusState::Working, 0).contains(" Jan\x07"));+ assert_eq!(+ title_sequence(AgentStatusState::Working, 0),+ "\x1b]2;⠋ Jan\x07"+ );+ // Blocked/waiting: Orca's permission label.+ assert_eq!(+ title_sequence(AgentStatusState::Blocked, 3),+ "\x1b]2;Jan - action required\x07"+ );+ assert_eq!(+ title_sequence(AgentStatusState::Waiting, 3),+ "\x1b]2;Jan - action required\x07"+ );+ // Idle: Orca's strong idle keyword.+ assert_eq!(+ title_sequence(AgentStatusState::Done, 3),+ "\x1b]2;Jan ready\x07"+ );+ }++ #[test]+ fn transitions_dedupe_and_reset_spinner() {+ let mut reporter = AgentStatusReporter::new();+ assert!(reporter.transition(AgentStatusState::Done, None).is_some());+ // Same state again: nothing to emit.+ assert!(reporter.transition(AgentStatusState::Done, None).is_none());+ assert!(reporter+ .transition(AgentStatusState::Working, None)+ .is_some());+ // Spinner frame survives across animate() calls and resets on+ // transitions.+ reporter.animate();+ assert_eq!(+ title_sequence(AgentStatusState::Working, reporter.spinner_frame),+ "\x1b]2;⠙ Jan\x07"+ );+ assert!(reporter.transition(AgentStatusState::Done, None).is_some());+ assert_eq!(reporter.spinner_frame, 0);+ }++ #[test]+ fn disabled_reporter_never_writes() {+ let mut reporter = AgentStatusReporter::new();+ // Must not panic or touch stdout: everything short-circuits.+ reporter.set_state(AgentStatusState::Working, None);+ reporter.animate();+ reporter.set_state(AgentStatusState::Done, None);+ }+}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 96304f9ec..9eb7178a7 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -2,6 +2,7 @@//!//! This module is only compiled when the `cli` feature is enabled.+mod agent_status;pub mod auth;pub mod brand;pub mod browser;diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 370489c65..fd798e8e2 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -41,6 +41,7 @@ use markdown::{format_markdown_lines, live_assistant_lines, reasoning_detail_lines, reasoning_summary_row,};+use super::agent_status::AgentStatusReporter;use super::brand;use super::journal::{self, DisplayEntry, ReasoningSeg};use super::mcp::McpServerEntry;@@ -1833,6 +1834,9 @@ struct App {/// Set by Esc to dismiss the path-hint popup; cleared on next char edit.path_hint_dismissed: bool,status: Status,+ /// Orca-integration status emitter (OSC 9999 + terminal titles). Inert+ /// until `run` enables it, so test-driven state machines write nothing.+ agent_status: AgentStatusReporter,/// Wall-clock start of the current reasoning `<think>` block while it is/// open (the model is actively reasoning). `None` between blocks.thinking_since: Option<Instant>,@@ -2396,6 +2400,7 @@ impl App {path_hint_selected: 0,path_hint_dismissed: false,status: Status::Idle,+ agent_status: AgentStatusReporter::new(),thinking_since: None,thought_for: None,thought_for_since: None,@@ -4859,22 +4864,27 @@ impl App {selected: 0,subagent: None,});+ self.publish_agent_status();}StreamEvent::AskRequest {request_id,request,timeout_secs,..- } => self.ask_queue.push_back(PendingAsk::new(- request_id,- request,- timeout_secs.map(std::time::Duration::from_secs),- )),+ } => {+ self.ask_queue.push_back(PendingAsk::new(+ request_id,+ request,+ timeout_secs.map(std::time::Duration::from_secs),+ ));+ self.publish_agent_status();+ }// 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);+ self.publish_agent_status();}StreamEvent::SubagentStart { run_id, name, task } => {// A queued dispatch already opened a panel for this run; promote@@ -5043,6 +5053,7 @@ impl App {selected: 0,subagent: Some(name.to_string()),});+ self.publish_agent_status();}// Each child request bumps its counter, so the panel shows work// happening even during a long think with no tool calls.@@ -5066,6 +5077,30 @@ impl App {}}+ /// Recompute and publish the Orca-visible agent status from primary state+ /// (turn status plus pending prompts). The reporter dedupes, so calling+ /// this after every transition is cheap. The prompt preview carries the+ /// pending permission summary (what Jan is blocked on) or the active+ /// subagent task, matching Orca's card fields.+ fn publish_agent_status(&mut self) {+ use super::agent_status::AgentStatusState as S;+ let state = match self.status {+ Status::Idle => S::Done,+ Status::Running if !self.pending_queue.is_empty() => S::Blocked,+ Status::Running if !self.ask_queue.is_empty() => S::Waiting,+ Status::Running => S::Working,+ };+ let prompt = match state {+ S::Waiting => self+ .ask_queue+ .front()+ .and_then(|ask| ask.request.questions.first())+ .map(|q| q.question.clone()),+ _ => None,+ };+ self.agent_status.set_state(state, prompt.as_deref());+ }+/// Arm the per-turn state shared by a user submit and a reminder/// continuation. Both paths start a run, so both must reset every/// turn-scoped counter -- keeping two hand-maintained copies in sync is how@@ -5087,6 +5122,7 @@ impl App {// A call cancelled before its result would otherwise leave its path// behind for the life of the session.self.diff_paths.clear();+ self.publish_agent_status();}/// Current throbber frame. `spinner_frame` is advanced on a fixed cadence@@ -5178,6 +5214,7 @@ impl App {self.run_started = None;self.detail = format!("stop_reason={stop_reason}");self.scrollback = 0;+ self.publish_agent_status();// Surface abnormal completions in the timeline, not just the footer: a// truncated/filtered finish, or a "stop" that yielded no answer (an// empty/malformed upstream completion defaults to stop_reason=stop).@@ -5256,6 +5293,7 @@ impl App {} else {format!("{code}: {message}")};+ self.publish_agent_status();self.system(Level::Error, &format!("error: {message}"));// A context overflow is the one error the session can recover from by// itself: compact, then resume the turn that failed. The goal loop and@@ -5389,6 +5427,7 @@ impl App {// cancel is silently undone.self.want_start = false;self.close_live_background();+ self.publish_agent_status();self.detail = "cancelled".to_string();self.scrollback = 0;self.system(Level::Warn, "cancelled");@@ -7807,6 +7846,9 @@ pub async fn run(Err(e) => app.note(&format!("could not attach image: {e}")),}}+ // From here on the terminal is ours: status sequences reach the real PTY.+ app.agent_status.enable();+ app.publish_agent_status();let res = chat_loop(&mut terminal,&args,@@ -8300,6 +8342,9 @@ async fn chat_loop<B: Backend>(// Advance the throbber at its own fixed cadence, catching up// whole frames if a tick stalled (a burst of deltas / slow term).app.advance_spinner(Instant::now());+ // Animate the working-title spinner on the same cadence; the+ // OSC 9999 payload is not re-sent, only the title frame.+ app.agent_status.animate();while event::poll(Duration::ZERO).unwrap_or(false) {match event::read() {Ok(Event::Key(key)) => {@@ -8671,6 +8716,7 @@ async fn resolve_front_ask(let Some(ask) = app.ask_queue.pop_front() else {return;};+ app.publish_agent_status();// Reserved plan-review ask: a single question with the exact id drives the// mode transition. Capture the chosen label before `answers` is moved into// the outcome. Skipped on cancel so a cancelled review never changes mode.@@ -9304,6 +9350,9 @@ async fn handle_key(if let Some(sender) = registry.lock().await.remove(&pending.request_id) {let _ = sender.send(d);}+ // The run resumes now that a prompt was answered (unless more are+ // queued) — publish the recomputed status either way.+ app.publish_agent_status();}return;}