Skip to content

armgit / agtx

Public Imported from GitHub
0

πŸ„πŸΌβ€β™‚οΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.

test: add missing tests to app_rs

fynnfluegge640374c17cbe
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index cd543db..86459f6 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -3993,3 +3993,2967 @@ fn test_orchestrator_empty_content_both_sides() {
assert_eq!(result, OrchestratorIdleResult::Waiting);
}
+// =============================================================================
+// Tests for task lifecycle transition functions
+// =============================================================================
+
+/// Helper: create a Task with the given id, title, and status.
+#[cfg(feature = "test-mocks")]
+fn make_test_task(id: &str, title: &str, status: TaskStatus) -> Task {
+ let mut t = Task::new(title, "claude", "test-project");
+ t.id = id.to_string();
+ t.status = status;
+ t
+}
+
+// --- check_phase_incomplete ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_check_phase_incomplete_skip_move_confirm() {
+ // When skip_move_confirm is set, always returns false without calling tmux
+ let mock_tmux = MockTmuxOperations::new(); // no expectations
+ 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();
+ app.state.skip_move_confirm = true;
+
+ let task = make_test_task("t1", "My task", TaskStatus::Planning);
+ let result = app.check_phase_incomplete(&task, TaskStatus::Planning, TaskStatus::Running);
+ assert!(!result);
+ assert!(app.state.move_confirm_popup.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_check_phase_incomplete_backlog_returns_false() {
+ // Backlog tasks are not in Planning/Running/Review β€” always returns false
+ let mock_tmux = MockTmuxOperations::new(); // no expectations
+ 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 task = make_test_task("t1", "My task", TaskStatus::Backlog);
+ let result = app.check_phase_incomplete(&task, TaskStatus::Backlog, TaskStatus::Planning);
+ assert!(!result);
+ assert!(app.state.move_confirm_popup.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_check_phase_incomplete_no_worktree_returns_false() {
+ // Task in Planning but no worktree_path β€” returns false (no artifact check possible)
+ let mock_tmux = MockTmuxOperations::new();
+ 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 mut task = make_test_task("t1", "My task", TaskStatus::Planning);
+ task.worktree_path = None;
+ let result = app.check_phase_incomplete(&task, TaskStatus::Planning, TaskStatus::Running);
+ assert!(!result);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_check_phase_incomplete_artifact_exists_returns_false() {
+ // Artifact exists β†’ phase is complete β†’ returns false, no window_exists call
+ let tmp = std::env::temp_dir().join("agtx_test_artifact_complete");
+ let _ = std::fs::remove_dir_all(&tmp);
+ std::fs::create_dir_all(&tmp).unwrap();
+ // agtx default planning artifact is .agtx/plan.md
+ let agtx_dir = tmp.join(".agtx");
+ std::fs::create_dir_all(&agtx_dir).unwrap();
+ std::fs::write(agtx_dir.join("plan.md"), "# Plan").unwrap();
+
+ let mock_tmux = MockTmuxOperations::new(); // no window_exists expectation
+ 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 mut task = make_test_task("t1", "My task", TaskStatus::Planning);
+ task.worktree_path = Some(tmp.to_string_lossy().to_string());
+ let result = app.check_phase_incomplete(&task, TaskStatus::Planning, TaskStatus::Running);
+ assert!(!result);
+
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_check_phase_incomplete_no_tmux_window_returns_false() {
+ // No artifact, but tmux window doesn't exist β†’ agent not running β†’ returns false
+ let tmp = std::env::temp_dir().join("agtx_test_no_window");
+ let _ = std::fs::remove_dir_all(&tmp);
+ std::fs::create_dir_all(&tmp).unwrap();
+
+ 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 mut task = make_test_task("t1", "My task", TaskStatus::Planning);
+ task.worktree_path = Some(tmp.to_string_lossy().to_string());
+ task.session_name = Some("proj:t1".to_string());
+ let result = app.check_phase_incomplete(&task, TaskStatus::Planning, TaskStatus::Running);
+ assert!(!result);
+ assert!(app.state.move_confirm_popup.is_none());
+
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_check_phase_incomplete_agent_running_sets_popup() {
+ // No artifact, window exists, agent process visible β†’ sets popup and returns true
+ let tmp = std::env::temp_dir().join("agtx_test_agent_running");
+ let _ = std::fs::remove_dir_all(&tmp);
+ std::fs::create_dir_all(&tmp).unwrap();
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux
+ .expect_window_exists()
+ .returning(|_| Ok(true));
+ // is_agent_active checks pane_current_command first
+ mock_tmux
+ .expect_pane_current_command()
+ .returning(|_| Some("claude".to_string()));
+
+ 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 mut task = make_test_task("t1", "My task", TaskStatus::Planning);
+ task.worktree_path = Some(tmp.to_string_lossy().to_string());
+ task.session_name = Some("proj:t1".to_string());
+ let result = app.check_phase_incomplete(&task, TaskStatus::Planning, TaskStatus::Running);
+ assert!(result);
+ assert!(app.state.move_confirm_popup.is_some());
+
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+// --- transition_to_planning ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_planning_stamps_plugin() {
+ // When task.plugin is None, config's workflow_plugin is stamped onto the task
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+ // Set the project workflow plugin
+ app.state.config.workflow_plugin = Some("agtx".to_string());
+
+ let mut task = make_test_task("t1", "My task", TaskStatus::Backlog);
+ task.plugin = None;
+
+ let _ = app.transition_to_planning(&mut task, Path::new("/tmp/test-project"));
+
+ // Plugin should have been stamped
+ assert_eq!(task.plugin.as_deref(), Some("agtx"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_planning_warning_when_research_required() {
+ // GSD planning doesn't accept {task} in its command β€” requires prior research artifact.
+ // With no worktree, should set warning_message and return Ok(true).
+ let mock_tmux = MockTmuxOperations::new();
+ 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 mut task = make_test_task("t1", "My task", TaskStatus::Backlog);
+ // Use gsd plugin β€” planning phase requires prior research artifact
+ task.plugin = Some("gsd".to_string());
+ task.worktree_path = None; // no research done yet
+
+ let result = app.transition_to_planning(&mut task, Path::new("/tmp/test-project"));
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), true); // handled, don't continue with db update
+ assert!(app.state.warning_message.is_some());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_planning_reuses_live_session() {
+ // Task has a live session β†’ reuses it (returns Ok(false) to continue with db update)
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux
+ .expect_window_exists()
+ .returning(|_| Ok(true));
+ // spawn_send_to_agent may call these; allow any number of calls
+ mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
+ mock_tmux.expect_send_keys_literal().returning(|_, _| Ok(()));
+ mock_tmux.expect_capture_pane().returning(|_| Ok(String::new()));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ let mut task = make_test_task("t1", "My task", TaskStatus::Backlog);
+ task.session_name = Some("test-project:task-t1--test-project--my-task".to_string());
+
+ let result = app.transition_to_planning(&mut task, Path::new("/tmp/test-project"));
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), false); // Ok(false) β†’ continue with db update
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_planning_returns_true_when_setup_in_progress() {
+ // If setup_rx is already set, return Ok(true) without spawning a new one
+ let mock_tmux = MockTmuxOperations::new();
+ 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();
+
+ // Pre-set a setup_rx to simulate in-progress setup
+ let (_tx, rx) = std::sync::mpsc::channel::<SetupResult>();
+ app.state.setup_rx = Some(rx);
+
+ let mut task = make_test_task("t1", "My task", TaskStatus::Backlog);
+ task.plugin = Some("agtx".to_string());
+
+ let result = app.transition_to_planning(&mut task, Path::new("/tmp/test-project"));
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), true);
+ // setup_rx should still be the original one (not replaced)
+ assert!(app.state.setup_rx.is_some());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_planning_spawns_background_setup() {
+ // No live session, no existing setup_rx β†’ spawns background setup and returns Ok(true)
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ let mut task = make_test_task("t1", "My task", TaskStatus::Backlog);
+ task.plugin = Some("agtx".to_string());
+
+ let result = app.transition_to_planning(&mut task, Path::new("/tmp/test-project"));
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), true);
+ // setup_rx should be set (background thread spawned)
+ assert!(app.state.setup_rx.is_some());
+}
+
+// --- transition_to_running ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_running_no_session_returns_false() {
+ // Task has no session_name β†’ nothing to send, returns Ok(false)
+ let mock_tmux = MockTmuxOperations::new(); // no send_keys expected
+ 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 mut task = make_test_task("t1", "My task", TaskStatus::Planning);
+ task.session_name = None;
+
+ let result = app.transition_to_running(&mut task);
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), false);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_running_with_session_returns_false() {
+ // Task has a session β†’ spawns send_to_agent (background), still returns Ok(false)
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
+ mock_tmux.expect_send_keys_literal().returning(|_, _| Ok(()));
+ mock_tmux.expect_capture_pane().returning(|_| Ok(String::new()));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ let mut task = make_test_task("t1", "My task", TaskStatus::Planning);
+ task.session_name = Some("test-project:task-t1".to_string());
+ task.agent = "claude".to_string();
+
+ let result = app.transition_to_running(&mut task);
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), false);
+ // agent should be unchanged (no switch configured)
+ assert_eq!(task.agent, "claude");
+}
+
+// --- transition_to_review ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_review_no_pr_sets_review_confirm_popup() {
+ // No existing PR β†’ shows review confirm popup (to ask if user wants to create PR)
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
+ mock_tmux.expect_send_keys_literal().returning(|_, _| Ok(()));
+ mock_tmux.expect_capture_pane().returning(|_| Ok(String::new()));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ let mut task = make_test_task("t1", "Implement feature", TaskStatus::Running);
+ task.pr_number = None;
+ task.session_name = Some("test-project:task-t1".to_string());
+
+ let result = app.transition_to_review(&mut task, Path::new("/tmp/test-project"));
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), true);
+ assert!(app.state.review_confirm_popup.is_some());
+ let popup = app.state.review_confirm_popup.as_ref().unwrap();
+ assert_eq!(popup.task_id, "t1");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_review_existing_pr_spawns_push() {
+ // PR already exists β†’ sets pr_status_popup (Pushing) and spawns push thread
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
+ mock_tmux.expect_send_keys_literal().returning(|_, _| Ok(()));
+ mock_tmux.expect_capture_pane().returning(|_| Ok(String::new()));
+
+ let mut mock_git = MockGitOperations::new();
+ // push_changes_to_existing_pr calls add_all, has_changes, push
+ mock_git.expect_add_all().returning(|_| Ok(()));
+ mock_git.expect_has_changes().returning(|_| false);
+ mock_git.expect_push().returning(|_, _, _| Ok(()));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ let mut mock_agent_ops = MockAgentOperations::new();
+ mock_agent_ops.expect_co_author_string().return_const("Test <[email protected]>".to_string());
+ let mock_agent_arc: Arc<dyn AgentOperations> = Arc::new(mock_agent_ops);
+ mock_registry
+ .expect_get()
+ .returning(move |_| Arc::clone(&mock_agent_arc));
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(mock_git),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(mock_registry),
+ ).unwrap();
+
+ let mut task = make_test_task("t1", "Implement feature", TaskStatus::Running);
+ task.pr_number = Some(42);
+ task.pr_url = Some("https://github.com/org/repo/pull/42".to_string());
+ task.session_name = Some("test-project:task-t1".to_string());
+ task.worktree_path = Some("/tmp/wt".to_string());
+ task.branch_name = Some("task/t1".to_string());
+
+ let result = app.transition_to_review(&mut task, Path::new("/tmp/test-project"));
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), true);
+ assert!(app.state.pr_status_popup.is_some());
+ assert!(app.state.pr_creation_rx.is_some());
+}
+
+// --- transition_to_done ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_done_merged_pr_shows_popup() {
+ // Task has a merged PR β†’ shows done_confirm_popup with Merged state
+ let mock_tmux = MockTmuxOperations::new();
+
+ let mut mock_git_provider = MockGitProviderOperations::new();
+ mock_git_provider
+ .expect_get_pr_state()
+ .returning(|_, _| Ok(PullRequestState::Merged));
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(MockGitOperations::new()),
+ Arc::new(mock_git_provider),
+ Arc::new(MockAgentRegistry::new()),
+ ).unwrap();
+
+ let mut task = make_test_task("t1", "My task", TaskStatus::Review);
+ task.pr_number = Some(5);
+
+ let result = app.transition_to_done(&mut task, Path::new("/tmp/test-project"));
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), true);
+ assert!(app.state.done_confirm_popup.is_some());
+ let popup = app.state.done_confirm_popup.as_ref().unwrap();
+ assert!(matches!(popup.pr_state, DoneConfirmPrState::Merged));
+ assert_eq!(popup.pr_number, 5);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_done_uncommitted_changes_shows_popup() {
+ // No PR, but uncommitted changes β†’ shows done_confirm_popup with UncommittedChanges
+ let mock_tmux = MockTmuxOperations::new();
+
+ let mut mock_git = MockGitOperations::new();
+ mock_git
+ .expect_has_changes()
+ .returning(|_| true);
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(mock_git),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(MockAgentRegistry::new()),
+ ).unwrap();
+
+ let mut task = make_test_task("t1", "My task", TaskStatus::Review);
+ task.pr_number = None;
+ task.worktree_path = Some("/tmp/wt".to_string());
+
+ let result = app.transition_to_done(&mut task, Path::new("/tmp/test-project"));
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), true);
+ assert!(app.state.done_confirm_popup.is_some());
+ let popup = app.state.done_confirm_popup.as_ref().unwrap();
+ assert!(matches!(popup.pr_state, DoneConfirmPrState::UncommittedChanges));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_transition_to_done_clean_clears_session_and_worktree() {
+ // No PR, no uncommitted changes β†’ spawns cleanup, clears session/worktree, returns Ok(false)
+ let mut mock_tmux = MockTmuxOperations::new();
+ // cleanup_task_resources may call kill_window
+ mock_tmux.expect_kill_window().returning(|_| Ok(()));
+
+ let mut mock_git = MockGitOperations::new();
+ mock_git
+ .expect_has_changes()
+ .returning(|_| false);
+ // cleanup_task_resources may call remove_worktree
+ mock_git.expect_remove_worktree().returning(|_, _| Ok(()));
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(mock_git),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(MockAgentRegistry::new()),
+ ).unwrap();
+
+ let mut task = make_test_task("t1", "My task", TaskStatus::Review);
+ task.pr_number = None;
+ task.session_name = Some("test-project:task-t1".to_string());
+ task.worktree_path = Some("/tmp/wt".to_string());
+
+ let result = app.transition_to_done(&mut task, Path::new("/tmp/test-project"));
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), false); // Ok(false) β†’ continue with db update
+ // Task fields cleared synchronously before background thread
+ assert!(task.session_name.is_none());
+ assert!(task.worktree_path.is_none());
+ // No popup shown
+ assert!(app.state.done_confirm_popup.is_none());
+}
+
+// =============================================================================
+// Tests for apply_session_refresh
+// =============================================================================
+
+/// Build a minimal SessionTaskStatus for tests.
+#[cfg(feature = "test-mocks")]
+fn make_session_task_status(
+ task_id: &str,
+ status: TaskStatus,
+ phase_status: PhaseStatus,
+ was_ready: bool,
+) -> SessionTaskStatus {
+ SessionTaskStatus {
+ task_id: task_id.to_string(),
+ phase_status,
+ content_hash: None,
+ status,
+ worktree_path: None,
+ session_name: None,
+ agent: "claude".to_string(),
+ was_ready,
+ }
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_apply_session_refresh_working_inserts_cache() {
+ // Working status β†’ stored in phase_status_cache as Working
+ let mut app = make_test_app();
+ let result = SessionRefreshResult {
+ statuses: vec![make_session_task_status("t1", TaskStatus::Planning, PhaseStatus::Working, false)],
+ };
+ app.apply_session_refresh(result);
+ let (phase, _) = app.state.phase_status_cache["t1"];
+ assert_eq!(phase, PhaseStatus::Working);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_apply_session_refresh_ready_inserts_cache() {
+ // Ready status β†’ stored as Ready, clears idle hash
+ let mut app = make_test_app();
+ // Pre-populate a content hash so we can verify it gets removed
+ app.state.pane_content_hashes.insert("t1".to_string(), (42, std::time::Instant::now()));
+
+ let result = SessionRefreshResult {
+ statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Ready, false)],
+ };
+ app.apply_session_refresh(result);
+ let (phase, _) = app.state.phase_status_cache["t1"];
+ assert_eq!(phase, PhaseStatus::Ready);
+ // Hash should be cleared on Ready
+ assert!(!app.state.pane_content_hashes.contains_key("t1"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_apply_session_refresh_working_becomes_idle_after_15s() {
+ // Working with same content hash stable for β‰₯15s β†’ promoted to Idle
+ let mut app = make_test_app();
+ let old_instant = std::time::Instant::now() - std::time::Duration::from_secs(20);
+ app.state.pane_content_hashes.insert("t1".to_string(), (99, old_instant));
+
+ let result = SessionRefreshResult {
+ statuses: vec![SessionTaskStatus {
+ task_id: "t1".to_string(),
+ phase_status: PhaseStatus::Working,
+ content_hash: Some(99), // same hash β†’ stable
+ status: TaskStatus::Planning,
+ worktree_path: None,
+ session_name: None,
+ agent: "claude".to_string(),
+ was_ready: false,
+ }],
+ };
+ app.apply_session_refresh(result);
+ let (phase, _) = app.state.phase_status_cache["t1"];
+ assert_eq!(phase, PhaseStatus::Idle);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_apply_session_refresh_working_stays_working_hash_changed() {
+ // Working with changed content hash β†’ still Working (timer resets)
+ let mut app = make_test_app();
+ let old_instant = std::time::Instant::now() - std::time::Duration::from_secs(20);
+ app.state.pane_content_hashes.insert("t1".to_string(), (99, old_instant));
+
+ let result = SessionRefreshResult {
+ statuses: vec![SessionTaskStatus {
+ task_id: "t1".to_string(),
+ phase_status: PhaseStatus::Working,
+ content_hash: Some(100), // different hash β†’ timer resets
+ status: TaskStatus::Planning,
+ worktree_path: None,
+ session_name: None,
+ agent: "claude".to_string(),
+ was_ready: false,
+ }],
+ };
+ app.apply_session_refresh(result);
+ let (phase, _) = app.state.phase_status_cache["t1"];
+ assert_eq!(phase, PhaseStatus::Working); // not promoted to Idle
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_apply_session_refresh_newly_ready_notifies_orchestrator() {
+ // newly_ready (was_ready=false, now Ready) with orchestrator active β†’ writes DB notification
+ 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();
+
+ // Add a task so the notification message can include its title
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("My feature", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.status = TaskStatus::Planning;
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ // Simulate orchestrator active
+ app.state.orchestrator_session = Some("orch-session".to_string());
+
+ let result = SessionRefreshResult {
+ statuses: vec![make_session_task_status("t1", TaskStatus::Planning, PhaseStatus::Ready, false)],
+ };
+ app.apply_session_refresh(result);
+
+ // Notification should have been written to the DB
+ let db = app.state.db.as_ref().unwrap();
+ let notifs = db.peek_notifications().unwrap();
+ assert!(!notifs.is_empty(), "should have created an orchestrator notification");
+ assert!(notifs[0].message.contains("My feature"));
+ assert!(notifs[0].message.contains("planning"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_apply_session_refresh_already_ready_no_notification() {
+ // was_ready=true β†’ not newly ready β†’ no orchestrator notification
+ 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();
+ app.state.orchestrator_session = Some("orch-session".to_string());
+
+ let result = SessionRefreshResult {
+ statuses: vec![make_session_task_status("t1", TaskStatus::Planning, PhaseStatus::Ready, true)],
+ };
+ app.apply_session_refresh(result);
+
+ let db = app.state.db.as_ref().unwrap();
+ let notifs = db.peek_notifications().unwrap();
+ assert!(notifs.is_empty(), "should not notify when was_ready=true");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_apply_session_refresh_multiple_tasks() {
+ // Multiple tasks in a single result batch β€” each gets its own cache entry
+ let mut app = make_test_app();
+ let result = SessionRefreshResult {
+ statuses: vec![
+ make_session_task_status("t1", TaskStatus::Planning, PhaseStatus::Working, false),
+ make_session_task_status("t2", TaskStatus::Running, PhaseStatus::Ready, false),
+ make_session_task_status("t3", TaskStatus::Review, PhaseStatus::Idle, false),
+ ],
+ };
+ app.apply_session_refresh(result);
+ assert_eq!(app.state.phase_status_cache["t1"].0, PhaseStatus::Working);
+ assert_eq!(app.state.phase_status_cache["t2"].0, PhaseStatus::Ready);
+ assert_eq!(app.state.phase_status_cache["t3"].0, PhaseStatus::Idle);
+}
+
+// =============================================================================
+// Tests for popup confirmation handlers
+// =============================================================================
+
+// --- handle_done_confirm_key ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_done_confirm_y_force_moves_to_done() {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_kill_window().returning(|_| Ok(()));
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_remove_worktree().returning(|_, _| Ok(()));
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(mock_git),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(MockAgentRegistry::new()),
+ ).unwrap();
+
+ // Create a task in the DB so force_move_to_done can find it
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("Ship it", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.status = TaskStatus::Review;
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ app.state.done_confirm_popup = Some(DoneConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_number: 0,
+ pr_state: DoneConfirmPrState::UncommittedChanges,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Char('y'), crossterm::event::KeyModifiers::NONE);
+ app.handle_done_confirm_key(key).unwrap();
+
+ assert!(app.state.done_confirm_popup.is_none());
+ // Task should be Done in DB
+ let updated = app.state.db.as_ref().unwrap().get_task("t1").unwrap().unwrap();
+ assert_eq!(updated.status, TaskStatus::Done);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_done_confirm_n_cancels() {
+ let mut app = make_test_app();
+ app.state.done_confirm_popup = Some(DoneConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_number: 0,
+ pr_state: DoneConfirmPrState::UncommittedChanges,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Char('n'), crossterm::event::KeyModifiers::NONE);
+ app.handle_done_confirm_key(key).unwrap();
+
+ assert!(app.state.done_confirm_popup.is_none()); // popup dismissed
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_done_confirm_esc_cancels() {
+ let mut app = make_test_app();
+ app.state.done_confirm_popup = Some(DoneConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_number: 5,
+ pr_state: DoneConfirmPrState::Open,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Esc, crossterm::event::KeyModifiers::NONE);
+ app.handle_done_confirm_key(key).unwrap();
+
+ assert!(app.state.done_confirm_popup.is_none());
+}
+
+// --- handle_move_confirm_key ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_move_confirm_y_clears_popup_and_moves() {
+ // y β†’ clears popup, sets skip_move_confirm, calls move_task_right
+ // We put a Backlog task on the board so move_task_right has something to do
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("My task", "claude", "test-project");
+ task.id = "t1".to_string();
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ app.state.move_confirm_popup = Some(MoveConfirmPopup {
+ task_id: "t1".to_string(),
+ from_status: TaskStatus::Backlog,
+ to_status: TaskStatus::Planning,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Char('y'), crossterm::event::KeyModifiers::NONE);
+ app.handle_move_confirm_key(key).unwrap();
+
+ assert!(app.state.move_confirm_popup.is_none());
+ // skip_move_confirm should be reset to false after the call
+ assert!(!app.state.skip_move_confirm);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_move_confirm_n_only_clears_popup() {
+ let mut app = make_test_app();
+ app.state.move_confirm_popup = Some(MoveConfirmPopup {
+ task_id: "t1".to_string(),
+ from_status: TaskStatus::Planning,
+ to_status: TaskStatus::Running,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Char('n'), crossterm::event::KeyModifiers::NONE);
+ app.handle_move_confirm_key(key).unwrap();
+
+ assert!(app.state.move_confirm_popup.is_none());
+ assert!(!app.state.skip_move_confirm);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_move_confirm_esc_clears_popup() {
+ let mut app = make_test_app();
+ app.state.move_confirm_popup = Some(MoveConfirmPopup {
+ task_id: "t1".to_string(),
+ from_status: TaskStatus::Running,
+ to_status: TaskStatus::Review,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Esc, crossterm::event::KeyModifiers::NONE);
+ app.handle_move_confirm_key(key).unwrap();
+
+ assert!(app.state.move_confirm_popup.is_none());
+}
+
+// --- handle_review_confirm_key ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_review_confirm_y_starts_pr_generation() {
+ // y β†’ calls move_running_to_review_with_pr β†’ opens pr_confirm_popup (generating=true)
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_diff_stat_from_main().returning(|_| String::new());
+
+ let mut mock_registry = MockAgentRegistry::new();
+ let mut mock_agent_ops = MockAgentOperations::new();
+ mock_agent_ops.expect_generate_text().returning(|_, _| Ok(String::new()));
+ let ops_arc: Arc<dyn AgentOperations> = Arc::new(mock_agent_ops);
+ mock_registry.expect_get().returning(move |_| Arc::clone(&ops_arc));
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(MockTmuxOperations::new()),
+ Arc::new(mock_git),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(mock_registry),
+ ).unwrap();
+
+ // Create a Running task in the DB
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("My feature", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.status = TaskStatus::Running;
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ app.state.review_confirm_popup = Some(ReviewConfirmPopup {
+ task_id: "t1".to_string(),
+ task_title: "My feature".to_string(),
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Char('y'), crossterm::event::KeyModifiers::NONE);
+ app.handle_review_confirm_key(key).unwrap();
+
+ assert!(app.state.review_confirm_popup.is_none());
+ // pr_confirm_popup should appear with generating=true
+ assert!(app.state.pr_confirm_popup.is_some());
+ assert!(app.state.pr_confirm_popup.as_ref().unwrap().generating);
+ // Background PR generation thread spawned
+ assert!(app.state.pr_generation_rx.is_some());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_review_confirm_n_moves_without_pr() {
+ // n β†’ moves to Review without creating PR, no pr_confirm_popup
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(MockTmuxOperations::new()),
+ 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 feature", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.status = TaskStatus::Running;
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ app.state.review_confirm_popup = Some(ReviewConfirmPopup {
+ task_id: "t1".to_string(),
+ task_title: "My feature".to_string(),
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Char('n'), crossterm::event::KeyModifiers::NONE);
+ app.handle_review_confirm_key(key).unwrap();
+
+ assert!(app.state.review_confirm_popup.is_none());
+ assert!(app.state.pr_confirm_popup.is_none()); // no PR popup
+ // Task should be in Review now
+ let updated = app.state.db.as_ref().unwrap().get_task("t1").unwrap().unwrap();
+ assert_eq!(updated.status, TaskStatus::Review);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_review_confirm_esc_cancels() {
+ let mut app = make_test_app();
+ app.state.review_confirm_popup = Some(ReviewConfirmPopup {
+ task_id: "t1".to_string(),
+ task_title: "Some task".to_string(),
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Esc, crossterm::event::KeyModifiers::NONE);
+ app.handle_review_confirm_key(key).unwrap();
+
+ assert!(app.state.review_confirm_popup.is_none());
+ assert!(app.state.pr_confirm_popup.is_none());
+}
+
+// --- handle_pr_confirm_key ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_pr_confirm_tab_switches_field() {
+ let mut app = make_test_app();
+ app.state.pr_confirm_popup = Some(PrConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_title: "Title".to_string(),
+ pr_body: "Body".to_string(),
+ editing_title: true,
+ generating: false,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Tab, crossterm::event::KeyModifiers::NONE);
+ app.handle_pr_confirm_key(key).unwrap();
+
+ let popup = app.state.pr_confirm_popup.as_ref().unwrap();
+ assert!(!popup.editing_title, "Tab should switch to body editing");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_pr_confirm_char_appends_to_active_field() {
+ let mut app = make_test_app();
+ // editing_title=true β†’ chars go to title
+ app.state.pr_confirm_popup = Some(PrConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_title: "Ti".to_string(),
+ pr_body: String::new(),
+ editing_title: true,
+ generating: false,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Char('X'), crossterm::event::KeyModifiers::NONE);
+ app.handle_pr_confirm_key(key).unwrap();
+ assert_eq!(app.state.pr_confirm_popup.as_ref().unwrap().pr_title, "TiX");
+
+ // Switch to body
+ let tab = crossterm::event::KeyEvent::new(KeyCode::Tab, crossterm::event::KeyModifiers::NONE);
+ app.handle_pr_confirm_key(tab).unwrap();
+
+ let key2 = crossterm::event::KeyEvent::new(KeyCode::Char('Z'), crossterm::event::KeyModifiers::NONE);
+ app.handle_pr_confirm_key(key2).unwrap();
+ assert_eq!(app.state.pr_confirm_popup.as_ref().unwrap().pr_body, "Z");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_pr_confirm_backspace_removes_char() {
+ let mut app = make_test_app();
+ app.state.pr_confirm_popup = Some(PrConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_title: "ABC".to_string(),
+ pr_body: String::new(),
+ editing_title: true,
+ generating: false,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Backspace, crossterm::event::KeyModifiers::NONE);
+ app.handle_pr_confirm_key(key).unwrap();
+ assert_eq!(app.state.pr_confirm_popup.as_ref().unwrap().pr_title, "AB");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_pr_confirm_enter_in_title_moves_to_body() {
+ let mut app = make_test_app();
+ app.state.pr_confirm_popup = Some(PrConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_title: "Title".to_string(),
+ pr_body: String::new(),
+ editing_title: true,
+ generating: false,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Enter, crossterm::event::KeyModifiers::NONE);
+ app.handle_pr_confirm_key(key).unwrap();
+ assert!(!app.state.pr_confirm_popup.as_ref().unwrap().editing_title);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_pr_confirm_enter_in_body_adds_newline() {
+ let mut app = make_test_app();
+ app.state.pr_confirm_popup = Some(PrConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_title: "Title".to_string(),
+ pr_body: "Line1".to_string(),
+ editing_title: false,
+ generating: false,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Enter, crossterm::event::KeyModifiers::NONE);
+ app.handle_pr_confirm_key(key).unwrap();
+ assert_eq!(app.state.pr_confirm_popup.as_ref().unwrap().pr_body, "Line1\n");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_pr_confirm_esc_closes_popup() {
+ let mut app = make_test_app();
+ app.state.pr_confirm_popup = Some(PrConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_title: "T".to_string(),
+ pr_body: String::new(),
+ editing_title: true,
+ generating: false,
+ });
+
+ let key = crossterm::event::KeyEvent::new(KeyCode::Esc, crossterm::event::KeyModifiers::NONE);
+ app.handle_pr_confirm_key(key).unwrap();
+ assert!(app.state.pr_confirm_popup.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_handle_pr_confirm_ctrl_s_submits_pr() {
+ // Ctrl+s when not generating β†’ closes popup, spawns PR creation thread
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_add_all().returning(|_| Ok(()));
+ mock_git.expect_has_changes().returning(|_| false);
+ mock_git.expect_push().returning(|_, _, _| Ok(()));
+
+ let mut mock_git_provider = MockGitProviderOperations::new();
+ mock_git_provider.expect_create_pr().returning(|_, _, _, _| Ok((1, "https://github.com/pr/1".to_string())));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ let mut mock_agent_ops = MockAgentOperations::new();
+ mock_agent_ops.expect_co_author_string().return_const("Test <[email protected]>".to_string());
+ let ops_arc: Arc<dyn AgentOperations> = Arc::new(mock_agent_ops);
+ mock_registry.expect_get().returning(move |_| Arc::clone(&ops_arc));
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(MockTmuxOperations::new()),
+ Arc::new(mock_git),
+ Arc::new(mock_git_provider),
+ Arc::new(mock_registry),
+ ).unwrap();
+
+ // Create task in DB
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("Feature", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.status = TaskStatus::Running;
+ task.branch_name = Some("feature/t1".to_string());
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ app.state.pr_confirm_popup = Some(PrConfirmPopup {
+ task_id: "t1".to_string(),
+ pr_title: "Add feature".to_string(),
+ pr_body: "Details".to_string(),
+ editing_title: false,
+ generating: false,
+ });
+
+ let key = crossterm::event::KeyEvent::new(
+ KeyCode::Char('s'),
+ crossterm::event::KeyModifiers::CONTROL,
+ );
+ app.handle_pr_confirm_key(key).unwrap();
+
+ // Popup dismissed, pr_creation_rx set
+ assert!(app.state.pr_confirm_popup.is_none());
+ assert!(app.state.pr_status_popup.is_some());
+ assert!(app.state.pr_creation_rx.is_some());
+}
+
+// =============================================================================
+// Tests for process_transition_requests / execute_transition_request
+// =============================================================================
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_process_transition_requests_empty_is_noop() {
+ let mut app = make_test_app();
+ // No pending requests β†’ returns Ok, no panic
+ let result = app.process_transition_requests();
+ assert!(result.is_ok());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_execute_transition_request_unknown_action_errors() {
+ let mut app = make_test_app();
+ let db = app.state.db.as_ref().unwrap();
+
+ let mut task = Task::new("My task", "claude", "test-project");
+ task.id = "t1".to_string();
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ let req = crate::db::TransitionRequest::new("t1", "fly_to_moon");
+ let result = app.execute_transition_request(&req);
+ assert!(result.is_err());
+ assert!(result.unwrap_err().to_string().contains("Unknown action"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_execute_transition_request_move_forward_backlog_to_planning() {
+ // move_forward on a Backlog task β†’ calls transition_to_planning (spawns setup, returns Ok)
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("Plan this", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.plugin = Some("agtx".to_string());
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ let req = crate::db::TransitionRequest::new("t1", "move_forward");
+ let result = app.execute_transition_request(&req);
+ assert!(result.is_ok());
+ // setup_rx should be set (planning setup spawned)
+ assert!(app.state.setup_rx.is_some());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_execute_transition_request_move_to_running_from_wrong_status_errors() {
+ // move_to_running when task is in Review β†’ should error
+ let mut app = make_test_app();
+ 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::Review;
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ let req = crate::db::TransitionRequest::new("t1", "move_to_running");
+ let result = app.execute_transition_request(&req);
+ assert!(result.is_err());
+ assert!(result.unwrap_err().to_string().contains("Backlog or Planning"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_execute_transition_request_move_to_done_from_wrong_status_errors() {
+ let mut app = make_test_app();
+ 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::Planning; // not Review
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ let req = crate::db::TransitionRequest::new("t1", "move_to_done");
+ let result = app.execute_transition_request(&req);
+ assert!(result.is_err());
+ assert!(result.unwrap_err().to_string().contains("Review to move to Done"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_execute_transition_request_resume_wrong_status_errors() {
+ let mut app = make_test_app();
+ 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; // not Review
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ let req = crate::db::TransitionRequest::new("t1", "resume");
+ let result = app.execute_transition_request(&req);
+ assert!(result.is_err());
+ assert!(result.unwrap_err().to_string().contains("Review to resume"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_execute_transition_request_resume_moves_review_to_running() {
+ // "resume" on a Review task β†’ moves to Running
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(MockTmuxOperations::new()),
+ 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("Resume me", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.status = TaskStatus::Review;
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ let req = crate::db::TransitionRequest::new("t1", "resume");
+ app.execute_transition_request(&req).unwrap();
+
+ let updated = app.state.db.as_ref().unwrap().get_task("t1").unwrap().unwrap();
+ assert_eq!(updated.status, TaskStatus::Running);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_execute_transition_request_move_to_done_calls_force_move() {
+ // "move_to_done" on a Review task β†’ force moves it to Done
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_kill_window().returning(|_| Ok(()));
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_remove_worktree().returning(|_, _| Ok(()));
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(mock_git),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(MockAgentRegistry::new()),
+ ).unwrap();
+
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("Done task", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.status = TaskStatus::Review;
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ let req = crate::db::TransitionRequest::new("t1", "move_to_done");
+ app.execute_transition_request(&req).unwrap();
+
+ let updated = app.state.db.as_ref().unwrap().get_task("t1").unwrap().unwrap();
+ assert_eq!(updated.status, TaskStatus::Done);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_process_transition_requests_marks_processed() {
+ // After processing, request should be marked processed in the DB
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_kill_window().returning(|_| Ok(()));
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_remove_worktree().returning(|_, _| Ok(()));
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(mock_git),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(MockAgentRegistry::new()),
+ ).unwrap();
+
+ {
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("Process me", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.status = TaskStatus::Review;
+ db.create_task(&task).unwrap();
+
+ // Queue a transition request
+ let req = crate::db::TransitionRequest::new("t1", "move_to_done");
+ db.create_transition_request(&req).unwrap();
+
+ // Should have 1 pending
+ assert_eq!(db.get_pending_transition_requests().unwrap().len(), 1);
+ }
+
+ app.refresh_tasks().unwrap();
+ app.process_transition_requests().unwrap();
+
+ // Should have 0 pending (request was processed)
+ assert_eq!(app.state.db.as_ref().unwrap().get_pending_transition_requests().unwrap().len(), 0);
+}
+
+// =============================================================================
+// Tests for parse_ansi_to_lines and parse_sgr
+// =============================================================================
+
+#[test]
+fn test_parse_ansi_plain_text() {
+ let input = b"Hello, world!";
+ let lines = parse_ansi_to_lines(input);
+ assert_eq!(lines.len(), 1);
+ assert_eq!(lines[0].spans.len(), 1);
+ assert_eq!(lines[0].spans[0].content, "Hello, world!");
+}
+
+#[test]
+fn test_parse_ansi_empty_input() {
+ let lines = parse_ansi_to_lines(b"");
+ assert!(lines.is_empty());
+}
+
+#[test]
+fn test_parse_ansi_multiline() {
+ let lines = parse_ansi_to_lines(b"line1\nline2\nline3");
+ assert_eq!(lines.len(), 3);
+ assert_eq!(lines[0].spans[0].content, "line1");
+ assert_eq!(lines[1].spans[0].content, "line2");
+ assert_eq!(lines[2].spans[0].content, "line3");
+}
+
+#[test]
+fn test_parse_ansi_empty_line_produces_empty_line_struct() {
+ // A line with only an escape sequence (no text) β†’ empty Line
+ let input = b"\x1b[0m";
+ let lines = parse_ansi_to_lines(input);
+ assert_eq!(lines.len(), 1);
+ // Empty span list renders as blank line
+ assert!(lines[0].spans.is_empty());
+}
+
+#[test]
+fn test_parse_ansi_reset_sequence() {
+ // ESC[0m should reset style
+ let input = b"\x1b[31mred\x1b[0mnormal";
+ let lines = parse_ansi_to_lines(input);
+ assert_eq!(lines.len(), 1);
+ let spans = &lines[0].spans;
+ assert_eq!(spans.len(), 2);
+ assert_eq!(spans[0].content, "red");
+ assert_eq!(spans[0].style.fg, Some(Color::Red));
+ assert_eq!(spans[1].content, "normal");
+ assert_eq!(spans[1].style.fg, None); // reset
+}
+
+#[test]
+fn test_parse_ansi_bold() {
+ let input = b"\x1b[1mbold text\x1b[0m";
+ let lines = parse_ansi_to_lines(input);
+ assert_eq!(lines.len(), 1);
+ assert_eq!(lines[0].spans[0].content, "bold text");
+ assert!(lines[0].spans[0].style.add_modifier.contains(ratatui::style::Modifier::BOLD));
+}
+
+#[test]
+fn test_parse_ansi_foreground_colors() {
+ // Basic 3/4-bit foreground colors
+ let cases: &[(&[u8], Color)] = &[
+ (b"\x1b[31mX", Color::Red),
+ (b"\x1b[32mX", Color::Green),
+ (b"\x1b[33mX", Color::Yellow),
+ (b"\x1b[34mX", Color::Blue),
+ (b"\x1b[35mX", Color::Magenta),
+ (b"\x1b[36mX", Color::Cyan),
+ ];
+ for (input, expected_color) in cases {
+ let lines = parse_ansi_to_lines(input);
+ assert_eq!(lines[0].spans[0].style.fg, Some(*expected_color), "input: {:?}", input);
+ }
+}
+
+#[test]
+fn test_parse_ansi_256_color() {
+ // ESC[38;5;200m β†’ Color::Indexed(200)
+ let input = b"\x1b[38;5;200mcolored";
+ let lines = parse_ansi_to_lines(input);
+ assert_eq!(lines[0].spans[0].style.fg, Some(Color::Indexed(200)));
+}
+
+#[test]
+fn test_parse_ansi_rgb_color() {
+ // ESC[38;2;10;20;30m β†’ Color::Rgb(10,20,30)
+ let input = b"\x1b[38;2;10;20;30mrgb";
+ let lines = parse_ansi_to_lines(input);
+ assert_eq!(lines[0].spans[0].style.fg, Some(Color::Rgb(10, 20, 30)));
+}
+
+#[test]
+fn test_parse_ansi_background_color() {
+ // ESC[42m β†’ bg Green
+ let input = b"\x1b[42mtext";
+ let lines = parse_ansi_to_lines(input);
+ assert_eq!(lines[0].spans[0].style.bg, Some(Color::Green));
+}
+
+#[test]
+fn test_parse_sgr_empty_resets() {
+ // ESC[m with empty sequence β†’ reset
+ let style = ratatui::style::Style::default().fg(Color::Red).bold();
+ let result = parse_sgr("", style);
+ assert_eq!(result, ratatui::style::Style::default());
+}
+
+#[test]
+fn test_parse_sgr_multiple_codes() {
+ // "1;31" β†’ bold + red foreground
+ let style = parse_sgr("1;31", ratatui::style::Style::default());
+ assert_eq!(style.fg, Some(Color::Red));
+ assert!(style.add_modifier.contains(ratatui::style::Modifier::BOLD));
+}
+
+#[test]
+fn test_parse_sgr_256_bg() {
+ // "48;5;100" β†’ bg Indexed(100)
+ let style = parse_sgr("48;5;100", ratatui::style::Style::default());
+ assert_eq!(style.bg, Some(Color::Indexed(100)));
+}
+
+#[test]
+fn test_parse_sgr_rgb_bg() {
+ // "48;2;5;10;15" β†’ bg Rgb(5,10,15)
+ let style = parse_sgr("48;2;5;10;15", ratatui::style::Style::default());
+ assert_eq!(style.bg, Some(Color::Rgb(5, 10, 15)));
+}
+
+#[test]
+fn test_parse_sgr_dim_italic_underline() {
+ let style = parse_sgr("2;3;4", ratatui::style::Style::default());
+ assert!(style.add_modifier.contains(ratatui::style::Modifier::DIM));
+ assert!(style.add_modifier.contains(ratatui::style::Modifier::ITALIC));
+ assert!(style.add_modifier.contains(ratatui::style::Modifier::UNDERLINED));
+}
+
+#[test]
+fn test_parse_sgr_bright_colors() {
+ // 90..97 are bright/dark foreground variants
+ let style = parse_sgr("90", ratatui::style::Style::default());
+ assert_eq!(style.fg, Some(Color::DarkGray));
+ let style = parse_sgr("91", ratatui::style::Style::default());
+ assert_eq!(style.fg, Some(Color::LightRed));
+ let style = parse_sgr("97", ratatui::style::Style::default());
+ assert_eq!(style.fg, Some(Color::White));
+}
+
+#[test]
+fn test_parse_ansi_mixed_text_and_colors() {
+ // "normal \x1b[32mgreen\x1b[0m after"
+ let input = b"normal \x1b[32mgreen\x1b[0m after";
+ let lines = parse_ansi_to_lines(input);
+ assert_eq!(lines.len(), 1);
+ let spans = &lines[0].spans;
+ assert_eq!(spans.len(), 3);
+ assert_eq!(spans[0].content, "normal ");
+ assert_eq!(spans[1].content, "green");
+ assert_eq!(spans[1].style.fg, Some(Color::Green));
+ assert_eq!(spans[2].content, " after");
+ assert_eq!(spans[2].style.fg, None);
+}
+
+// =============================================================================
+// Tests for start_research and move_backlog_to_running_by_id
+// =============================================================================
+
+/// Build a test App with a task already in the DB and board, plus configurable mocks.
+#[cfg(feature = "test-mocks")]
+fn make_app_with_task(task: &Task, mock_tmux: MockTmuxOperations, mock_git: MockGitOperations) -> App {
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(mock_git),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(mock_registry),
+ ).unwrap();
+
+ app.state.db.as_ref().unwrap().create_task(task).unwrap();
+ app.refresh_tasks().unwrap();
+ app
+}
+
+// --- start_research ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_start_research_returns_early_if_setup_in_progress() {
+ let mock_tmux = MockTmuxOperations::new();
+ let task = make_test_task("r1", "Research task", TaskStatus::Backlog);
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+
+ // Pre-set setup_rx to simulate in-progress setup
+ let (_tx, rx) = std::sync::mpsc::channel::<SetupResult>();
+ app.state.setup_rx = Some(rx);
+
+ app.start_research("r1").unwrap();
+
+ // setup_rx should still be set (wasn't cleared or replaced)
+ assert!(app.state.setup_rx.is_some());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_start_research_warns_when_plugin_has_no_research_command() {
+ let mock_tmux = MockTmuxOperations::new();
+ let task = make_test_task("r2", "Research task", TaskStatus::Backlog);
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+ // start_research stamps plugin from config.workflow_plugin β€” set openspec which has no research cmd
+ app.state.config.workflow_plugin = Some("openspec".to_string());
+
+ app.start_research("r2").unwrap();
+
+ assert!(app.state.warning_message.is_some());
+ assert!(app.state.setup_rx.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_start_research_spawns_setup_rx_for_valid_task() {
+ let mock_tmux = MockTmuxOperations::new();
+ let mut task = make_test_task("r3", "Research task", TaskStatus::Backlog);
+ // agtx plugin has a research command
+ task.plugin = Some("agtx".to_string());
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+
+ app.start_research("r3").unwrap();
+
+ // Background thread spawned β†’ setup_rx set
+ assert!(app.state.setup_rx.is_some());
+ assert!(app.state.warning_message.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_start_research_returns_early_for_missing_task() {
+ let mock_tmux = MockTmuxOperations::new();
+ let task = make_test_task("r4", "Research task", TaskStatus::Backlog);
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+
+ // Call with a task ID that doesn't exist in DB
+ app.start_research("nonexistent-id").unwrap();
+
+ assert!(app.state.setup_rx.is_none());
+ assert!(app.state.warning_message.is_none());
+}
+
+// --- move_backlog_to_running_by_id ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_move_backlog_to_running_returns_error_if_setup_in_progress() {
+ let mock_tmux = MockTmuxOperations::new();
+ let task = make_test_task("m1", "Running task", TaskStatus::Backlog);
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+
+ let (_tx, rx) = std::sync::mpsc::channel::<SetupResult>();
+ app.state.setup_rx = Some(rx);
+
+ let result = app.move_backlog_to_running_by_id("m1");
+ assert!(result.is_err());
+ let msg = result.unwrap_err().to_string();
+ assert!(msg.contains("already in progress"), "unexpected: {}", msg);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_move_backlog_to_running_errors_for_non_backlog_task() {
+ let mock_tmux = MockTmuxOperations::new();
+ let task = make_test_task("m2", "Running task", TaskStatus::Planning);
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+
+ let result = app.move_backlog_to_running_by_id("m2");
+ assert!(result.is_err());
+ let msg = result.unwrap_err().to_string();
+ assert!(msg.contains("Backlog"), "unexpected: {}", msg);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_move_backlog_to_running_warns_when_prior_phase_required() {
+ let mock_tmux = MockTmuxOperations::new();
+ let mut task = make_test_task("m3", "Running task", TaskStatus::Backlog);
+ // gsd running phase has no {task} in prompt β†’ requires prior artifact
+ task.plugin = Some("gsd".to_string());
+ task.worktree_path = None; // no prior artifact
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+
+ app.move_backlog_to_running_by_id("m3").unwrap();
+
+ assert!(app.state.warning_message.is_some());
+ assert!(app.state.setup_rx.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_move_backlog_to_running_stamps_plugin_from_config() {
+ let mock_tmux = MockTmuxOperations::new();
+ let mut task = make_test_task("m4", "Running task", TaskStatus::Backlog);
+ // task has no plugin set β€” should be stamped from config
+ task.plugin = None;
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+ // agtx running phase accepts {task} directly β†’ no blocking
+ app.state.config.workflow_plugin = Some("agtx".to_string());
+
+ app.move_backlog_to_running_by_id("m4").unwrap();
+
+ // setup_rx spawned means plugin was stamped and setup started
+ assert!(app.state.setup_rx.is_some());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_move_backlog_to_running_spawns_setup_rx_for_agtx_plugin() {
+ let mock_tmux = MockTmuxOperations::new();
+ let mut task = make_test_task("m5", "Running task", TaskStatus::Backlog);
+ task.plugin = Some("agtx".to_string());
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+
+ app.move_backlog_to_running_by_id("m5").unwrap();
+
+ assert!(app.state.setup_rx.is_some());
+ assert!(app.state.warning_message.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_move_backlog_to_running_returns_ok_for_missing_task() {
+ let mock_tmux = MockTmuxOperations::new();
+ let task = make_test_task("m6", "Running task", TaskStatus::Backlog);
+ let mut app = make_app_with_task(&task, mock_tmux, MockGitOperations::new());
+
+ // Nonexistent task ID β†’ silently returns Ok(())
+ app.move_backlog_to_running_by_id("nonexistent").unwrap();
+
+ assert!(app.state.setup_rx.is_none());
+}
+
+// =============================================================================
+// Tests for check_orchestrator_idle (pure function)
+// =============================================================================
+
+#[test]
+fn test_check_orchestrator_idle_signal_in_changed_content() {
+ // Content changed AND contains [agtx:idle] β†’ Idle
+ let result = check_orchestrator_idle("new content [agtx:idle]", "old content", None);
+ assert!(matches!(result, OrchestratorIdleResult::Idle));
+}
+
+#[test]
+fn test_check_orchestrator_idle_busy_when_content_changed_no_signal() {
+ // Content changed, no idle signal β†’ Busy
+ let result = check_orchestrator_idle("new content", "old content", None);
+ assert!(matches!(result, OrchestratorIdleResult::Busy));
+}
+
+#[test]
+fn test_check_orchestrator_idle_waiting_when_unchanged_no_timer() {
+ // Content unchanged, no stable_since set β†’ Waiting
+ let result = check_orchestrator_idle("same", "same", None);
+ assert!(matches!(result, OrchestratorIdleResult::Waiting));
+}
+
+#[test]
+fn test_check_orchestrator_idle_waiting_when_unchanged_timer_not_elapsed() {
+ // Content unchanged, timer started just now β†’ Waiting
+ let stable_since = Some(Instant::now());
+ let result = check_orchestrator_idle("same", "same", stable_since);
+ assert!(matches!(result, OrchestratorIdleResult::Waiting));
+}
+
+#[test]
+fn test_check_orchestrator_idle_idle_when_stable_for_15s() {
+ // Content unchanged, timer elapsed β‰₯15s β†’ Idle
+ let stable_since = Some(Instant::now() - std::time::Duration::from_secs(20));
+ let result = check_orchestrator_idle("same", "same", stable_since);
+ assert!(matches!(result, OrchestratorIdleResult::Idle));
+}
+
+// =============================================================================
+// Tests for toggle_orchestrator
+// =============================================================================
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_toggle_orchestrator_warns_in_dashboard_mode() {
+ // No project path β†’ sets warning, no session spawned
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
+ mock_tmux.expect_has_session().returning(|_| false);
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ let mut app = App::new_for_test(
+ None, // dashboard mode β€” no project path
+ Arc::new(mock_tmux),
+ Arc::new(MockGitOperations::new()),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(mock_registry),
+ ).unwrap();
+
+ app.toggle_orchestrator().unwrap();
+
+ assert!(app.state.warning_message.is_some());
+ assert!(app.state.orchestrator_session.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_toggle_orchestrator_spawns_new_session() {
+ // No existing orchestrator β†’ creates window, sets orchestrator_session
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
+ mock_tmux.expect_has_session().returning(|_| false);
+ mock_tmux.expect_create_session().returning(|_, _| Ok(()));
+ mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+ mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));
+ mock_tmux.expect_capture_pane_with_history().returning(|_, _| vec![]);
+ mock_tmux.expect_get_cursor_info().returning(|_| None);
+
+ 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());
+ Arc::new(ops)
+ });
+
+ 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(mock_registry),
+ ).unwrap();
+
+ app.toggle_orchestrator().unwrap();
+
+ assert!(app.state.orchestrator_session.is_some());
+ assert!(app.state.warning_message.is_none());
+ // Shell popup should be opened to show the starting orchestrator
+ assert!(app.state.shell_popup.is_some());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_toggle_orchestrator_opens_popup_when_already_running() {
+ // orchestrator_session is set AND window still exists β†’ opens popup, no new spawn
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(true));
+ mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));
+ mock_tmux.expect_capture_pane_with_history().returning(|_, _| vec![]);
+ mock_tmux.expect_get_cursor_info().returning(|_| None);
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ // Simulate already-running orchestrator
+ app.state.orchestrator_session = Some("test-project:orchestrator".to_string());
+
+ app.toggle_orchestrator().unwrap();
+
+ // Should open the popup, not spawn a new session
+ assert!(app.state.shell_popup.is_some());
+ // Session stays the same
+ assert_eq!(
+ app.state.orchestrator_session.as_deref(),
+ Some("test-project:orchestrator")
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_toggle_orchestrator_clears_stale_session_and_respawns() {
+ // orchestrator_session set but window is GONE β†’ clears session, spawns new one
+ let mut mock_tmux = MockTmuxOperations::new();
+ // First call: check existing session β†’ gone
+ // Then: has_session, create_session, create_window, resize, capture for new spawn
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
+ mock_tmux.expect_has_session().returning(|_| false);
+ mock_tmux.expect_create_session().returning(|_, _| Ok(()));
+ mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+ mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));
+ mock_tmux.expect_capture_pane_with_history().returning(|_, _| vec![]);
+ mock_tmux.expect_get_cursor_info().returning(|_| None);
+
+ 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());
+ Arc::new(ops)
+ });
+
+ 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(mock_registry),
+ ).unwrap();
+
+ // Stale session β€” window no longer exists
+ app.state.orchestrator_session = Some("test-project:orchestrator".to_string());
+
+ app.toggle_orchestrator().unwrap();
+
+ // New session should be set (different value possible, but must be Some)
+ assert!(app.state.orchestrator_session.is_some());
+ assert!(app.state.shell_popup.is_some());
+}
+
+// =============================================================================
+// Tests for deliver_orchestrator_notifications
+// =============================================================================
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_deliver_orchestrator_notifications_throttled() {
+ // Called immediately after reset β†’ should return early (< 2s elapsed)
+ let mut mock_tmux = MockTmuxOperations::new();
+ // send_keys must NOT be called β€” any call would panic with mockall
+ mock_tmux.expect_window_exists().returning(|_| Ok(true));
+ mock_tmux.expect_capture_pane().returning(|_| Ok("[agtx:idle]".to_string()));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ app.state.orchestrator_session = Some("proj:orchestrator".to_string());
+ app.state.orchestrator_ready.store(true, Ordering::Release);
+ // last_check was just set in new_for_test β†’ throttled
+ app.state.orchestrator_last_check = Instant::now();
+
+ // Should be a no-op (throttle)
+ app.deliver_orchestrator_notifications();
+ // Nothing sent β€” test passes if no panic from unexpected mock calls
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_deliver_orchestrator_notifications_returns_early_no_session() {
+ // No orchestrator_session β†’ returns immediately
+ let mock_tmux = MockTmuxOperations::new();
+ // window_exists must NOT be called
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ // Expire the throttle
+ app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
+ // No session set
+ app.state.orchestrator_session = None;
+
+ app.deliver_orchestrator_notifications();
+ // No panic = correct
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_deliver_orchestrator_notifications_returns_early_not_ready() {
+ // Session set but orchestrator_ready = false β†’ returns before window check
+ let mock_tmux = MockTmuxOperations::new();
+ // window_exists must NOT be called
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
+ app.state.orchestrator_session = Some("proj:orchestrator".to_string());
+ app.state.orchestrator_ready.store(false, Ordering::Release);
+
+ app.deliver_orchestrator_notifications();
+ // No panic = correct
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_deliver_orchestrator_notifications_busy_when_content_changed() {
+ // Content changed, no idle signal β†’ state updated to Busy (stable_since set), nothing sent
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(true));
+ mock_tmux.expect_capture_pane().returning(|_| Ok("new content here".to_string()));
+ // send_keys must NOT be called
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
+ app.state.orchestrator_session = Some("proj:orchestrator".to_string());
+ app.state.orchestrator_ready.store(true, Ordering::Release);
+ app.state.orchestrator_last_content = "old content".to_string();
+
+ app.deliver_orchestrator_notifications();
+
+ // stable_since should be set (Busy path resets timer)
+ assert!(app.state.orchestrator_stable_since.is_some());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_deliver_orchestrator_notifications_delivers_when_idle_signal() {
+ // Content changed AND has [agtx:idle] β†’ sends combined notification
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(true));
+ mock_tmux.expect_capture_pane().returning(|_| Ok("stuff [agtx:idle]".to_string()));
+ mock_tmux.expect_send_keys()
+ .withf(|_target, msg| msg.starts_with("[agtx]"))
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
+ app.state.orchestrator_session = Some("proj:orchestrator".to_string());
+ app.state.orchestrator_ready.store(true, Ordering::Release);
+ app.state.orchestrator_last_content = "old content".to_string();
+
+ // Insert a notification into the DB
+ {
+ let db = app.state.db.as_ref().unwrap();
+ db.create_notification(&crate::db::Notification::new("task X completed planning")).unwrap();
+ }
+
+ app.deliver_orchestrator_notifications();
+
+ // Notifications should have been consumed (DB now empty)
+ let remaining = app.state.db.as_ref().unwrap().peek_notifications().unwrap();
+ assert!(remaining.is_empty());
+ // Idle tracking reset
+ assert!(app.state.orchestrator_last_content.is_empty());
+ assert!(app.state.orchestrator_stable_since.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_deliver_orchestrator_notifications_delivers_via_stability_fallback() {
+ // Content unchanged, timer β‰₯15s β†’ Idle via fallback, delivers notification
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(true));
+ mock_tmux.expect_capture_pane().returning(|_| Ok("same content".to_string()));
+ mock_tmux.expect_send_keys()
+ .withf(|_target, msg| msg.starts_with("[agtx]"))
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
+ app.state.orchestrator_session = Some("proj:orchestrator".to_string());
+ app.state.orchestrator_ready.store(true, Ordering::Release);
+ // Same content as what capture_pane returns
+ app.state.orchestrator_last_content = "same content".to_string();
+ // Timer has been running for 20s β†’ stability fallback triggers
+ app.state.orchestrator_stable_since = Some(Instant::now() - std::time::Duration::from_secs(20));
+
+ {
+ let db = app.state.db.as_ref().unwrap();
+ db.create_notification(&crate::db::Notification::new("task Y completed running")).unwrap();
+ }
+
+ app.deliver_orchestrator_notifications();
+
+ let remaining = app.state.db.as_ref().unwrap().peek_notifications().unwrap();
+ assert!(remaining.is_empty());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_deliver_orchestrator_notifications_noop_when_no_notifications() {
+ // Idle orchestrator but DB has no notifications β†’ send_keys NOT called
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(true));
+ mock_tmux.expect_capture_pane().returning(|_| Ok("stuff [agtx:idle]".to_string()));
+ // send_keys must NOT be called β€” mockall will panic if it is
+
+ let mut mock_registry = MockAgentRegistry::new();
+ mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+
+ 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(mock_registry),
+ ).unwrap();
+
+ app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
+ app.state.orchestrator_session = Some("proj:orchestrator".to_string());
+ app.state.orchestrator_ready.store(true, Ordering::Release);
+ app.state.orchestrator_last_content = "old content".to_string();
+ // DB has no notifications
+
+ app.deliver_orchestrator_notifications();
+ // No panic = correct (send_keys not called)
+}
+
+
+// =============================================================================
+// Tests for pure functions: fuzzy_score, word_boundary_left/right,
+// generate_task_slug, centered_rect, centered_rect_fixed_width,
+// transform_skill_frontmatter, transform_skill_for_opencode
+// =============================================================================
+
+// --- fuzzy_score ---
+
+#[test]
+fn test_fuzzy_score_empty_needle_returns_one() {
+ assert_eq!(fuzzy_score("anything", ""), 1);
+}
+
+#[test]
+fn test_fuzzy_score_no_match_returns_zero() {
+ assert_eq!(fuzzy_score("hello", "xyz"), 0);
+}
+
+#[test]
+fn test_fuzzy_score_partial_match_returns_zero() {
+ // needle chars not all present
+ assert_eq!(fuzzy_score("abc", "abz"), 0);
+}
+
+#[test]
+fn test_fuzzy_score_all_chars_present_scores_nonzero() {
+ // All needle chars present β†’ score > 0
+ assert!(fuzzy_score("readme", "rdm") > 0);
+ // All chars present in order, exact β†’ highest possible for that length
+ let s = fuzzy_score("readme", "readme");
+ assert!(s > 0);
+}
+
+#[test]
+fn test_fuzzy_score_case_sensitive() {
+ // function is case-sensitive
+ assert_eq!(fuzzy_score("Hello", "hello"), 0);
+ assert!(fuzzy_score("hello", "hello") > 0);
+}
+
+// --- word_boundary_left ---
+
+#[test]
+fn test_word_boundary_left_at_zero() {
+ assert_eq!(word_boundary_left("hello world", 0), 0);
+}
+
+#[test]
+fn test_word_boundary_left_from_end_of_word() {
+ // "hello world" β€” cursor at 5 (end of "hello") β†’ should land at 0
+ assert_eq!(word_boundary_left("hello world", 5), 0);
+}
+
+#[test]
+fn test_word_boundary_left_skips_space_then_word() {
+ // "hello world" cursor at 11 (end) β†’ skip "d l r o w" then space β†’ land at 6
+ assert_eq!(word_boundary_left("hello world", 11), 6);
+}
+
+#[test]
+fn test_word_boundary_left_from_middle_of_word() {
+ // "hello world" cursor at 8 β†’ inside "world" β†’ land at 6
+ assert_eq!(word_boundary_left("hello world", 8), 6);
+}
+
+#[test]
+fn test_word_boundary_left_empty_string() {
+ assert_eq!(word_boundary_left("", 0), 0);
+}
+
+// --- word_boundary_right ---
+
+#[test]
+fn test_word_boundary_right_from_middle_of_word() {
+ // "hello world" cursor at 2 β†’ skip "llo" β†’ skip " " β†’ land at 6
+ assert_eq!(word_boundary_right("hello world", 2), 6);
+}
+
+#[test]
+fn test_word_boundary_right_empty_string() {
+ assert_eq!(word_boundary_right("", 0), 0);
+}
+
+// --- generate_task_slug ---
+
+#[test]
+fn test_generate_task_slug_basic() {
+ let slug = generate_task_slug("abcdefgh-1234-5678", "My Task");
+ assert!(slug.starts_with("abcdefgh-"), "slug={}", slug);
+ assert!(slug.contains("My-Task") || slug.contains("my-task") || slug.contains("My"), "slug={}", slug);
+}
+
+#[test]
+fn test_generate_task_slug_truncates_long_title() {
+ let long_title = "a".repeat(60);
+ let slug = generate_task_slug("id12345678", &long_title);
+ // slug part should be <= 30 chars for the title portion
+ let after_prefix = slug.trim_start_matches("id123456-");
+ assert!(after_prefix.len() <= 30, "slug title part too long: {}", after_prefix);
+}
+
+#[test]
+fn test_generate_task_slug_special_chars_replaced() {
+ let slug = generate_task_slug("id12345678", "Fix: bug #42 (urgent)");
+ // special chars become '-', alphanumeric and '-'/'_' are kept
+ assert!(!slug.contains('#'), "slug={}", slug);
+ assert!(!slug.contains('('), "slug={}", slug);
+ assert!(!slug.contains(':'), "slug={}", slug);
+}
+
+#[test]
+fn test_generate_task_slug_id_prefix_is_8_chars() {
+ let slug = generate_task_slug("abcdefghijklmnop", "title");
+ // First component before "-title" is 8 chars of the id
+ let first_dash = slug.find('-').unwrap();
+ assert_eq!(first_dash, 8, "id prefix should be 8 chars, slug={}", slug);
+}
+
+// --- centered_rect ---
+
+#[test]
+fn test_centered_rect_basic() {
+ use ratatui::layout::Rect;
+ let area = Rect { x: 0, y: 0, width: 100, height: 50 };
+ let popup = centered_rect(60, 40, area);
+ // x should be centered
+ assert_eq!(popup.x, 20); // (100 - 60) / 2
+ assert_eq!(popup.width, 60);
+ assert_eq!(popup.height, 20); // 40% of 50
+}
+
+#[test]
+fn test_centered_rect_full_size() {
+ use ratatui::layout::Rect;
+ let area = Rect { x: 0, y: 0, width: 80, height: 24 };
+ let popup = centered_rect(100, 100, area);
+ assert_eq!(popup.width, 80);
+ assert_eq!(popup.height, 24);
+}
+
+// --- centered_rect_fixed_width ---
+
+#[test]
+fn test_centered_rect_fixed_width_basic() {
+ use ratatui::layout::Rect;
+ let area = Rect { x: 0, y: 0, width: 100, height: 50 };
+ let popup = centered_rect_fixed_width(60, 50, area);
+ assert_eq!(popup.width, 60);
+ // should be centered horizontally
+ assert_eq!(popup.x, 20); // (100 - 60) / 2
+}
+
+#[test]
+fn test_centered_rect_fixed_width_capped_to_terminal() {
+ use ratatui::layout::Rect;
+ // fixed_width wider than terminal β†’ capped at width - 4
+ let area = Rect { x: 0, y: 0, width: 40, height: 24 };
+ let popup = centered_rect_fixed_width(100, 50, area);
+ assert_eq!(popup.width, 36); // 40 - 4
+}
+
+// --- transform_skill_frontmatter ---
+
+#[test]
+fn test_transform_skill_frontmatter_renames_name_field() {
+ let content = "---\nname: agtx-plan\ndescription: Plan a task\n---\nContent here";
+ let result = transform_skill_frontmatter(content);
+ // skill_name_to_command("agtx-plan") β†’ "/agtx:plan"
+ assert!(result.contains("name: agtx:plan"), "result={}", result);
+ assert!(!result.contains("name: agtx-plan"), "result={}", result);
+}
+
+#[test]
+fn test_transform_skill_frontmatter_passthrough_when_no_name() {
+ let content = "---\ndescription: No name field here\n---\nContent";
+ let result = transform_skill_frontmatter(content);
+ assert_eq!(result, content);
+}
+
+#[test]
+fn test_transform_skill_frontmatter_preserves_rest_of_content() {
+ let content = "---\nname: agtx-execute\ndescription: Run it\n---\nBody text here";
+ let result = transform_skill_frontmatter(content);
+ assert!(result.contains("description: Run it"), "result={}", result);
+ assert!(result.contains("Body text here"), "result={}", result);
+}
+
+// --- transform_skill_for_opencode ---
+
+#[test]
+fn test_transform_skill_for_opencode_strips_frontmatter() {
+ let content = "---\nname: agtx-plan\ndescription: Plan the task\n---\nDo the planning work.";
+ let result = transform_skill_for_opencode(content);
+ // Should produce OpenCode format: description frontmatter + body
+ assert!(result.contains("description:"), "result={}", result);
+ assert!(result.contains("Do the planning work."), "result={}", result);
+ // Original name: field should not appear
+ assert!(!result.contains("name: agtx-plan"), "result={}", result);
+}
+
+#[test]
+fn test_transform_skill_for_opencode_uses_description_from_frontmatter() {
+ let content = "---\nname: agtx-plan\ndescription: My custom desc\n---\nBody.";
+ let result = transform_skill_for_opencode(content);
+ assert!(result.contains("My custom desc"), "result={}", result);
+}
+
+// =============================================================================
+// Tests for mock-dependent functions: is_pane_at_shell, is_agent_active,
+// collect_task_diff, cleanup_task_for_done, cleanup_task_resources,
+// delete_task_resources, save_task
+// =============================================================================
+
+// --- is_pane_at_shell ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_is_pane_at_shell_returns_true_for_shell_command() {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string()));
+ assert!(is_pane_at_shell(&mock_tmux, "proj:task"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_is_pane_at_shell_returns_false_when_no_command() {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| None);
+ assert!(!is_pane_at_shell(&mock_tmux, "proj:task"));
+}
+
+// --- is_agent_active ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_is_agent_active_true_when_agent_process_running() {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("claude".to_string()));
+ assert!(is_agent_active(&mock_tmux, "proj:task"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_is_agent_active_true_when_gemini_indicator_in_pane() {
+ // Gemini runs inside bash β€” detected via pane content indicator
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string()));
+ mock_tmux.expect_capture_pane()
+ .returning(|_| Ok("some output\nType your message\n".to_string()));
+ assert!(is_agent_active(&mock_tmux, "proj:task"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_is_agent_active_false_when_at_shell_no_indicator() {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string()));
+ mock_tmux.expect_capture_pane()
+ .returning(|_| Ok("$ ".to_string()));
+ assert!(!is_agent_active(&mock_tmux, "proj:task"));
+}
+
+// --- collect_task_diff ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_collect_task_diff_shows_unstaged_changes() {
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_diff().returning(|_| "diff --git a/foo.rs\n-old\n+new\n".to_string());
+ mock_git.expect_diff_cached().returning(|_| String::new());
+ mock_git.expect_list_untracked_files().returning(|_| String::new());
+
+ let result = collect_task_diff("/tmp/wt", &mock_git, &[]);
+ assert!(result.contains("Unstaged Changes"), "result={}", result);
+ assert!(result.contains("foo.rs"), "result={}", result);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_collect_task_diff_shows_staged_changes() {
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_diff().returning(|_| String::new());
+ mock_git.expect_diff_cached().returning(|_| "diff --git a/bar.rs\n+added\n".to_string());
+ mock_git.expect_list_untracked_files().returning(|_| String::new());
+
+ let result = collect_task_diff("/tmp/wt", &mock_git, &[]);
+ assert!(result.contains("Staged Changes"), "result={}", result);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_collect_task_diff_untracked_excluded_by_prefix() {
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_diff().returning(|_| String::new());
+ mock_git.expect_diff_cached().returning(|_| String::new());
+ mock_git.expect_list_untracked_files()
+ .returning(|_| ".claude/settings.json\nsrc/new_file.rs\n".to_string());
+ // diff_untracked_file only called for non-excluded files
+ mock_git.expect_diff_untracked_file()
+ .withf(|_, file: &str| file == "src/new_file.rs")
+ .returning(|_, _| "+new content\n".to_string());
+
+ let result = collect_task_diff("/tmp/wt", &mock_git, &[".claude"]);
+ assert!(!result.contains("settings.json"), "excluded file appeared: {}", result);
+ assert!(result.contains("new_file.rs") || result.contains("Untracked"), "result={}", result);
+}
+
+// --- cleanup_task_for_done ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_cleanup_task_for_done_clears_session_and_worktree() {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_kill_window()
+ .withf(|name: &str| name == "proj:task-1")
+ .times(1)
+ .returning(|_| Ok(()));
+
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_remove_worktree()
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ let mut task = make_test_task("t1", "My task", TaskStatus::Review);
+ task.session_name = Some("proj:task-1".to_string());
+ task.worktree_path = Some("/tmp/nonexistent-wt".to_string());
+
+ cleanup_task_for_done(&mut task, Path::new("/tmp/proj"), &mock_tmux, &mock_git);
+
+ assert_eq!(task.status, TaskStatus::Done);
+ assert!(task.session_name.is_none());
+ assert!(task.worktree_path.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_cleanup_task_for_done_no_ops_when_no_session_or_worktree() {
+ // No session or worktree β†’ kill_window and remove_worktree must NOT be called
+ let mock_tmux = MockTmuxOperations::new();
+ let mock_git = MockGitOperations::new();
+
+ let mut task = make_test_task("t2", "My task", TaskStatus::Review);
+ task.session_name = None;
+ task.worktree_path = None;
+
+ cleanup_task_for_done(&mut task, Path::new("/tmp/proj"), &mock_tmux, &mock_git);
+
+ assert_eq!(task.status, TaskStatus::Done);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_cleanup_task_for_done_archives_md_files() {
+ use std::io::Write;
+
+ let mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_remove_worktree().returning(|_, _| Ok(()));
+
+ // Create a worktree dir with a .agtx/*.md file
+ let wt = tempfile::tempdir().unwrap();
+ let agtx_dir = wt.path().join(".agtx");
+ std::fs::create_dir_all(&agtx_dir).unwrap();
+ let mut f = std::fs::File::create(agtx_dir.join("plan.md")).unwrap();
+ writeln!(f, "# Plan").unwrap();
+
+ let project_dir = tempfile::tempdir().unwrap();
+
+ let mut task = make_test_task("t3", "Archive task", TaskStatus::Review);
+ task.session_name = None;
+ task.worktree_path = Some(wt.path().to_string_lossy().to_string());
+ task.branch_name = Some("task/my-slug".to_string());
+
+ cleanup_task_for_done(&mut task, project_dir.path(), &mock_tmux, &mock_git);
+
+ // Archived file should exist under .agtx/archive/my-slug/plan.md
+ let archive = project_dir.path().join(".agtx").join("archive").join("my-slug").join("plan.md");
+ assert!(archive.exists(), "archive not created at {:?}", archive);
+}
+
+// --- cleanup_task_resources ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_cleanup_task_resources_kills_window_and_removes_worktree() {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_kill_window()
+ .times(1)
+ .returning(|_| Ok(()));
+
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_remove_worktree()
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ cleanup_task_resources(
+ "task-id",
+ &Some("task/branch".to_string()),
+ &Some("proj:task-win".to_string()),
+ &Some("/tmp/wt".to_string()),
+ Path::new("/tmp/proj"),
+ &mock_tmux,
+ &mock_git,
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_cleanup_task_resources_noop_when_no_session_or_worktree() {
+ let mock_tmux = MockTmuxOperations::new();
+ let mock_git = MockGitOperations::new();
+
+ cleanup_task_resources(
+ "task-id",
+ &None,
+ &None,
+ &None,
+ Path::new("/tmp/proj"),
+ &mock_tmux,
+ &mock_git,
+ );
+ // No panic = correct (no mock calls made)
+}
+
+// --- delete_task_resources ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_delete_task_resources_kills_window_removes_worktree_and_deletes_branch() {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_kill_window()
+ .times(1)
+ .returning(|_| Ok(()));
+
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_remove_worktree()
+ .times(1)
+ .returning(|_, _| Ok(()));
+ mock_git.expect_delete_branch()
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ let mut task = make_test_task("t1", "Delete me", TaskStatus::Planning);
+ task.session_name = Some("proj:task-win".to_string());
+ task.worktree_path = Some("/tmp/wt".to_string());
+ task.branch_name = Some("task/my-task".to_string());
+
+ delete_task_resources(&task, Path::new("/tmp/proj"), &mock_tmux, &mock_git);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_delete_task_resources_noop_when_no_session_or_worktree() {
+ let mock_tmux = MockTmuxOperations::new();
+ let mock_git = MockGitOperations::new();
+
+ let task = make_test_task("t2", "Nothing to clean", TaskStatus::Backlog);
+ // session_name and worktree_path both None β†’ no mock calls
+ delete_task_resources(&task, Path::new("/tmp/proj"), &mock_tmux, &mock_git);
+}
+
+// --- save_task ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_save_task_creates_new_task_in_db() {
+ let mut app = make_test_app();
+
+ // Set up wizard state for a new task
+ app.state.pending_task_title = "New Task Title".to_string();
+ app.state.input_buffer = "Task description here".to_string();
+ app.state.editing_task_id = None;
+ app.state.wizard_plugin_options = vec![
+ crate::tui::app::PluginOption {
+ name: "agtx".to_string(),
+ label: "agtx".to_string(),
+ description: "".to_string(),
+ active: true,
+ }
+ ];
+ app.state.wizard_selected_plugin = 0;
+
+ app.save_task().unwrap();
+
+ let tasks = app.state.db.as_ref().unwrap().get_all_tasks().unwrap();
+ assert_eq!(tasks.len(), 1);
+ let task = &tasks[0];
+ assert_eq!(task.title, "New Task Title");
+ assert_eq!(task.description.as_deref(), Some("Task description here"));
+ assert_eq!(task.plugin.as_deref(), Some("agtx"));
+ assert_eq!(task.status, TaskStatus::Backlog);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_save_task_updates_existing_task() {
+ let mut app = make_test_app();
+
+ // Create a task in the DB first
+ let original = make_test_task("edit-me", "Original Title", TaskStatus::Backlog);
+ app.state.db.as_ref().unwrap().create_task(&original).unwrap();
+ app.refresh_tasks().unwrap();
+
+ // Set up wizard state for editing
+ app.state.pending_task_title = "Updated Title".to_string();
+ app.state.input_buffer = "Updated description".to_string();
+ app.state.editing_task_id = Some("edit-me".to_string());
+ app.state.wizard_plugin_options = vec![
+ crate::tui::app::PluginOption {
+ name: "gsd".to_string(),
+ label: "gsd".to_string(),
+ description: "".to_string(),
+ active: true,
+ }
+ ];
+ app.state.wizard_selected_plugin = 0;
+
+ app.save_task().unwrap();
+
+ let updated = app.state.db.as_ref().unwrap().get_task("edit-me").unwrap().unwrap();
+ assert_eq!(updated.title, "Updated Title");
+ assert_eq!(updated.description.as_deref(), Some("Updated description"));
+ assert_eq!(updated.plugin.as_deref(), Some("gsd"));
+ // Status unchanged
+ assert_eq!(updated.status, TaskStatus::Backlog);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_save_task_empty_description_stored_as_none() {
+ let mut app = make_test_app();
+
+ app.state.pending_task_title = "Title only".to_string();
+ app.state.input_buffer = String::new(); // empty
+ app.state.editing_task_id = None;
+ app.state.wizard_plugin_options = vec![
+ crate::tui::app::PluginOption {
+ name: "agtx".to_string(),
+ label: "agtx".to_string(),
+ description: "".to_string(),
+ active: true,
+ }
+ ];
+ app.state.wizard_selected_plugin = 0;
+
+ app.save_task().unwrap();
+
+ let tasks = app.state.db.as_ref().unwrap().get_all_tasks().unwrap();
+ assert_eq!(tasks[0].description, None);
+}
+
+// --- init_plugin_selection ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_init_plugin_selection_includes_agtx() {
+ let mut app = make_test_app();
+ app.init_plugin_selection();
+ let names: Vec<&str> = app.state.wizard_plugin_options.iter().map(|o| o.name.as_str()).collect();
+ assert!(names.contains(&"agtx"), "options={:?}", names);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_init_plugin_selection_sets_active_from_config() {
+ let mut app = make_test_app();
+ app.state.config.workflow_plugin = Some("gsd".to_string());
+ app.init_plugin_selection();
+
+ let active = app.state.wizard_plugin_options.iter().find(|o| o.active);
+ assert!(active.is_some());
+ assert_eq!(active.unwrap().name, "gsd");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_init_plugin_selection_selected_index_matches_active() {
+ let mut app = make_test_app();
+ app.state.config.workflow_plugin = Some("gsd".to_string());
+ app.init_plugin_selection();
+
+ let idx = app.state.wizard_selected_plugin;
+ assert!(app.state.wizard_plugin_options[idx].active, "selected idx {} not active", idx);
+}
+
+// =============================================================================
+// Tests for switch_agent_in_tmux and wait_for_agent_ready
+// =============================================================================
+
+// --- switch_agent_in_tmux ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_switch_agent_claude_sends_exit_then_new_cmd() {
+ // Claude: sends /exit, shell found immediately, then sends new agent cmd
+ let mut mock_tmux = MockTmuxOperations::new();
+ // /exit sent to current agent
+ mock_tmux.expect_send_keys()
+ .withf(|_, cmd: &str| cmd == "/exit")
+ .times(1)
+ .returning(|_, _| Ok(()));
+ // pane_current_command returns "bash" on first poll β†’ shell found
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string()));
+ // new agent command sent after shell found
+ mock_tmux.expect_send_keys()
+ .withf(|_, cmd: &str| cmd == "claude --dangerously-skip-permissions")
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ switch_agent_in_tmux(&mock_tmux, "proj:task", "claude", "claude --dangerously-skip-permissions");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_switch_agent_codex_sends_ctrl_c_not_exit() {
+ // Codex has no exit command β€” sends C-c instead
+ let mut mock_tmux = MockTmuxOperations::new();
+ // C-c via send_keys_literal (not send_keys)
+ mock_tmux.expect_send_keys_literal()
+ .withf(|_, key: &str| key == "C-c")
+ .times(1)
+ .returning(|_, _| Ok(()));
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string()));
+ mock_tmux.expect_send_keys()
+ .withf(|_, cmd: &str| cmd == "codex --full-auto")
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ switch_agent_in_tmux(&mock_tmux, "proj:task", "codex", "codex --full-auto");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_switch_agent_retries_with_ctrl_c_when_shell_not_found() {
+ // Shell not found on first 30 polls β†’ retry path: sends C-c then /exit again
+ let seq = std::sync::Arc::new(std::sync::Mutex::new(0u32));
+ let seq2 = seq.clone();
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ // Initial /exit
+ mock_tmux.expect_send_keys()
+ .withf(|_, cmd: &str| cmd == "/exit")
+ .returning(|_, _| Ok(()));
+ // pane_current_command: returns "claude" for first 30 polls (shell not found),
+ // then "bash" for the retry polls
+ mock_tmux.expect_pane_current_command()
+ .returning(move |_| {
+ let mut n = seq2.lock().unwrap();
+ *n += 1;
+ if *n <= 30 { Some("claude".to_string()) } else { Some("bash".to_string()) }
+ });
+ // C-c sent on retry
+ mock_tmux.expect_send_keys_literal()
+ .withf(|_, key: &str| key == "C-c")
+ .times(1)
+ .returning(|_, _| Ok(()));
+ // new agent cmd always sent at end
+ mock_tmux.expect_send_keys()
+ .withf(|_, cmd: &str| cmd == "newagent")
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ switch_agent_in_tmux(&mock_tmux, "proj:task", "claude", "newagent");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_switch_agent_sends_ctrl_d_as_last_resort() {
+ // Shell never found β†’ C-d last resort, but new agent cmd still sent
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_send_keys()
+ .withf(|_, cmd: &str| cmd == "/exit")
+ .returning(|_, _| Ok(()));
+ // Always returns agent process β€” shell never found
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("claude".to_string()));
+ // C-c on retry
+ mock_tmux.expect_send_keys_literal()
+ .withf(|_, key: &str| key == "C-c")
+ .times(1)
+ .returning(|_, _| Ok(()));
+ // C-d as last resort
+ mock_tmux.expect_send_keys_literal()
+ .withf(|_, key: &str| key == "C-d")
+ .times(1)
+ .returning(|_, _| Ok(()));
+ // new agent still sent
+ mock_tmux.expect_send_keys()
+ .withf(|_, cmd: &str| cmd == "newagent")
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ switch_agent_in_tmux(&mock_tmux, "proj:task", "claude", "newagent");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_switch_agent_always_sends_new_agent_cmd() {
+ // Even in worst case (shell never found), new agent cmd is sent
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_send_keys()
+ .withf(|_, cmd: &str| cmd == "/exit")
+ .returning(|_, _| Ok(()));
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("claude".to_string()));
+ mock_tmux.expect_send_keys_literal()
+ .returning(|_, _| Ok(()));
+ // This is the key assertion β€” new_agent_cmd must be sent exactly once
+ mock_tmux.expect_send_keys()
+ .withf(|_, cmd: &str| cmd == "my-new-agent")
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ switch_agent_in_tmux(&mock_tmux, "proj:task", "claude", "my-new-agent");
+}
+
+// --- wait_for_agent_ready ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_agent_ready_returns_when_process_detected() {
+ // pane_current_command returns agent process immediately β†’ exits loop on first check
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("claude".to_string())); // not shell β†’ agent detected
+ // capture_pane called for settle, returning no indicator content
+ mock_tmux.expect_capture_pane()
+ .returning(|_| Ok(String::new()));
+
+ let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ assert_eq!(result, Some("proj:task".to_string()));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_agent_ready_returns_when_ready_indicator_in_pane() {
+ // pane_current_command returns shell (bash), but pane content has ready indicator
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string())); // at shell
+ mock_tmux.expect_capture_pane()
+ .returning(|_| Ok("Type your message\n> ".to_string())); // Gemini ready indicator
+
+ let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ assert_eq!(result, Some("proj:task".to_string()));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_agent_ready_handles_claude_bypass_prompt() {
+ // Pane contains "Yes, I accept" β†’ sends "2" + Enter and returns immediately
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string()));
+ mock_tmux.expect_capture_pane()
+ .returning(|_| Ok("Yes, I accept\nSome prompt text".to_string()));
+ // Must send "2" to accept
+ mock_tmux.expect_send_keys_literal()
+ .withf(|_, key: &str| key == "2")
+ .times(1)
+ .returning(|_, _| Ok(()));
+ // Must send Enter to confirm
+ mock_tmux.expect_send_keys_literal()
+ .withf(|_, key: &str| key == "Enter")
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ assert_eq!(result, Some("proj:task".to_string()));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_agent_ready_returns_when_content_stabilizes() {
+ // Content changes 3 times then stays stable for CONTENT_STABLE_THRESHOLD ticks
+ let call_count = std::sync::Arc::new(std::sync::Mutex::new(0u32));
+ let call_count2 = call_count.clone();
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string())); // always at shell
+
+ mock_tmux.expect_capture_pane()
+ .returning(move |_| {
+ let mut n = call_count2.lock().unwrap();
+ *n += 1;
+ // 3 changes (different content), then stable
+ match *n {
+ 1 => Ok("loading 1".to_string()),
+ 2 => Ok("loading 2".to_string()),
+ 3 => Ok("loading 3".to_string()),
+ _ => Ok("stable content".to_string()), // unchanged β†’ stable_ticks increment
+ }
+ });
+
+ let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ assert_eq!(result, Some("proj:task".to_string()));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_agent_ready_always_returns_some() {
+ // Even if loop exhausts (150 iters), always returns Some
+ // Simulate: always at shell, content never changes, change_count stays 0
+ // β†’ stable_ticks never counted β†’ loop runs to completion
+ // We only run a minimal version: content changes 0 times β†’ loop exits at 150
+ // With mocks this is instant.
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string()));
+ mock_tmux.expect_capture_pane()
+ .returning(|_| Ok("same content forever".to_string()));
+
+ // Loop runs all 150 iters with no content change β†’ change_count=0, stable never triggered
+ // Function always returns Some at end regardless.
+ let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ assert_eq!(result, Some("proj:task".to_string()));
+}