ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
feat: add stuck task detection to orchestrator agent (#43)
Fynn FlΓΌgge485cf911a125
diff --git a/README.md b/README.mdindex 99a76af..ccefa72 100644--- a/README.md+++ b/README.md@@ -423,6 +423,8 @@ agtx --experimental # then press O- Monitors tasks in Planning and Running- Advances tasks automatically as phases complete (Planning β Running β Review)- Respects plugin phase rules β checks `allowed_actions` before each transition+- Detects stuck tasks (idle for 1+ minute without a phase artifact) and reads the agent pane to diagnose the cause+- Nudges stuck agents, answers CLI prompts automatically, or escalates to you with a reason when human input is needed**You triage. It executes.** Move tasks from Backlog into Planning or Running β the orchestrator handles the rest. Merging is your call.@@ -451,13 +453,17 @@ The orchestrator communicates with agtx through the [Model Context Protocol (MCP| `get_transition_status` | Check if a queued transition completed or errored || `check_conflicts` | Non-destructive merge conflict detection against the default branch || `get_notifications` | Manually fetch pending notifications (backup β usually pushed automatically) |+| `read_pane_content` | Read the last N lines of a task's agent tmux pane |+| `send_to_task` | Send a message to a task's agent pane (Planning/Running only) |**How it works:**1. When you press `O`, the TUI registers the MCP server with the orchestrator agent via `claude mcp add-json --scope local`2. The orchestrator receives phase completion notifications pushed to its tmux pane when idle3. It reacts by calling `get_task` to check `allowed_actions`, then `move_task` to advance the task4. The TUI processes the transition request, executes all side effects (agent switching, skill deployment, prompt sending), and updates the database-5. MCP registration is cleaned up when the orchestrator is stopped+5. If a task has been idle for 1+ minute without a phase artifact, the orchestrator is notified β it reads the pane with `read_pane_content`, then either nudges the agent with `send_to_task` or calls `move_task` with `escalate_to_user` to flag it for your attention+6. Escalated tasks show a `β ` badge on the kanban board; opening the task popup shows the reason and dismisses the flag+7. MCP registration is cleaned up when the orchestrator is stopped## Contributingdiff --git a/plugins/agtx/skills/orchestrate.md b/plugins/agtx/skills/orchestrate.mdindex a2b0a7a..e3fa03e 100644--- a/plugins/agtx/skills/orchestrate.md+++ b/plugins/agtx/skills/orchestrate.md@@ -19,11 +19,14 @@ You have access to these agtx MCP tools:- **get_task** β Get full details of a specific task. Includes `allowed_actions`showing which transitions are valid given the task's status and plugin rules.- **move_task** β Queue a task state transition (the TUI executes it with full side effects)- - Actions: `move_forward`+ - Actions: `move_forward`, `escalate_to_user` (flag task for user attention with a reason)- **get_transition_status** β Check if a queued transition completed- **get_notifications** β Manually fetch pending notifications (usually not needed βnotifications are pushed to you automatically when you are idle).-+- **read_pane_content(task_id, lines?)** β Read the last N lines of a task's agent pane+ (default 50). Use this to see what an agent is showing when a task is stuck.+- **send_to_task(task_id, message)** β Send a message + Enter to a task's agent pane.+ Only works for Planning or Running tasks. Use to answer CLI prompts or nudge stuck agents.## How You Receive UpdatesNotifications are **pushed to you automatically** when you are idle (waiting for input).@@ -84,3 +87,31 @@ Backlog β Research β Planning β Running β Review- Do not move tasks beyond Review β merging is the user's responsibility.- When idle with no pending work, output `[agtx:idle]` and wait β notificationswill be pushed to you. Never skip the idle signal.++## Handling Stuck Tasks++When you receive a notification like:+```+Task "fix-auth" (abc12345) has been idle for 5m in phase: running+```++1. Call `read_pane_content(task_id)` to see what the agent is showing.+2. Analyze what you see:+ - **Agent asking a domain question** (ends with `?`, "Should I...", "Do you want to...",+ "Which approach...", anything requiring the user's judgment about the project):+ Call `move_task` with `action: "escalate_to_user"` and set `reason` to a brief+ summary of what the agent is asking. **Do NOT answer domain questions on the user's behalf.**+ - **CLI confirmation prompt** (`[y/N]`, `[Y/n]`, numbered menu like `1)`, `2)`, `3)`,+ "Press Enter to continue", "Continue? (yes/no)"):+ Call `send_to_task` with the appropriate response (e.g. `"y"`, `"1"`, `""`).+ Then call `read_pane_content` again after a few seconds to verify it was dismissed.+ - **Agent appears stuck on an error, in a loop, or confused**:+ Compose a short nudge prompt summarizing what you see and suggesting the agent+ tries a different approach. Call `send_to_task` with that nudge.+ If a second idle notification arrives for the same task after your nudge,+ escalate to the user with `escalate_to_user`.+3. After acting, output `[agtx:idle]` on its own line and wait for the next notification.++**Important:** `escalate_to_user` shows a visible warning banner to the user in the TUI+with your reason text. Keep the reason concise (one sentence). The user will see it when+they open the task popup.diff --git a/src/agent/operations.rs b/src/agent/operations.rsindex 6b8d399..f0b0324 100644--- a/src/agent/operations.rs+++ b/src/agent/operations.rs@@ -27,6 +27,14 @@ pub trait AgentOperations: Send + Sync {/// Build the shell command to start the agent interactively./// When prompt is empty, the agent starts with no initial message.fn build_interactive_command(&self, prompt: &str) -> String;++ /// Build the full shell command to run this agent as an orchestrator.+ /// Includes MCP registration (if supported by the agent) and cleanup on exit.+ /// Default implementation: no MCP, just launches the agent interactively.+ fn build_orchestrator_command(&self, mcp_json: &str, agtx_bin: &str) -> String {+ let _ = (mcp_json, agtx_bin);+ self.build_interactive_command("")+ }}/// Generic agent implementation that works with any Agent config@@ -72,6 +80,18 @@ impl AgentOperations for CodingAgent {fn build_interactive_command(&self, prompt: &str) -> String {self.agent.build_interactive_command(prompt)}++ fn build_orchestrator_command(&self, mcp_json: &str, _agtx_bin: &str) -> String {+ match self.agent.name.as_str() {+ "claude" => format!(+ "claude mcp add-json agtx '{}' --scope local && {}; claude mcp remove agtx --scope local",+ mcp_json,+ self.build_interactive_command("")+ ),+ // To add a new orchestrator agent, add a match arm here.+ _ => self.build_interactive_command(""),+ }+ }}/// Registry that maps agent names to AgentOperations instances.diff --git a/src/db/models.rs b/src/db/models.rsindex 8315fd8..41ea0e7 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -71,6 +71,7 @@ pub struct Task {pub plugin: Option<String>,pub cycle: i32,pub referenced_tasks: Option<String>,+ pub escalation_note: Option<String>,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,}@@ -94,6 +95,7 @@ impl Task {plugin: None,cycle: 1,referenced_tasks: None,+ escalation_note: None,created_at: now,updated_at: now,}@@ -150,6 +152,7 @@ pub struct TransitionRequest {pub id: String,pub task_id: String,pub action: String,+ pub reason: Option<String>,pub requested_at: DateTime<Utc>,pub processed_at: Option<DateTime<Utc>>,pub error: Option<String>,@@ -161,6 +164,7 @@ impl TransitionRequest {id: uuid::Uuid::new_v4().to_string(),task_id: task_id.into(),action: action.into(),+ reason: None,requested_at: Utc::now(),processed_at: None,error: None,diff --git a/src/db/schema.rs b/src/db/schema.rsindex cbecf56..90dba51 100644--- a/src/db/schema.rs+++ b/src/db/schema.rs@@ -116,6 +116,7 @@ impl Database {let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN plugin TEXT", []);let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN cycle INTEGER NOT NULL DEFAULT 1", []);let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN referenced_tasks TEXT", []);+ let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN escalation_note TEXT", []);// MCP transition request queueself.conn.execute_batch(@@ -137,6 +138,9 @@ impl Database {"#,)?;+ // Migration: add reason column to transition_requests if it doesn't exist+ let _ = self.conn.execute("ALTER TABLE transition_requests ADD COLUMN reason TEXT", []);+Ok(())}@@ -173,8 +177,8 @@ impl Database {pub fn create_task(&self, task: &Task) -> Result<()> {self.conn.execute(r#"- INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, referenced_tasks, created_at, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)+ INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, referenced_tasks, escalation_note, created_at, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)"#,params![task.id,@@ -191,6 +195,7 @@ impl Database {task.plugin,task.cycle,task.referenced_tasks,+ task.escalation_note,task.created_at.to_rfc3339(),task.updated_at.to_rfc3339(),],@@ -214,7 +219,8 @@ impl Database {plugin = ?11,cycle = ?12,referenced_tasks = ?13,- updated_at = ?14+ escalation_note = ?14,+ updated_at = ?15WHERE id = ?1"#,params![@@ -231,6 +237,7 @@ impl Database {task.plugin,task.cycle,task.referenced_tasks,+ task.escalation_note,task.updated_at.to_rfc3339(),],)?;@@ -260,6 +267,7 @@ impl Database {plugin: row.get("plugin").ok().flatten(),cycle: row.get("cycle").unwrap_or(1),referenced_tasks: row.get("referenced_tasks").ok().flatten(),+ escalation_note: row.get("escalation_note").ok().flatten(),created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>("created_at")?).map(|dt| dt.with_timezone(&chrono::Utc)).unwrap_or_else(|_| chrono::Utc::now()),@@ -363,13 +371,14 @@ impl Database {pub fn create_transition_request(&self, req: &TransitionRequest) -> Result<()> {self.conn.execute(r#"- INSERT INTO transition_requests (id, task_id, action, requested_at, processed_at, error)- VALUES (?1, ?2, ?3, ?4, ?5, ?6)+ INSERT INTO transition_requests (id, task_id, action, reason, requested_at, processed_at, error)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"#,params![req.id,req.task_id,req.action,+ req.reason,req.requested_at.to_rfc3339(),req.processed_at.map(|dt| dt.to_rfc3339()),req.error,@@ -425,6 +434,7 @@ impl Database {id: row.get("id")?,task_id: row.get("task_id")?,action: row.get("action")?,+ reason: row.get("reason").ok().flatten(),requested_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>("requested_at")?,)diff --git a/src/mcp/server.rs b/src/mcp/server.rsindex 76b7b27..13d02ac 100644--- a/src/mcp/server.rs+++ b/src/mcp/server.rs@@ -1,4 +1,5 @@use std::path::PathBuf;+use std::process::Command;use rmcp::{ServerHandler, ServiceExt,@@ -36,11 +37,14 @@ pub struct MoveTaskParams {/// The task ID (UUID)#[schemars(description = "The task ID (UUID)")]pub task_id: String,- /// Action: "research", "move_forward", "move_to_planning", "move_to_running", "move_to_review", "move_to_done", "resume"+ /// Action: "research", "move_forward", "move_to_planning", "move_to_running", "move_to_review", "move_to_done", "resume", "escalate_to_user"#[schemars(- description = "Action: research (start research for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume"+ description = "Action: research (start research for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume, escalate_to_user")]pub action: String,+ /// Optional reason (used with escalate_to_user action)+ #[schemars(description = "Optional reason, used with escalate_to_user action")]+ pub reason: Option<String>,}#[derive(Debug, Deserialize, schemars::JsonSchema)]@@ -60,6 +64,26 @@ pub struct CheckConflictsParams {#[derive(Debug, Deserialize, schemars::JsonSchema)]pub struct GetNotificationsParams {}+#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct ReadPaneParams {+ /// The task ID (UUID)+ #[schemars(description = "The task ID (UUID)")]+ pub task_id: String,+ /// Number of lines to read from the end of the pane (default 50)+ #[schemars(description = "Number of lines to read from the end of the pane (default 50)")]+ pub lines: Option<i32>,+}++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct SendToTaskParams {+ /// The task ID (UUID)+ #[schemars(description = "The task ID (UUID)")]+ pub task_id: String,+ /// Message to send to the task's agent pane (followed by Enter)+ #[schemars(description = "Message to send to the task's agent pane (followed by Enter)")]+ pub message: String,+}+// === Response types ===#[derive(Serialize)]@@ -142,6 +166,22 @@ struct GetNotificationsResponse {notifications: Vec<NotificationItem>,}+#[derive(Serialize)]+struct ReadPaneResponse {+ task_id: String,+ session_name: String,+ content: String,+ lines_requested: i32,+}++#[derive(Serialize)]+struct SendToTaskResponse {+ task_id: String,+ session_name: String,+ success: bool,+ message: String,+}+// === MCP Server ===#[derive(Debug, Clone)]@@ -183,9 +223,11 @@ impl AgtxMcpServer {}TaskStatus::Planning => {actions.push("move_forward".to_string());+ actions.push("escalate_to_user".to_string());}TaskStatus::Running => {actions.push("move_forward".to_string());+ actions.push("escalate_to_user".to_string());}TaskStatus::Review => {actions.push("move_to_done".to_string());@@ -290,7 +332,7 @@ impl AgtxMcpServer {}}- #[tool(description = "Queue a task state transition. The agtx TUI will process it and execute all side effects (worktree creation, agent spawning, etc). Use get_transition_status to check completion. Actions: research (start research phase for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume")]+ #[tool(description = "Queue a task state transition. The agtx TUI will process it and execute all side effects (worktree creation, agent spawning, etc). Use get_transition_status to check completion. Actions: research (start research phase for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume, escalate_to_user (flag task for user attention with an optional reason)")]fn move_task(&self, Parameters(params): Parameters<MoveTaskParams>) -> String {let valid_actions = ["research",@@ -300,6 +342,7 @@ impl AgtxMcpServer {"move_to_review","move_to_done","resume",+ "escalate_to_user",];if !valid_actions.contains(¶ms.action.as_str()) {return format!(@@ -318,7 +361,8 @@ impl AgtxMcpServer {Err(e) => return format!("Error checking task: {}", e),}- let req = TransitionRequest::new(¶ms.task_id, ¶ms.action);+ let mut req = TransitionRequest::new(¶ms.task_id, ¶ms.action);+ req.reason = params.reason.clone();let request_id = req.id.clone();match db.create_transition_request(&req) {@@ -465,6 +509,102 @@ impl AgtxMcpServer {Err(e) => e,}}++ #[tool(description = "Read the last N lines of a task's agent tmux pane. Use this to understand what the agent is showing β e.g., when a task has been idle for a while. Returns pane content as text.")]+ fn read_pane_content(&self, Parameters(params): Parameters<ReadPaneParams>) -> String {+ let db = match self.open_project_db() {+ Ok(db) => db,+ Err(e) => return e,+ };++ let task = match db.get_task(¶ms.task_id) {+ Ok(Some(t)) => t,+ Ok(None) => return format!("Task not found: {}", params.task_id),+ Err(e) => return format!("Error getting task: {}", e),+ };++ let session_name = match task.session_name {+ Some(ref s) => s.clone(),+ None => return format!("Task {} has no active session", params.task_id),+ };++ let lines = params.lines.unwrap_or(50);+ let lines_arg = format!("-{}", lines);++ let output = Command::new("tmux")+ .args(["-L", "agtx", "capture-pane", "-t", &session_name, "-p", "-S", &lines_arg])+ .output();++ match output {+ Ok(out) => {+ let content = String::from_utf8_lossy(&out.stdout).to_string();+ let response = ReadPaneResponse {+ task_id: params.task_id,+ session_name,+ content,+ lines_requested: lines,+ };+ serde_json::to_string_pretty(&response)+ .unwrap_or_else(|e| format!("Error serializing: {}", e))+ }+ Err(e) => format!("Error reading pane content: {}", e),+ }+ }++ #[tool(description = "Send a message to a task's agent pane (followed by Enter). Only works for tasks in Planning or Running status. Use this to nudge a stuck agent, answer a CLI prompt (e.g. 'y' for yes), or provide guidance.")]+ fn send_to_task(&self, Parameters(params): Parameters<SendToTaskParams>) -> String {+ let db = match self.open_project_db() {+ Ok(db) => db,+ Err(e) => return e,+ };++ let task = match db.get_task(¶ms.task_id) {+ Ok(Some(t)) => t,+ Ok(None) => return format!("Task not found: {}", params.task_id),+ Err(e) => return format!("Error getting task: {}", e),+ };++ // Only allow sending to active phases+ if !matches!(task.status, TaskStatus::Planning | TaskStatus::Running) {+ return format!(+ "Error: task is not in an active phase (current: {}). send_to_task only works for Planning or Running tasks.",+ task.status.as_str()+ );+ }++ let session_name = match task.session_name {+ Some(ref s) => s.clone(),+ None => return format!("Task {} has no active session", params.task_id),+ };++ // Send the message text+ let send_text = Command::new("tmux")+ .args(["-L", "agtx", "send-keys", "-t", &session_name, ¶ms.message])+ .output();++ if let Err(e) = send_text {+ return format!("Error sending message: {}", e);+ }++ // Send Enter+ let send_enter = Command::new("tmux")+ .args(["-L", "agtx", "send-keys", "-t", &session_name, "Enter"])+ .output();++ match send_enter {+ Ok(_) => {+ let response = SendToTaskResponse {+ task_id: params.task_id,+ session_name,+ success: true,+ message: format!("Message sent: {}", params.message),+ };+ serde_json::to_string_pretty(&response)+ .unwrap_or_else(|e| format!("Error serializing: {}", e))+ }+ Err(e) => format!("Error sending Enter: {}", e),+ }+ }}#[tool_handler]diff --git a/src/tui/app.rs b/src/tui/app.rsindex 8dc60bb..2819dfe 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -235,6 +235,10 @@ struct AppState {pane_content_hashes: HashMap<String, (u64, Instant)>,// Guard: task IDs for which merge-conflict check has already been performedmerge_conflict_checked: HashSet<String>,+ // Guard: task IDs for which stuck-task notification has been fired (reset on phase advance)+ stuck_task_notified: HashSet<String>,+ // When each task first became Idle (for stuck-task detection)+ stuck_task_idle_since: HashMap<String, Instant>,cached_plugin: Option<Option<WorkflowPlugin>>,// Transient warning message shown in footer (auto-clears after a few seconds)warning_message: Option<(String, Instant)>,@@ -552,6 +556,8 @@ impl App {spinner_frame: 0,pane_content_hashes: HashMap::new(),merge_conflict_checked: HashSet::new(),+ stuck_task_notified: HashSet::new(),+ stuck_task_idle_since: HashMap::new(),cached_plugin: None,warning_message: None,plugin_select_popup: None,@@ -700,6 +706,8 @@ impl App {spinner_frame: 0,pane_content_hashes: HashMap::new(),merge_conflict_checked: HashSet::new(),+ stuck_task_notified: HashSet::new(),+ stuck_task_idle_since: HashMap::new(),cached_plugin: None,warning_message: None,plugin_select_popup: None,@@ -1781,6 +1789,8 @@ impl App {header_bg: hex_to_color(&theme.color_popup_header),footer_fg: Color::Black,footer_bg: hex_to_color(&theme.color_dimmed),+ escalation_fg: Color::Black,+ escalation_bg: Color::Yellow,};shell_popup::render_shell_popup(popup, frame, popup_area, styled_lines, &colors);@@ -1838,7 +1848,13 @@ impl App {Some((PhaseStatus::Exited, _)) => Span::styled("\u{2717} ", Style::default().fg(Color::Red)),None => Span::raw(""),};- let title_spans = Line::from(vec![indicator, Span::styled(title, title_style)]);+ // Escalation warning indicator+ let warn_span = if task.escalation_note.is_some() {+ Span::styled("\u{26a0} ", Style::default().fg(hex_to_color(&theme.color_accent)).bold())+ } else {+ Span::raw("")+ };+ let title_spans = Line::from(vec![indicator, warn_span, Span::styled(title, title_style)]);let title_line = Paragraph::new(title_spans);let title_area = Rect {x: inner.x,@@ -2581,6 +2597,27 @@ impl App {let window_name = popup.window_name.clone();let has_ctrl = key.modifiers.contains(KeyModifiers::CONTROL);+ // Dismiss escalation note on any key press (before forwarding)+ if popup.escalation_note.is_some() {+ let task_id = popup.task_id.clone();+ popup.escalation_note = None;+ if let Some(id) = task_id {+ if let Some(db) = &self.state.db {+ if let Ok(Some(mut task)) = db.get_task(&id) {+ task.escalation_note = None;+ task.updated_at = chrono::Utc::now();+ let _ = db.update_task(&task);+ }+ }+ // Update the in-memory task list too+ if let Some(t) = self.state.board.tasks.iter_mut().find(|t| t.id == id) {+ t.escalation_note = None;+ }+ }+ // Return early so the keypress only dismisses the banner, not forwarded+ return Ok(());+ }+match key.code {// Ctrl+q = close popupKeyCode::Char('q') if has_ctrl => {@@ -4346,6 +4383,20 @@ impl App {}self.move_review_to_running(&req.task_id)?;}+ "escalate_to_user" => {+ if !matches!(task.status, TaskStatus::Planning | TaskStatus::Running) {+ anyhow::bail!(+ "escalate_to_user is only valid for Planning or Running tasks (current: {})",+ task.status.as_str()+ );+ }+ task.escalation_note = req.reason.clone().or_else(|| Some("Needs attention".to_string()));+ task.updated_at = chrono::Utc::now();+ if let Some(db) = &self.state.db {+ db.update_task(&task)?;+ }+ self.refresh_tasks()?;+ }other => {anyhow::bail!("Unknown action: {}", other);}@@ -4488,16 +4539,7 @@ impl App {});let mcp_json_str = mcp_json.to_string().replace('\'', "'\\''");- // Build agent command: register MCP in local scope, launch agent, clean up on exit- // --scope local stores in ~/.claude.json tied to project path (not in project files)- let agent_base = agent.build_interactive_command("");- let agent_cmd = match default_agent.as_str() {- "claude" => format!(- "claude mcp add-json agtx '{}' --scope local && {}; claude mcp remove agtx --scope local",- mcp_json_str, agent_base- ),- _ => agent_base,- };+ let agent_cmd = agent.build_orchestrator_command(&mcp_json_str, &agtx_bin);// Ensure project tmux session existsensure_project_tmux_session(&project_name, &project_path, self.state.tmux_ops.as_ref());@@ -4547,7 +4589,11 @@ impl App {fn open_selected_task(&mut self) -> Result<()> {if let Some(task) = self.state.board.selected_task() {if let Some(window_name) = &task.session_name.clone() {+ let task_id = task.id.clone();+ let escalation_note = task.escalation_note.clone();let mut popup = ShellPopup::new(task.title.clone(), window_name.clone());+ popup.task_id = Some(task_id);+ popup.escalation_note = escalation_note;// Resize tmux window to match popup dimensions (uses same constants as draw_shell_popup)if let Ok((_term_width, term_height)) = crossterm::terminal::size() {@@ -4917,6 +4963,40 @@ impl App {}}}++ // Stuck-task notification: fire once when Planning/Running task has been Idle for 1+ min+ if matches!(task_status.status, TaskStatus::Planning | TaskStatus::Running)+ && phase == PhaseStatus::Idle+ && self.state.orchestrator_session.is_some()+ {+ let stuck_key = format!("{}:{}", task_status.task_id, task_status.status.as_str());+ if !self.state.stuck_task_notified.contains(&stuck_key) {+ // Track when this task first became Idle+ let idle_since = self.state.stuck_task_idle_since+ .entry(task_status.task_id.clone())+ .or_insert(now);++ if now.duration_since(*idle_since) >= std::time::Duration::from_secs(60) {+ self.state.stuck_task_notified.insert(stuck_key);++ if let Some(db) = &self.state.db {+ let task_title = self.state.board.tasks.iter()+ .find(|t| t.id == task_status.task_id)+ .map(|t| t.title.as_str())+ .unwrap_or("unknown");+ let short_id = if task_status.task_id.len() >= 8 { &task_status.task_id[..8] } else { &task_status.task_id };+ let notif = crate::db::Notification::new(format!(+ "Task \"{}\" ({}) has been idle for 1m in phase: {}",+ task_title, short_id, task_status.status.as_str()+ ));+ let _ = db.create_notification(¬if);+ }+ }+ }+ } else if phase != PhaseStatus::Idle {+ // Task is no longer idle β reset the idle-since timer+ self.state.stuck_task_idle_since.remove(&task_status.task_id);+ }}self.state.spinner_frame = self.state.spinner_frame.wrapping_add(1);@@ -4960,6 +5040,8 @@ impl App {// Clear per-task caches from previous projectself.state.merge_conflict_checked.clear();+ self.state.stuck_task_notified.clear();+ self.state.stuck_task_idle_since.clear();// Reload tasks for new projectself.refresh_tasks()?;diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex 011d0e5..0f809b5 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -207,6 +207,7 @@ fn test_create_pr_with_content_success() {plugin: None,cycle: 1,referenced_tasks: None,+ escalation_note: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -296,6 +297,7 @@ fn test_create_pr_with_content_no_changes() {plugin: None,cycle: 1,referenced_tasks: None,+ escalation_note: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -355,6 +357,7 @@ fn test_create_pr_with_content_push_failure() {plugin: None,cycle: 1,referenced_tasks: None,+ escalation_note: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -411,6 +414,7 @@ fn test_push_changes_to_existing_pr_success() {plugin: None,cycle: 1,referenced_tasks: None,+ escalation_note: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -464,6 +468,7 @@ fn test_push_changes_to_existing_pr_no_changes() {plugin: None,cycle: 1,referenced_tasks: None,+ escalation_note: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -500,6 +505,7 @@ fn test_push_changes_to_existing_pr_no_url() {plugin: None,cycle: 1,referenced_tasks: None,+ escalation_note: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -5806,7 +5812,7 @@ fn test_toggle_orchestrator_spawns_new_session() {let mut mock_registry = MockAgentRegistry::new();mock_registry.expect_get().returning(|_| {let mut ops = MockAgentOperations::new();- ops.expect_build_interactive_command().returning(|_| "claude".to_string());+ ops.expect_build_orchestrator_command().returning(|_, _| "claude".to_string());Arc::new(ops)});@@ -5879,7 +5885,7 @@ fn test_toggle_orchestrator_clears_stale_session_and_respawns() {let mut mock_registry = MockAgentRegistry::new();mock_registry.expect_get().returning(|_| {let mut ops = MockAgentOperations::new();- ops.expect_build_interactive_command().returning(|_| "claude".to_string());+ ops.expect_build_orchestrator_command().returning(|_, _| "claude".to_string());Arc::new(ops)});@@ -6135,6 +6141,201 @@ fn test_deliver_orchestrator_notifications_noop_when_no_notifications() {// No panic = correct (send_keys not called)}+// =============================================================================+// Tests for stuck-task notification logic in apply_session_refresh+// =============================================================================++#[test]+#[cfg(feature = "test-mocks")]+fn test_stuck_task_notification_fires_after_1_min_idle() {+ // Task Idle for β₯60s with orchestrator active β notification written to DB+ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_window_exists().returning(|_| Ok(false));+ let mut app = App::new_for_test(+ Some(PathBuf::from("/tmp/test-project")),+ Arc::new(mock_tmux),+ Arc::new(MockGitOperations::new()),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ ).unwrap();++ let db = app.state.db.as_ref().unwrap();+ let mut task = Task::new("stuck task", "claude", "test-project");+ task.id = "t1".to_string();+ task.status = TaskStatus::Running;+ db.create_task(&task).unwrap();+ app.refresh_tasks().unwrap();++ app.state.orchestrator_session = Some("orch-session".to_string());+ // Simulate task has been Idle for 65 seconds+ app.state.stuck_task_idle_since.insert(+ "t1".to_string(),+ Instant::now() - std::time::Duration::from_secs(65),+ );++ let result = SessionRefreshResult {+ statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Idle, false)],+ };+ app.apply_session_refresh(result);++ let notifs = app.state.db.as_ref().unwrap().peek_notifications().unwrap();+ assert!(!notifs.is_empty(), "should have created a stuck-task notification");+ assert!(notifs[0].message.contains("stuck task"));+ assert!(notifs[0].message.contains("running"));+ assert!(notifs[0].message.contains("idle"));+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_stuck_task_notification_does_not_fire_before_1_min() {+ // Task Idle for only 30s β no notification yet+ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_window_exists().returning(|_| Ok(false));+ let mut app = App::new_for_test(+ Some(PathBuf::from("/tmp/test-project")),+ Arc::new(mock_tmux),+ Arc::new(MockGitOperations::new()),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ ).unwrap();++ let db = app.state.db.as_ref().unwrap();+ let mut task = Task::new("pending task", "claude", "test-project");+ task.id = "t1".to_string();+ task.status = TaskStatus::Running;+ db.create_task(&task).unwrap();+ app.refresh_tasks().unwrap();++ app.state.orchestrator_session = Some("orch-session".to_string());+ app.state.stuck_task_idle_since.insert(+ "t1".to_string(),+ Instant::now() - std::time::Duration::from_secs(30),+ );++ let result = SessionRefreshResult {+ statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Idle, false)],+ };+ app.apply_session_refresh(result);++ let notifs = app.state.db.as_ref().unwrap().peek_notifications().unwrap();+ assert!(notifs.is_empty(), "should not have fired notification before 1 minute");+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_stuck_task_notification_fires_once_per_phase() {+ // Guard ensures notification fires only once even across multiple refreshes+ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_window_exists().returning(|_| Ok(false));+ let mut app = App::new_for_test(+ Some(PathBuf::from("/tmp/test-project")),+ Arc::new(mock_tmux),+ Arc::new(MockGitOperations::new()),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ ).unwrap();++ let db = app.state.db.as_ref().unwrap();+ let mut task = Task::new("my task", "claude", "test-project");+ task.id = "t1".to_string();+ task.status = TaskStatus::Running;+ db.create_task(&task).unwrap();+ app.refresh_tasks().unwrap();++ app.state.orchestrator_session = Some("orch-session".to_string());+ app.state.stuck_task_idle_since.insert(+ "t1".to_string(),+ Instant::now() - std::time::Duration::from_secs(65),+ );++ let make_result = || SessionRefreshResult {+ statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Idle, false)],+ };++ app.apply_session_refresh(make_result());+ app.apply_session_refresh(make_result());+ app.apply_session_refresh(make_result());++ let notifs = app.state.db.as_ref().unwrap().peek_notifications().unwrap();+ assert_eq!(notifs.len(), 1, "notification should fire exactly once");+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_stuck_task_notification_not_fired_without_orchestrator() {+ // No orchestrator_session β no notification even after 1+ min idle+ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_window_exists().returning(|_| Ok(false));+ let mut app = App::new_for_test(+ Some(PathBuf::from("/tmp/test-project")),+ Arc::new(mock_tmux),+ Arc::new(MockGitOperations::new()),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ ).unwrap();++ let db = app.state.db.as_ref().unwrap();+ let mut task = Task::new("my task", "claude", "test-project");+ task.id = "t1".to_string();+ task.status = TaskStatus::Running;+ db.create_task(&task).unwrap();+ app.refresh_tasks().unwrap();++ // No orchestrator+ app.state.orchestrator_session = None;+ app.state.stuck_task_idle_since.insert(+ "t1".to_string(),+ Instant::now() - std::time::Duration::from_secs(65),+ );++ let result = SessionRefreshResult {+ statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Idle, false)],+ };+ app.apply_session_refresh(result);++ let notifs = app.state.db.as_ref().unwrap().peek_notifications().unwrap();+ assert!(notifs.is_empty(), "no notification without orchestrator");+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_stuck_task_idle_since_cleared_when_not_idle() {+ // Task transitions out of Idle β idle_since timer is cleared+ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_window_exists().returning(|_| Ok(false));+ let mut app = App::new_for_test(+ Some(PathBuf::from("/tmp/test-project")),+ Arc::new(mock_tmux),+ Arc::new(MockGitOperations::new()),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ ).unwrap();++ let db = app.state.db.as_ref().unwrap();+ let mut task = Task::new("my task", "claude", "test-project");+ task.id = "t1".to_string();+ task.status = TaskStatus::Running;+ db.create_task(&task).unwrap();+ app.refresh_tasks().unwrap();++ app.state.orchestrator_session = Some("orch-session".to_string());+ app.state.stuck_task_idle_since.insert(+ "t1".to_string(),+ Instant::now() - std::time::Duration::from_secs(30),+ );++ // Task is now Working (no longer Idle)+ let result = SessionRefreshResult {+ statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Working, false)],+ };+ app.apply_session_refresh(result);++ assert!(+ !app.state.stuck_task_idle_since.contains_key("t1"),+ "idle_since timer should be cleared when task is no longer Idle"+ );+}+// =============================================================================// Tests for pure functions: fuzzy_score, word_boundary_left/right,diff --git a/src/tui/shell_popup.rs b/src/tui/shell_popup.rsindex 5868031..7f77711 100644--- a/src/tui/shell_popup.rs+++ b/src/tui/shell_popup.rs@@ -11,6 +11,10 @@ pub struct ShellPopup {pub cached_content: Vec<u8>,/// Last known pane dimensions for resize detectionpub last_pane_size: Option<(u16, u16)>,+ /// Escalation note from the orchestrator, shown as a banner+ pub escalation_note: Option<String>,+ /// Task ID (used to clear escalation note on dismiss)+ pub task_id: Option<String>,}impl ShellPopup {@@ -21,6 +25,8 @@ impl ShellPopup {scroll_offset: 0,cached_content: Vec::new(),last_pane_size: None,+ escalation_note: None,+ task_id: None,}}@@ -209,6 +215,8 @@ pub struct ShellPopupColors {pub header_bg: Color,pub footer_fg: Color,pub footer_bg: Color,+ pub escalation_fg: Color,+ pub escalation_bg: Color,}impl Default for ShellPopupColors {@@ -219,6 +227,8 @@ impl Default for ShellPopupColors {header_bg: Color::Cyan,footer_fg: Color::Black,footer_bg: Color::Gray,+ escalation_fg: Color::Black,+ escalation_bg: Color::Yellow,}}}@@ -246,13 +256,17 @@ pub fn render_shell_popup(let inner_area = border_block.inner(popup_area);frame.render_widget(border_block, popup_area);- // Layout: header, content, footer (inside the border)+ // Layout: header, optional escalation banner, content, footer (inside the border)+ let has_escalation = popup.escalation_note.is_some();+ let escalation_height = if has_escalation { 2u16 } else { 0u16 };+let popup_chunks = Layout::default().direction(Direction::Vertical).constraints([- Constraint::Length(1), // Title bar- Constraint::Min(0), // Shell content- Constraint::Length(1), // Footer+ Constraint::Length(1), // Title bar+ Constraint::Length(escalation_height), // Escalation banner (0 if none)+ Constraint::Min(0), // Shell content+ Constraint::Length(1), // Footer]).split(inner_area);@@ -263,20 +277,31 @@ pub fn render_shell_popup(.style(Style::default().fg(colors.header_fg).bg(colors.header_bg));frame.render_widget(title_bar, popup_chunks[0]);+ // Escalation banner (if present)+ if let Some(ref note) = popup.escalation_note {+ let banner_text = format!(" \u{26a0} {} ", note);+ let padded_banner = format!("{:<width$}", banner_text, width = popup_chunks[1].width as usize);+ let hint = format!("{:<width$}", " Press any key to dismiss", width = popup_chunks[1].width as usize);+ let banner_content = format!("{}\n{}", padded_banner, hint);+ let banner = Paragraph::new(banner_content)+ .style(Style::default().fg(colors.escalation_fg).bg(colors.escalation_bg));+ frame.render_widget(banner, popup_chunks[1]);+ }+// Shell content- let visible_height = popup_chunks[1].height as usize;+ let visible_height = popup_chunks[2].height as usize;// Use the testable helper to compute visible lineslet (visible_lines, start_line, _total_lines) =compute_visible_lines(styled_lines, visible_height, popup.scroll_offset);let content = Paragraph::new(visible_lines);- frame.render_widget(content, popup_chunks[1]);+ frame.render_widget(content, popup_chunks[2]);// Footer with scroll indicator (pad to fill width)let footer_text = build_footer_text(popup.scroll_offset, start_line);- let padded_footer = format!("{:<width$}", footer_text, width = popup_chunks[2].width as usize);+ let padded_footer = format!("{:<width$}", footer_text, width = popup_chunks[3].width as usize);let footer = Paragraph::new(padded_footer).style(Style::default().fg(colors.footer_fg).bg(colors.footer_bg));- frame.render_widget(footer, popup_chunks[2]);+ frame.render_widget(footer, popup_chunks[3]);}diff --git a/tests/shell_popup_tests.rs b/tests/shell_popup_tests.rsindex 9eaadf8..0a57458 100644--- a/tests/shell_popup_tests.rs+++ b/tests/shell_popup_tests.rs@@ -309,6 +309,8 @@ fn test_render_shell_popup_custom_colors() {header_bg: Color::Blue,footer_fg: Color::Yellow,footer_bg: Color::Magenta,+ escalation_fg: Color::Black,+ escalation_bg: Color::Yellow,};let lines: Vec<Line> = vec![Line::from("content")];