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.

🧹🧽 🫧 polish: change all coding agent/tmux/git operations to mockable interfaces (#11)

Fynn FlΓΌgge0b0279f46a26
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4ec1d36..b4e8ec0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -50,7 +50,4 @@ jobs:
run: cargo build --verbose
- name: Run tests
- run: cargo test --verbose
-
- - name: Run tests with mocks
run: cargo test --verbose --features test-mocks
diff --git a/Cargo.toml b/Cargo.toml
index 9f42e11..97fe8b1 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -36,7 +36,8 @@ uuid = { version = "1.16", features = ["v4"] }
[features]
-test-mocks = ["mockall"]
+default = []
+test-mocks = ["dep:mockall"]
[dev-dependencies]
tempfile = "3"
diff --git a/README.md b/README.md
index d25191d..8b4b5e0 100644
--- a/README.md
+++ b/README.md
@@ -191,8 +191,8 @@ See [CLAUDE.md](CLAUDE.md) for development documentation.
# Build
cargo build
-# Run tests
-cargo test
+# Run tests (includes mock-based tests)
+cargo test --features test-mocks
# Build release
cargo build --release
diff --git a/src/agent/mod.rs b/src/agent/mod.rs
index b7c26e6..a652705 100644
--- a/src/agent/mod.rs
+++ b/src/agent/mod.rs
@@ -1,3 +1,10 @@
+mod operations;
+
+pub use operations::{AgentOperations, CodingAgent};
+
+#[cfg(feature = "test-mocks")]
+pub use operations::MockAgentOperations;
+
use serde::{Deserialize, Serialize};
/// Known coding agents that agtx can work with
@@ -7,15 +14,17 @@ pub struct Agent {
pub command: String,
pub args: Vec<String>,
pub description: String,
+ pub co_author: String,
}
impl Agent {
- pub fn new(name: &str, command: &str, description: &str) -> Self {
+ pub fn new(name: &str, command: &str, description: &str, co_author: &str) -> Self {
Self {
name: name.to_string(),
command: command.to_string(),
args: vec![],
description: description.to_string(),
+ co_author: co_author.to_string(),
}
}
@@ -23,17 +32,51 @@ impl Agent {
pub fn is_available(&self) -> bool {
which::which(&self.command).is_ok()
}
+
+ /// Build the shell command to start the agent interactively with a prompt
+ pub fn build_interactive_command(&self, prompt: &str) -> String {
+ // Escape single quotes in prompt for shell
+ let escaped_prompt = prompt.replace('\'', "'\"'\"'");
+
+ match self.name.as_str() {
+ "claude" => {
+ format!("claude --dangerously-skip-permissions '{}'", escaped_prompt)
+ }
+ "aider" => {
+ format!("aider --message '{}'", escaped_prompt)
+ }
+ "codex" => {
+ format!("codex '{}'", escaped_prompt)
+ }
+ "gh-copilot" => {
+ format!("gh copilot suggest '{}'", escaped_prompt)
+ }
+ "opencode" => {
+ format!("opencode '{}'", escaped_prompt)
+ }
+ "cline" => {
+ format!("cline '{}'", escaped_prompt)
+ }
+ "q" => {
+ format!("q chat '{}'", escaped_prompt)
+ }
+ _ => {
+ format!("{} '{}'", self.command, escaped_prompt)
+ }
+ }
+ }
}
/// Get the list of known agents
pub fn known_agents() -> Vec<Agent> {
vec![
- Agent::new("claude", "claude", "Anthropic's Claude Code CLI"),
- Agent::new("aider", "aider", "AI pair programming in your terminal"),
- Agent::new("codex", "codex", "OpenAI's Codex CLI"),
- Agent::new("gh-copilot", "gh", "GitHub Copilot CLI"),
- Agent::new("mentat", "mentat", "Open source coding assistant"),
- Agent::new("q", "q", "Amazon Q Developer CLI"),
+ Agent::new("claude", "claude", "Anthropic's Claude Code CLI", "Claude <[email protected]>"),
+ Agent::new("aider", "aider", "AI pair programming in your terminal", "Aider <[email protected]>"),
+ Agent::new("codex", "codex", "OpenAI's Codex CLI", "Codex <[email protected]>"),
+ Agent::new("gh-copilot", "gh", "GitHub Copilot CLI", "GitHub Copilot <[email protected]>"),
+ Agent::new("opencode", "opencode", "AI-powered coding assistant", "OpenCode <[email protected]>"),
+ Agent::new("cline", "cline", "AI coding assistant for VS Code", "Cline <[email protected]>"),
+ Agent::new("q", "q", "Amazon Q Developer CLI", "Amazon Q <[email protected]>"),
]
}
@@ -52,7 +95,7 @@ pub fn get_agent(name: &str) -> Option<Agent> {
/// Find the default agent (first available from preference order)
pub fn default_agent() -> Option<Agent> {
- let preference_order = ["claude", "aider", "codex", "gh-copilot", "mentat", "q"];
+ let preference_order = ["claude", "aider", "codex", "gh-copilot", "opencode", "cline", "q"];
for name in preference_order {
if let Some(agent) = get_agent(name) {
diff --git a/src/agent/operations.rs b/src/agent/operations.rs
new file mode 100644
index 0000000..c93a600
--- /dev/null
+++ b/src/agent/operations.rs
@@ -0,0 +1,74 @@
+//! Traits for agent operations to enable testing with mocks.
+//!
+//! This module provides a generic interface for interacting with coding agents
+//! like Claude Code, Aider, Codex, etc.
+
+use anyhow::Result;
+use std::path::Path;
+
+#[cfg(feature = "test-mocks")]
+use mockall::automock;
+
+use super::Agent;
+
+/// Operations for coding agents (Claude, Aider, Codex, etc.)
+#[cfg_attr(feature = "test-mocks", automock)]
+pub trait AgentOperations: Send + Sync {
+ /// Generate text using the agent's print/non-interactive mode
+ /// Used for tasks like generating PR descriptions
+ fn generate_text(&self, working_dir: &Path, prompt: &str) -> Result<String>;
+
+ /// Get the co-author string for git commits
+ /// e.g., "Claude <[email protected]>"
+ fn co_author_string(&self) -> &str;
+}
+
+/// Generic agent implementation that works with any Agent config
+pub struct CodingAgent {
+ agent: Agent,
+}
+
+impl CodingAgent {
+ pub fn new(agent: Agent) -> Self {
+ Self { agent }
+ }
+
+ /// Create a CodingAgent for the default available agent
+ pub fn default() -> Self {
+ let agent = super::default_agent()
+ .unwrap_or_else(|| super::get_agent("claude").unwrap());
+ Self::new(agent)
+ }
+}
+
+impl AgentOperations for CodingAgent {
+ fn generate_text(&self, working_dir: &Path, prompt: &str) -> Result<String> {
+ // Build the command based on agent type
+ let (cmd, args) = match self.agent.name.as_str() {
+ "claude" => ("claude", vec!["--print", prompt]),
+ "aider" => ("aider", vec!["--message", prompt, "--no-auto-commits"]),
+ "codex" => ("codex", vec!["--print", prompt]),
+ "gh-copilot" => ("gh", vec!["copilot", "explain", prompt]),
+ "opencode" => ("opencode", vec!["--print", prompt]),
+ "cline" => ("cline", vec!["--print", prompt]),
+ "q" => ("q", vec!["chat", "--no-interactive", prompt]),
+ _ => (self.agent.command.as_str(), vec![prompt]),
+ };
+
+ let output = std::process::Command::new(cmd)
+ .current_dir(working_dir)
+ .args(&args)
+ .output()?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("{} command failed: {}", self.agent.name, stderr);
+ }
+
+ Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
+ }
+
+ fn co_author_string(&self) -> &str {
+ &self.agent.co_author
+ }
+}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 91ea143..19f716e 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -1,7 +1,16 @@
+mod operations;
+mod provider;
mod worktree;
+pub use operations::*;
+pub use provider::{GitProviderOperations, PullRequestState, RealGitHubOps};
pub use worktree::*;
+#[cfg(feature = "test-mocks")]
+pub use operations::MockGitOperations;
+#[cfg(feature = "test-mocks")]
+pub use provider::MockGitProviderOperations;
+
use anyhow::{Context, Result};
use std::path::Path;
use std::process::Command;
diff --git a/src/git/operations.rs b/src/git/operations.rs
new file mode 100644
index 0000000..171c0e6
--- /dev/null
+++ b/src/git/operations.rs
@@ -0,0 +1,215 @@
+//! Traits for git operations to enable testing with mocks.
+
+use anyhow::Result;
+use std::path::Path;
+
+#[cfg(feature = "test-mocks")]
+use mockall::automock;
+
+/// Operations for git worktree management
+#[cfg_attr(feature = "test-mocks", automock)]
+pub trait GitOperations: Send + Sync {
+ /// Create a worktree for a task
+ fn create_worktree(&self, project_path: &Path, task_slug: &str) -> Result<String>;
+
+ /// Remove a worktree
+ fn remove_worktree(&self, project_path: &Path, worktree_path: &str) -> Result<()>;
+
+ /// Check if worktree exists
+ fn worktree_exists(&self, project_path: &Path, task_slug: &str) -> bool;
+
+ /// Delete a branch
+ fn delete_branch(&self, project_path: &Path, branch_name: &str) -> Result<()>;
+
+ /// Get unstaged diff
+ fn diff(&self, worktree_path: &Path) -> String;
+
+ /// Get staged diff
+ fn diff_cached(&self, worktree_path: &Path) -> String;
+
+ /// List untracked files
+ fn list_untracked_files(&self, worktree_path: &Path) -> String;
+
+ /// Get diff for untracked file (comparing to /dev/null)
+ fn diff_untracked_file(&self, worktree_path: &Path, file: &str) -> String;
+
+ /// Get diff stats from main branch
+ fn diff_stat_from_main(&self, worktree_path: &Path) -> String;
+
+ /// Stage all changes
+ fn add_all(&self, worktree_path: &Path) -> Result<()>;
+
+ /// Check if there are uncommitted changes (returns true if there are changes)
+ fn has_changes(&self, worktree_path: &Path) -> bool;
+
+ /// Commit with message
+ fn commit(&self, worktree_path: &Path, message: &str) -> Result<()>;
+
+ /// Push branch to origin
+ fn push(&self, worktree_path: &Path, branch: &str, set_upstream: bool) -> Result<()>;
+
+ /// List all files (tracked + untracked, respects .gitignore)
+ fn list_files(&self, project_path: &Path) -> Vec<String>;
+
+ /// Initialize a worktree by copying files and running init script
+ /// Returns a list of warning messages for any issues encountered
+ fn initialize_worktree(
+ &self,
+ project_path: &Path,
+ worktree_path: &Path,
+ copy_files: Option<String>,
+ init_script: Option<String>,
+ ) -> Vec<String>;
+}
+
+/// Real implementation using actual git commands
+pub struct RealGitOps;
+
+impl GitOperations for RealGitOps {
+ fn create_worktree(&self, project_path: &Path, task_slug: &str) -> Result<String> {
+ let path = super::create_worktree(project_path, task_slug)?;
+ Ok(path.to_string_lossy().to_string())
+ }
+
+ fn remove_worktree(&self, project_path: &Path, worktree_path: &str) -> Result<()> {
+ std::process::Command::new("git")
+ .current_dir(project_path)
+ .args(["worktree", "remove", "--force", worktree_path])
+ .output()?;
+ Ok(())
+ }
+
+ fn worktree_exists(&self, project_path: &Path, task_slug: &str) -> bool {
+ super::worktree_exists(project_path, task_slug)
+ }
+
+ fn delete_branch(&self, project_path: &Path, branch_name: &str) -> Result<()> {
+ std::process::Command::new("git")
+ .current_dir(project_path)
+ .args(["branch", "-D", branch_name])
+ .output()?;
+ Ok(())
+ }
+
+ fn diff(&self, worktree_path: &Path) -> String {
+ std::process::Command::new("git")
+ .current_dir(worktree_path)
+ .args(["diff"])
+ .output()
+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
+ .unwrap_or_default()
+ }
+
+ fn diff_cached(&self, worktree_path: &Path) -> String {
+ std::process::Command::new("git")
+ .current_dir(worktree_path)
+ .args(["diff", "--cached"])
+ .output()
+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
+ .unwrap_or_default()
+ }
+
+ fn list_untracked_files(&self, worktree_path: &Path) -> String {
+ std::process::Command::new("git")
+ .current_dir(worktree_path)
+ .args(["ls-files", "--others", "--exclude-standard"])
+ .output()
+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
+ .unwrap_or_default()
+ }
+
+ fn diff_untracked_file(&self, worktree_path: &Path, file: &str) -> String {
+ std::process::Command::new("git")
+ .current_dir(worktree_path)
+ .args(["diff", "--no-index", "/dev/null", file])
+ .output()
+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
+ .unwrap_or_default()
+ }
+
+ fn diff_stat_from_main(&self, worktree_path: &Path) -> String {
+ std::process::Command::new("git")
+ .current_dir(worktree_path)
+ .args(["diff", "main", "--stat"])
+ .output()
+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
+ .unwrap_or_default()
+ }
+
+ fn add_all(&self, worktree_path: &Path) -> Result<()> {
+ std::process::Command::new("git")
+ .current_dir(worktree_path)
+ .args(["add", "-A"])
+ .output()?;
+ Ok(())
+ }
+
+ fn has_changes(&self, worktree_path: &Path) -> bool {
+ std::process::Command::new("git")
+ .current_dir(worktree_path)
+ .args(["status", "--porcelain"])
+ .output()
+ .map(|o| !o.stdout.is_empty())
+ .unwrap_or(false)
+ }
+
+ fn commit(&self, worktree_path: &Path, message: &str) -> Result<()> {
+ let output = std::process::Command::new("git")
+ .current_dir(worktree_path)
+ .args(["commit", "-m", message])
+ .output()?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ // Only fail if it's not "nothing to commit"
+ if !stderr.contains("nothing to commit") {
+ anyhow::bail!("Failed to commit changes: {}", stderr);
+ }
+ }
+ Ok(())
+ }
+
+ fn push(&self, worktree_path: &Path, branch: &str, set_upstream: bool) -> Result<()> {
+ let mut args = vec!["push"];
+ if set_upstream {
+ args.push("-u");
+ }
+ args.push("origin");
+ args.push(branch);
+
+ let output = std::process::Command::new("git")
+ .current_dir(worktree_path)
+ .args(&args)
+ .output()?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("Failed to push branch: {}", stderr);
+ }
+ Ok(())
+ }
+
+ fn list_files(&self, project_path: &Path) -> Vec<String> {
+ std::process::Command::new("git")
+ .current_dir(project_path)
+ .args(["ls-files", "--cached", "--others", "--exclude-standard"])
+ .output()
+ .map(|o| {
+ String::from_utf8_lossy(&o.stdout)
+ .lines()
+ .map(String::from)
+ .collect()
+ })
+ .unwrap_or_default()
+ }
+
+ fn initialize_worktree(
+ &self,
+ project_path: &Path,
+ worktree_path: &Path,
+ copy_files: Option<String>,
+ init_script: Option<String>,
+ ) -> Vec<String> {
+ super::initialize_worktree(project_path, worktree_path, copy_files.as_deref(), init_script.as_deref())
+ }
+}
diff --git a/src/git/provider.rs b/src/git/provider.rs
new file mode 100644
index 0000000..062d273
--- /dev/null
+++ b/src/git/provider.rs
@@ -0,0 +1,97 @@
+//! Traits for git provider operations to enable testing with mocks.
+//!
+//! This module provides a generic interface for interacting with git hosting
+//! providers like GitHub, GitLab, Bitbucket, etc.
+
+use anyhow::Result;
+use std::path::Path;
+
+#[cfg(feature = "test-mocks")]
+use mockall::automock;
+
+/// State of a pull/merge request
+#[derive(Debug, Clone, PartialEq)]
+pub enum PullRequestState {
+ Open,
+ Merged,
+ Closed,
+ Unknown,
+}
+
+/// Operations for git hosting providers (GitHub, GitLab, etc.)
+#[cfg_attr(feature = "test-mocks", automock)]
+pub trait GitProviderOperations: Send + Sync {
+ /// Get the state of a pull/merge request
+ fn get_pr_state(&self, project_path: &Path, pr_number: i32) -> Result<PullRequestState>;
+
+ /// Create a pull/merge request
+ /// Returns (pr_number, pr_url)
+ fn create_pr(
+ &self,
+ project_path: &Path,
+ title: &str,
+ body: &str,
+ head_branch: &str,
+ ) -> Result<(i32, String)>;
+}
+
+/// GitHub implementation using the `gh` CLI
+pub struct RealGitHubOps;
+
+impl GitProviderOperations for RealGitHubOps {
+ fn get_pr_state(&self, project_path: &Path, pr_number: i32) -> Result<PullRequestState> {
+ let output = std::process::Command::new("gh")
+ .current_dir(project_path)
+ .args(["pr", "view", &pr_number.to_string(), "--json", "state"])
+ .output()?;
+
+ if !output.status.success() {
+ return Ok(PullRequestState::Unknown);
+ }
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ if stdout.contains("MERGED") {
+ Ok(PullRequestState::Merged)
+ } else if stdout.contains("CLOSED") {
+ Ok(PullRequestState::Closed)
+ } else if stdout.contains("OPEN") {
+ Ok(PullRequestState::Open)
+ } else {
+ Ok(PullRequestState::Unknown)
+ }
+ }
+
+ fn create_pr(
+ &self,
+ project_path: &Path,
+ title: &str,
+ body: &str,
+ head_branch: &str,
+ ) -> Result<(i32, String)> {
+ let output = std::process::Command::new("gh")
+ .current_dir(project_path)
+ .args([
+ "pr", "create",
+ "--title", title,
+ "--body", body,
+ "--head", head_branch,
+ ])
+ .output()?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("Failed to create PR: {}", stderr);
+ }
+
+ let pr_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
+
+ // Extract PR number from URL (e.g., https://github.com/owner/repo/pull/123)
+ let pr_number = pr_url
+ .split('/')
+ .last()
+ .and_then(|s| s.parse::<i32>().ok())
+ .unwrap_or(0);
+
+ Ok((pr_number, pr_url))
+ }
+}
diff --git a/src/git/worktree.rs b/src/git/worktree.rs
index d5a6fd5..9e064d7 100644
--- a/src/git/worktree.rs
+++ b/src/git/worktree.rs
@@ -196,50 +196,6 @@ pub fn remove_worktree(project_path: &Path, task_id: &str) -> Result<()> {
Ok(())
}
-/// List all worktrees for a project
-pub fn list_worktrees(project_path: &Path) -> Result<Vec<WorktreeInfo>> {
- let output = Command::new("git")
- .current_dir(project_path)
- .args(["worktree", "list", "--porcelain"])
- .output()
- .context("Failed to list git worktrees")?;
-
- let stdout = String::from_utf8_lossy(&output.stdout);
- let mut worktrees = Vec::new();
- let mut current: Option<WorktreeInfo> = None;
-
- for line in stdout.lines() {
- if line.starts_with("worktree ") {
- if let Some(wt) = current.take() {
- worktrees.push(wt);
- }
- current = Some(WorktreeInfo {
- path: PathBuf::from(line.strip_prefix("worktree ").unwrap()),
- branch: None,
- is_bare: false,
- });
- } else if line.starts_with("branch ") {
- if let Some(ref mut wt) = current {
- wt.branch = Some(
- line.strip_prefix("branch refs/heads/")
- .unwrap_or(line.strip_prefix("branch ").unwrap())
- .to_string(),
- );
- }
- } else if line == "bare" {
- if let Some(ref mut wt) = current {
- wt.is_bare = true;
- }
- }
- }
-
- if let Some(wt) = current {
- worktrees.push(wt);
- }
-
- Ok(worktrees)
-}
-
/// Get the worktree path for a task
pub fn worktree_path(project_path: &Path, task_id: &str) -> PathBuf {
project_path
@@ -252,27 +208,3 @@ pub fn worktree_path(project_path: &Path, task_id: &str) -> PathBuf {
pub fn worktree_exists(project_path: &Path, task_id: &str) -> bool {
worktree_path(project_path, task_id).exists()
}
-
-/// Information about a git worktree
-#[derive(Debug, Clone)]
-pub struct WorktreeInfo {
- pub path: PathBuf,
- pub branch: Option<String>,
- pub is_bare: bool,
-}
-
-impl WorktreeInfo {
- /// Extract task ID from worktree path if it's an agtx worktree
- pub fn task_id(&self) -> Option<&str> {
- self.path
- .file_name()
- .and_then(|n| n.to_str())
- .filter(|_| {
- self.path
- .parent()
- .and_then(|p| p.file_name())
- .map(|n| n == WORKTREES_DIR)
- .unwrap_or(false)
- })
- }
-}
diff --git a/src/lib.rs b/src/lib.rs
index c24860b..7c880b7 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -2,7 +2,6 @@ pub mod agent;
pub mod config;
pub mod db;
pub mod git;
-pub mod operations;
pub mod tmux;
pub mod tui;
diff --git a/src/operations.rs b/src/operations.rs
deleted file mode 100644
index 23cbd52..0000000
--- a/src/operations.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-//! Traits for external operations (tmux, git) to enable testing with mocks.
-
-use anyhow::Result;
-use std::path::Path;
-
-#[cfg(any(test, feature = "test-mocks"))]
-use mockall::automock;
-
-/// Operations for tmux window management
-#[cfg_attr(any(test, feature = "test-mocks"), automock)]
-pub trait TmuxOperations {
- /// Create a new tmux window in a session
- fn create_window(&self, session: &str, window_name: &str, working_dir: &str) -> Result<()>;
-
- /// Kill a tmux window
- fn kill_window(&self, target: &str) -> Result<()>;
-
- /// Check if a window exists
- fn window_exists(&self, target: &str) -> Result<bool>;
-
- /// Send keys to a window
- fn send_keys(&self, target: &str, keys: &str) -> Result<()>;
-
- /// Capture pane content
- fn capture_pane(&self, target: &str) -> Result<String>;
-
- /// Resize a tmux window
- fn resize_window(&self, target: &str, width: u16, height: u16) -> Result<()>;
-}
-
-/// Operations for git worktree management
-#[cfg_attr(any(test, feature = "test-mocks"), automock)]
-pub trait GitOperations {
- /// Create a worktree for a task
- fn create_worktree(&self, project_path: &Path, task_slug: &str) -> Result<String>;
-
- /// Remove a worktree
- fn remove_worktree(&self, project_path: &Path, worktree_path: &str) -> Result<()>;
-
- /// Check if worktree exists
- fn worktree_exists(&self, project_path: &Path, task_slug: &str) -> bool;
-}
-
-/// Real implementation using actual tmux commands
-pub struct RealTmuxOps;
-
-impl TmuxOperations for RealTmuxOps {
- fn create_window(&self, session: &str, window_name: &str, working_dir: &str) -> Result<()> {
- let output = std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["new-window", "-d", "-t", session, "-n", window_name])
- .args(["-c", working_dir])
- .output()?;
-
- if !output.status.success() {
- anyhow::bail!("Failed to create tmux window");
- }
- Ok(())
- }
-
- fn kill_window(&self, target: &str) -> Result<()> {
- std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["kill-window", "-t", target])
- .output()?;
- Ok(())
- }
-
- fn window_exists(&self, target: &str) -> Result<bool> {
- let output = std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["list-windows", "-t", target])
- .output()?;
- Ok(output.status.success())
- }
-
- fn send_keys(&self, target: &str, keys: &str) -> Result<()> {
- std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["send-keys", "-t", target, keys, "Enter"])
- .output()?;
- Ok(())
- }
-
- fn capture_pane(&self, target: &str) -> Result<String> {
- let output = std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["capture-pane", "-t", target, "-p"])
- .output()?;
- Ok(String::from_utf8_lossy(&output.stdout).to_string())
- }
-
- fn resize_window(&self, target: &str, width: u16, height: u16) -> Result<()> {
- std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["resize-window", "-t", target])
- .args(["-x", &width.to_string()])
- .args(["-y", &height.to_string()])
- .output()?;
- Ok(())
- }
-}
-
-/// Real implementation using actual git commands
-pub struct RealGitOps;
-
-impl GitOperations for RealGitOps {
- fn create_worktree(&self, project_path: &Path, task_slug: &str) -> Result<String> {
- let path = crate::git::create_worktree(project_path, task_slug)?;
- Ok(path.to_string_lossy().to_string())
- }
-
- fn remove_worktree(&self, project_path: &Path, worktree_path: &str) -> Result<()> {
- std::process::Command::new("git")
- .current_dir(project_path)
- .args(["worktree", "remove", "--force", worktree_path])
- .output()?;
- Ok(())
- }
-
- fn worktree_exists(&self, project_path: &Path, task_slug: &str) -> bool {
- crate::git::worktree_exists(project_path, task_slug)
- }
-}
diff --git a/src/tmux/mod.rs b/src/tmux/mod.rs
index 275fd58..1d2e968 100644
--- a/src/tmux/mod.rs
+++ b/src/tmux/mod.rs
@@ -1,3 +1,10 @@
+mod operations;
+
+pub use operations::*;
+
+#[cfg(feature = "test-mocks")]
+pub use operations::MockTmuxOperations;
+
use anyhow::{Context, Result};
use std::process::Command;
diff --git a/src/tmux/operations.rs b/src/tmux/operations.rs
new file mode 100644
index 0000000..4e14683
--- /dev/null
+++ b/src/tmux/operations.rs
@@ -0,0 +1,181 @@
+//! Traits for tmux operations to enable testing with mocks.
+
+use anyhow::Result;
+
+#[cfg(feature = "test-mocks")]
+use mockall::automock;
+
+/// Operations for tmux window management
+#[cfg_attr(feature = "test-mocks", automock)]
+pub trait TmuxOperations: Send + Sync {
+ /// Create a new tmux window in a session with an optional command to run
+ fn create_window(
+ &self,
+ session: &str,
+ window_name: &str,
+ working_dir: &str,
+ command: Option<String>,
+ ) -> Result<()>;
+
+ /// Kill a tmux window
+ fn kill_window(&self, target: &str) -> Result<()>;
+
+ /// Check if a window exists
+ fn window_exists(&self, target: &str) -> Result<bool>;
+
+ /// Send keys to a window (with Enter at the end)
+ fn send_keys(&self, target: &str, keys: &str) -> Result<()>;
+
+ /// Send keys to a window without pressing Enter
+ fn send_keys_literal(&self, target: &str, keys: &str) -> Result<()>;
+
+ /// Capture pane content
+ fn capture_pane(&self, target: &str) -> Result<String>;
+
+ /// Capture pane content with history (returns raw bytes for ANSI parsing)
+ fn capture_pane_with_history(&self, target: &str, history_lines: i32) -> Vec<u8>;
+
+ /// Get cursor position and pane height: (cursor_y, pane_height)
+ fn get_cursor_info(&self, target: &str) -> Option<(usize, usize)>;
+
+ /// Resize a tmux window
+ fn resize_window(&self, target: &str, width: u16, height: u16) -> Result<()>;
+
+ /// Check if a session exists
+ fn has_session(&self, session: &str) -> bool;
+
+ /// Create a new detached session
+ fn create_session(&self, session: &str, working_dir: &str) -> Result<()>;
+}
+
+/// Real implementation using actual tmux commands
+pub struct RealTmuxOps;
+
+impl TmuxOperations for RealTmuxOps {
+ fn create_window(
+ &self,
+ session: &str,
+ window_name: &str,
+ working_dir: &str,
+ command: Option<String>,
+ ) -> Result<()> {
+ let mut cmd = std::process::Command::new("tmux");
+ cmd.args(["-L", super::AGENT_SERVER])
+ .args(["new-window", "-d", "-t", session, "-n", window_name])
+ .args(["-c", working_dir]);
+
+ if let Some(ref shell_cmd) = command {
+ cmd.args(["sh", "-c", shell_cmd]);
+ }
+
+ let output = cmd.output()?;
+
+ if !output.status.success() {
+ anyhow::bail!("Failed to create tmux window");
+ }
+ Ok(())
+ }
+
+ fn kill_window(&self, target: &str) -> Result<()> {
+ std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["kill-window", "-t", target])
+ .output()?;
+ Ok(())
+ }
+
+ fn window_exists(&self, target: &str) -> Result<bool> {
+ let output = std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["list-windows", "-t", target])
+ .output()?;
+ Ok(output.status.success())
+ }
+
+ fn send_keys(&self, target: &str, keys: &str) -> Result<()> {
+ // Send the text first
+ std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["send-keys", "-t", target, keys])
+ .output()?;
+ // Send Enter separately (like the original implementation)
+ std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["send-keys", "-t", target, "Enter"])
+ .output()?;
+ Ok(())
+ }
+
+ fn send_keys_literal(&self, target: &str, keys: &str) -> Result<()> {
+ std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["send-keys", "-t", target, keys])
+ .output()?;
+ Ok(())
+ }
+
+ fn capture_pane(&self, target: &str) -> Result<String> {
+ let output = std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["capture-pane", "-t", target, "-p"])
+ .output()?;
+ Ok(String::from_utf8_lossy(&output.stdout).to_string())
+ }
+
+ fn capture_pane_with_history(&self, target: &str, history_lines: i32) -> Vec<u8> {
+ std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["capture-pane", "-t", target, "-p", "-e", "-J"])
+ .args(["-S", &format!("-{}", history_lines)])
+ .output()
+ .map(|o| o.stdout)
+ .unwrap_or_default()
+ }
+
+ fn get_cursor_info(&self, target: &str) -> Option<(usize, usize)> {
+ let output = std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["display", "-p", "-t", target, "#{cursor_y} #{pane_height}"])
+ .output()
+ .ok()?;
+
+ if output.status.success() {
+ let output_str = String::from_utf8_lossy(&output.stdout);
+ let parts: Vec<&str> = output_str.trim().split_whitespace().collect();
+ if parts.len() == 2 {
+ let cursor_y: usize = parts[0].parse().ok()?;
+ let pane_height: usize = parts[1].parse().ok()?;
+ return Some((cursor_y, pane_height));
+ }
+ }
+ None
+ }
+
+ fn resize_window(&self, target: &str, width: u16, height: u16) -> Result<()> {
+ std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["resize-window", "-t", target])
+ .args(["-x", &width.to_string()])
+ .args(["-y", &height.to_string()])
+ .output()?;
+ Ok(())
+ }
+
+ fn has_session(&self, session: &str) -> bool {
+ std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["has-session", "-t", session])
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+ }
+
+ fn create_session(&self, session: &str, working_dir: &str) -> Result<()> {
+ std::process::Command::new("tmux")
+ .args(["-L", super::AGENT_SERVER])
+ .args(["new-session", "-d", "-s", session])
+ .args(["-c", working_dir])
+ .output()?;
+ Ok(())
+ }
+}
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 4e8e814..d697166 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -7,14 +7,13 @@ use crossterm::{
use ratatui::{prelude::*, widgets::*};
use std::io::{self, Stdout};
use std::path::{Path, PathBuf};
-use std::sync::mpsc;
+use std::sync::{mpsc, Arc};
-use crate::agent;
+use crate::agent::{self, AgentOperations, CodingAgent};
use crate::config::{GlobalConfig, MergedConfig, ProjectConfig, ThemeConfig};
use crate::db::{Database, Task, TaskStatus};
-use crate::git;
-use crate::operations::{RealTmuxOps, TmuxOperations};
-use crate::tmux;
+use crate::git::{self, GitOperations, GitProviderOperations, PullRequestState, RealGitHubOps, RealGitOps};
+use crate::tmux::{self, RealTmuxOps, TmuxOperations};
use crate::AppMode;
use super::board::BoardState;
@@ -53,6 +52,14 @@ struct AppState {
project_path: Option<PathBuf>,
project_name: String,
available_agents: Vec<agent::Agent>,
+ // Tmux operations (injectable for testing)
+ tmux_ops: Arc<dyn TmuxOperations>,
+ // Git operations (injectable for testing)
+ git_ops: Arc<dyn git::GitOperations>,
+ // Git provider operations (injectable for testing)
+ git_provider_ops: Arc<dyn GitProviderOperations>,
+ // Agent operations (injectable for testing)
+ agent_ops: Arc<dyn AgentOperations>,
// Sidebar
sidebar_visible: bool,
sidebar_focused: bool,
@@ -141,7 +148,7 @@ struct PrConfirmPopup {
pr_title: String,
pr_body: String,
editing_title: bool, // true = editing title, false = editing body
- generating: bool, // true while Claude is generating description
+ generating: bool, // true while agent is generating description
}
/// Info about a project for the sidebar
@@ -181,6 +188,22 @@ pub struct App {
impl App {
pub fn new(mode: AppMode) -> Result<Self> {
+ Self::with_ops(
+ mode,
+ Arc::new(RealTmuxOps),
+ Arc::new(RealGitOps),
+ Arc::new(RealGitHubOps),
+ Arc::new(CodingAgent::default()),
+ )
+ }
+
+ pub fn with_ops(
+ mode: AppMode,
+ tmux_ops: Arc<dyn TmuxOperations>,
+ git_ops: Arc<dyn GitOperations>,
+ git_provider_ops: Arc<dyn GitProviderOperations>,
+ agent_ops: Arc<dyn AgentOperations>,
+ ) -> Result<Self> {
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
@@ -213,7 +236,7 @@ impl App {
global_db.upsert_project(&project)?;
// Ensure tmux session exists for this project
- ensure_project_tmux_session(&name, &canonical);
+ ensure_project_tmux_session(&name, &canonical, tmux_ops.as_ref());
(Some(db), Some(canonical), name, project_config)
}
@@ -238,6 +261,10 @@ impl App {
project_path,
project_name: project_name.clone(),
available_agents,
+ tmux_ops,
+ git_ops,
+ git_provider_ops,
+ agent_ops,
sidebar_visible: true,
sidebar_focused: false,
projects: vec![],
@@ -316,7 +343,7 @@ impl App {
// Refresh shell popup content periodically (every poll cycle when open)
if let Some(ref mut popup) = self.state.shell_popup {
- popup.cached_content = capture_tmux_pane_with_history(&popup.window_name, 500);
+ popup.cached_content = capture_tmux_pane_with_history(&popup.window_name, 500, self.state.tmux_ops.as_ref());
}
// Periodically refresh session status
@@ -705,7 +732,8 @@ impl App {
.as_millis() / 100) as usize % spinner_chars.len();
let spinner = spinner_chars[spinner_idx];
- let loading_text = format!("{} Generating PR description with Claude...", spinner);
+ let agent_name = agent::default_agent().map(|a| a.name).unwrap_or_else(|| "agent".to_string());
+ let loading_text = format!("{} Generating PR description with {}...", spinner, agent_name);
let loading = Paragraph::new(loading_text)
.style(Style::default().fg(Color::Cyan))
.alignment(ratatui::layout::Alignment::Center);
@@ -1333,25 +1361,12 @@ impl App {
fn force_move_to_done(&mut self, task_id: &str) -> Result<()> {
if let (Some(db), Some(project_path)) = (&self.state.db, self.state.project_path.clone()) {
if let Some(mut task) = db.get_task(task_id)? {
- // Cleanup resources
- if let Some(session_name) = &task.session_name {
- let _ = std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["kill-window", "-t", session_name])
- .output();
- }
- if let Some(worktree) = &task.worktree_path {
- let _ = std::process::Command::new("git")
- .current_dir(&project_path)
- .args(["worktree", "remove", "--force", worktree])
- .output();
- }
- // Keep the branch so task can be reopened later
-
- task.session_name = None;
- task.worktree_path = None;
- task.status = TaskStatus::Done;
- task.updated_at = chrono::Utc::now();
+ cleanup_task_for_done(
+ &mut task,
+ &project_path,
+ self.state.tmux_ops.as_ref(),
+ self.state.git_ops.as_ref(),
+ );
db.update_task(&task)?;
self.refresh_tasks()?;
}
@@ -1380,11 +1395,15 @@ impl App {
let title_for_thread = task_title.clone();
let worktree_for_thread = worktree_path.clone();
+ let git_ops = Arc::clone(&self.state.git_ops);
+ let agent_ops = Arc::clone(&self.state.agent_ops);
std::thread::spawn(move || {
let (pr_title, pr_body) = generate_pr_description(
&title_for_thread,
worktree_for_thread.as_deref(),
None,
+ git_ops.as_ref(),
+ agent_ops.as_ref(),
);
let _ = tx.send((pr_title, pr_body));
});
@@ -1473,6 +1492,9 @@ impl App {
let project_path_clone = project_path.clone();
let pr_title_clone = pr_title.to_string();
let pr_body_clone = pr_body.to_string();
+ let git_ops = Arc::clone(&self.state.git_ops);
+ let git_provider_ops = Arc::clone(&self.state.git_provider_ops);
+ let agent_ops = Arc::clone(&self.state.agent_ops);
// Create channel for result
let (tx, rx) = mpsc::channel();
@@ -1480,7 +1502,15 @@ impl App {
// Spawn background thread to create PR
std::thread::spawn(move || {
- let result = create_pr_with_content(&task_clone, &project_path_clone, &pr_title_clone, &pr_body_clone);
+ let result = create_pr_with_content(
+ &task_clone,
+ &project_path_clone,
+ &pr_title_clone,
+ &pr_body_clone,
+ git_ops.as_ref(),
+ git_provider_ops.as_ref(),
+ agent_ops.as_ref(),
+ );
match result {
Ok((pr_number, pr_url)) => {
// Update task in database from background thread
@@ -1671,9 +1701,9 @@ impl App {
}
_ => {
// Forward all other keys to tmux window (including Esc)
- send_key_to_tmux(&window_name, key.code);
+ send_key_to_tmux(&window_name, key.code, self.state.tmux_ops.as_ref());
// After sending a key, refresh content to show the result
- popup.cached_content = capture_tmux_pane_with_history(&window_name, 500);
+ popup.cached_content = capture_tmux_pane_with_history(&window_name, 500, self.state.tmux_ops.as_ref());
}
}
}
@@ -2042,7 +2072,7 @@ impl App {
fn update_file_search_matches(&mut self) {
if let (Some(ref mut search), Some(ref project_path)) = (&mut self.state.file_search, &self.state.project_path) {
let pattern = &search.pattern;
- search.matches = fuzzy_find_files(project_path, pattern, 10);
+ search.matches = fuzzy_find_files(project_path, pattern, 10, self.state.git_ops.as_ref());
search.selected = 0;
}
}
@@ -2090,32 +2120,14 @@ impl App {
}
fn perform_delete_task(&mut self, task_id: &str) -> Result<()> {
- if let Some(db) = &self.state.db {
+ if let (Some(db), Some(project_path)) = (&self.state.db, &self.state.project_path) {
if let Some(task) = db.get_task(task_id)? {
- // Kill tmux window if exists (not the whole session)
- if let Some(ref session_name) = task.session_name {
- let _ = std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["kill-window", "-t", session_name])
- .output();
- }
-
- // Remove worktree if exists
- if let (Some(ref _worktree_path), Some(ref project_path)) = (&task.worktree_path, &self.state.project_path) {
- // Extract slug from branch_name (format: "task/{slug}")
- if let Some(ref branch_name) = task.branch_name {
- let slug = branch_name.strip_prefix("task/").unwrap_or(branch_name);
- let _ = git::remove_worktree(project_path, slug);
-
- // Also try to delete the branch
- let _ = std::process::Command::new("git")
- .current_dir(project_path)
- .args(["branch", "-D", branch_name])
- .output();
- }
- }
-
- // Delete from database
+ delete_task_resources(
+ &task,
+ project_path,
+ self.state.tmux_ops.as_ref(),
+ self.state.git_ops.as_ref(),
+ );
db.delete_task(&task.id)?;
self.refresh_tasks()?;
}
@@ -2126,69 +2138,7 @@ impl App {
fn show_task_diff(&mut self) -> Result<()> {
if let Some(task) = self.state.board.selected_task() {
let diff_content = if let Some(worktree_path) = &task.worktree_path {
- let mut sections = Vec::new();
-
- // Unstaged changes (modified tracked files)
- let unstaged = std::process::Command::new("git")
- .current_dir(worktree_path)
- .args(["diff"])
- .output()
- .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
- .unwrap_or_default();
-
- if !unstaged.trim().is_empty() {
- sections.push(format!("=== Unstaged Changes ===\n\n{}", unstaged));
- }
-
- // Staged changes
- let staged = std::process::Command::new("git")
- .current_dir(worktree_path)
- .args(["diff", "--cached"])
- .output()
- .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
- .unwrap_or_default();
-
- if !staged.trim().is_empty() {
- sections.push(format!("=== Staged Changes ===\n\n{}", staged));
- }
-
- // Untracked files - show as diff (new file content)
- let untracked = std::process::Command::new("git")
- .current_dir(worktree_path)
- .args(["ls-files", "--others", "--exclude-standard"])
- .output()
- .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
- .unwrap_or_default();
-
- if !untracked.trim().is_empty() {
- let mut untracked_section = String::from("=== Untracked Files ===\n");
- for file in untracked.lines() {
- if file.trim().is_empty() {
- continue;
- }
- // Show diff for untracked file (as if adding new file)
- let file_diff = std::process::Command::new("git")
- .current_dir(worktree_path)
- .args(["diff", "--no-index", "/dev/null", file])
- .output()
- .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
- .unwrap_or_default();
-
- if !file_diff.trim().is_empty() {
- untracked_section.push_str(&format!("\n{}", file_diff));
- } else {
- // Fallback: just show file name
- untracked_section.push_str(&format!("\n+++ new file: {}\n", file));
- }
- }
- sections.push(untracked_section);
- }
-
- if sections.is_empty() {
- format!("(no changes)\n\nWorktree: {}", worktree_path)
- } else {
- sections.join("\n\n")
- }
+ collect_task_diff(worktree_path, self.state.git_ops.as_ref())
} else {
"(task has no worktree yet)".to_string()
};
@@ -2224,45 +2174,36 @@ impl App {
if let Some(new_status) = next_status {
// Create worktree and tmux window when moving from Backlog to Planning
if current_status == TaskStatus::Backlog && new_status == TaskStatus::Planning {
- // Sanitize title for worktree/window name
- let title_slug: String = task.title
- .chars()
- .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '-' })
- .take(30)
- .collect();
- let title_slug = title_slug.trim_matches('-').to_string();
-
- // Add task ID prefix to ensure uniqueness (safe slice)
- let id_prefix: String = task.id.chars().take(8).collect();
- let unique_slug = format!("{}-{}", id_prefix, title_slug);
+ let unique_slug = generate_task_slug(&task.id, &task.title);
let window_name = format!("task-{}", unique_slug);
let target = format!("{}:{}", self.state.project_name, window_name);
// Create git worktree from main branch
- let worktree_path = match git::create_worktree(&project_path, &unique_slug) {
+ let worktree_path_str = match self.state.git_ops.create_worktree(&project_path, &unique_slug) {
Ok(path) => path,
Err(e) => {
// Log error but don't crash - worktree might already exist
eprintln!("Failed to create worktree: {}", e);
// Try to use existing worktree path
project_path.join(".agtx").join("worktrees").join(&unique_slug)
+ .to_string_lossy().to_string()
}
};
- let worktree_path_str = worktree_path.to_string_lossy().to_string();
// Initialize worktree: copy files and run init script
- let init_warnings = git::initialize_worktree(
+ let worktree_path = Path::new(&worktree_path_str);
+ let init_warnings = self.state.git_ops.initialize_worktree(
&project_path,
- &worktree_path,
- self.state.config.copy_files.as_deref(),
- self.state.config.init_script.as_deref(),
+ worktree_path,
+ self.state.config.copy_files.clone(),
+ self.state.config.init_script.clone(),
);
for warning in &init_warnings {
eprintln!("Worktree init: {}", warning);
}
// Build the prompt from task title and description
- // Instruct Claude to plan first and wait for approval
+ // Instruct agent to plan first and wait for approval
let task_content = if let Some(desc) = &task.description {
format!("{}\n\n{}", task.title, desc)
} else {
@@ -2275,71 +2216,50 @@ impl App {
task_content
);
- // Escape single quotes in prompt for shell
- let escaped_prompt = prompt.replace('\'', "'\"'\"'");
-
- // Create tmux window and start Claude Code
- let claude_cmd = format!("claude --dangerously-skip-permissions '{}'", escaped_prompt);
+ // Get the default agent and build the interactive command
+ let agent = agent::default_agent().unwrap_or_else(|| agent::get_agent("claude").unwrap());
+ let agent_cmd = agent.build_interactive_command(&prompt);
// Ensure project tmux session exists
- ensure_project_tmux_session(&self.state.project_name, &project_path);
+ ensure_project_tmux_session(&self.state.project_name, &project_path, self.state.tmux_ops.as_ref());
- std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["new-window", "-d", "-t", &self.state.project_name, "-n", &window_name])
- .args(["-c", &worktree_path_str])
- .args(["sh", "-c", &claude_cmd])
- .output()?;
+ self.state.tmux_ops.create_window(
+ &self.state.project_name,
+ &window_name,
+ &worktree_path_str,
+ Some(agent_cmd),
+ )?;
- // Wait for Claude to show the bypass warning prompt, then accept it and rename session
+ // Wait for agent to show the bypass warning prompt, then accept it and rename session
// Poll until we see "Yes, I accept" option or timeout after 5 seconds
let target_clone = target.clone();
let task_id_clone = task.id.clone();
+ let tmux_ops = Arc::clone(&self.state.tmux_ops);
std::thread::spawn(move || {
let mut accepted = false;
for _ in 0..50 {
std::thread::sleep(std::time::Duration::from_millis(100));
// Check pane content for the bypass prompt
- let output = std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["capture-pane", "-t", &target_clone, "-p"])
- .output();
-
- if let Ok(output) = output {
- let content = String::from_utf8_lossy(&output.stdout);
+ if let Ok(content) = tmux_ops.capture_pane(&target_clone) {
// Look for the bypass warning prompt options
if content.contains("Yes, I accept") || content.contains("I accept the risk") {
// Found the prompt, send "2" and Enter
- let _ = std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["send-keys", "-t", &target_clone, "2"])
- .output();
+ let _ = tmux_ops.send_keys_literal(&target_clone, "2");
std::thread::sleep(std::time::Duration::from_millis(50));
- let _ = std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["send-keys", "-t", &target_clone, "Enter"])
- .output();
+ let _ = tmux_ops.send_keys_literal(&target_clone, "Enter");
accepted = true;
break;
}
}
}
- // After accepting, wait for Claude to be ready and rename the session
+ // After accepting, wait for agent to be ready and rename the session
if accepted {
std::thread::sleep(std::time::Duration::from_millis(1000));
// Send /rename command to name the session with task ID for later resume
let rename_cmd = format!("/rename {}", task_id_clone);
- let _ = std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["send-keys", "-t", &target_clone, &rename_cmd])
- .output();
- std::thread::sleep(std::time::Duration::from_millis(50));
- let _ = std::process::Command::new("tmux")
- .args(["-L", crate::tmux::AGENT_SERVER])
- .args(["send-keys", "-t", &target_clone, "Enter"])
- .output();
+ let _ = tmux_ops.send_keys(&target_clone, &rename_cmd);
}
});
@@ -2348,19 +2268,11 @@ impl App {
task.branch_name = Some(format!("task/{}", unique_slug));
}
- // When moving from Planning to Running, tell Claude to start implementing
+ // When moving from Planning to Running, tell agent to start implementing
if current_status == TaskStatus::Planning && new_status == TaskStatus::Running {
if let Some(session_name) = &task.session_name {
- // Send message to start implementation
- std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["send-keys", "-t", session_name, "Looks good, please proceed with the implementation."])
- .output()?;
- // Send Enter separately
- std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["send-keys", "-t", session_name, "Enter"])
- .output()?;
+ // Send message to start implementation (send_keys adds Enter at the end)
+ let _ = self.state.tmux_ops.send_keys(session_name, "Looks good, please proceed with the implementation.");
}
}
@@ -2377,12 +2289,14 @@ impl App {
let task_clone = task.clone();
let project_path_clone = project_path.clone();
+ let git_ops = Arc::clone(&self.state.git_ops);
+ let agent_ops = Arc::clone(&self.state.agent_ops);
let (tx, rx) = mpsc::channel();
self.state.pr_creation_rx = Some(rx);
std::thread::spawn(move || {
- let result = push_changes_to_existing_pr(&task_clone, &project_path_clone);
+ let result = push_changes_to_existing_pr(&task_clone, git_ops.as_ref(), agent_ops.as_ref());
match result {
Ok(pr_url) => {
// Update task in database
@@ -2417,13 +2331,13 @@ impl App {
// When moving from Review to Done: Show confirmation with PR state
if current_status == TaskStatus::Review && new_status == TaskStatus::Done {
if let Some(pr_number) = task.pr_number {
- let pr_state = get_pr_state(pr_number, &project_path)?;
+ let pr_state = self.state.git_provider_ops.get_pr_state(&project_path, pr_number)?;
let confirm_state = match pr_state {
- PrState::Merged => DoneConfirmPrState::Merged,
- PrState::Closed => DoneConfirmPrState::Closed,
- PrState::Open => DoneConfirmPrState::Open,
- PrState::Unknown => DoneConfirmPrState::Unknown,
+ PullRequestState::Merged => DoneConfirmPrState::Merged,
+ PullRequestState::Closed => DoneConfirmPrState::Closed,
+ PullRequestState::Open => DoneConfirmPrState::Open,
+ PullRequestState::Unknown => DoneConfirmPrState::Unknown,
};
self.state.done_confirm_popup = Some(DoneConfirmPopup {
@@ -2434,22 +2348,13 @@ impl App {
return Ok(());
}
// No PR - allow moving to Done directly (task might have been abandoned early)
- // Cleanup any resources that might exist
- if let Some(session_name) = &task.session_name {
- let _ = std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["kill-window", "-t", session_name])
- .output();
- }
- if let Some(worktree) = &task.worktree_path {
- let _ = std::process::Command::new("git")
- .current_dir(&project_path)
- .args(["worktree", "remove", "--force", worktree])
- .output();
- }
- // Keep the branch so task can be reopened later
- task.session_name = None;
- task.worktree_path = None;
+ // Cleanup resources (but don't set status yet - that's done below)
+ cleanup_task_for_done(
+ &mut task,
+ &project_path,
+ self.state.tmux_ops.as_ref(),
+ self.state.git_ops.as_ref(),
+ );
}
task.status = new_status;
@@ -2497,12 +2402,12 @@ impl App {
// TODO the resize should be done on target which is
// session_name:window_name, but for some reason that doesn't work
// doing tmux -L agtx resize-window -t session:window -x 30 -y 30 works
- let _ = RealTmuxOps.resize_window(&window_name, pane_width, pane_height);
+ let _ = self.state.tmux_ops.resize_window(&window_name, pane_width, pane_height);
popup.last_pane_size = Some((pane_width, pane_height));
}
// Capture initial content
- popup.cached_content = capture_tmux_pane_with_history(window_name, 500);
+ popup.cached_content = capture_tmux_pane_with_history(window_name, 500, self.state.tmux_ops.as_ref());
self.state.shell_popup = Some(popup);
}
@@ -2584,7 +2489,7 @@ impl App {
let _ = self.state.global_db.upsert_project(&proj);
// Ensure tmux session exists
- ensure_project_tmux_session(&project.name, &project_path);
+ ensure_project_tmux_session(&project.name, &project_path, self.state.tmux_ops.as_ref());
// Reload tasks for new project
self.refresh_tasks()?;
@@ -2601,22 +2506,111 @@ impl Drop for App {
}
/// Ensure tmux session exists for a project
-fn ensure_project_tmux_session(project_name: &str, project_path: &Path) {
- // Check if session already exists
- let session_exists = std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["has-session", "-t", project_name])
- .output()
- .map(|o| o.status.success())
- .unwrap_or(false);
-
- if !session_exists {
- // Create detached session for this project
- let _ = std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["new-session", "-d", "-s", project_name])
- .args(["-c", &project_path.to_string_lossy().to_string()])
- .output();
+fn ensure_project_tmux_session(project_name: &str, project_path: &Path, tmux_ops: &dyn TmuxOperations) {
+ if !tmux_ops.has_session(project_name) {
+ let _ = tmux_ops.create_session(project_name, &project_path.to_string_lossy());
+ }
+}
+
+/// Generate a URL-safe slug from task ID and title
+fn generate_task_slug(task_id: &str, title: &str) -> String {
+ let title_slug: String = title
+ .chars()
+ .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '-' })
+ .take(30)
+ .collect();
+ let title_slug = title_slug.trim_matches('-').to_string();
+
+ // Add task ID prefix to ensure uniqueness
+ let id_prefix: String = task_id.chars().take(8).collect();
+ format!("{}-{}", id_prefix, title_slug)
+}
+
+/// Cleanup task resources (tmux window, git worktree) and mark as done
+/// Modifies the task in place, ready for database update
+fn cleanup_task_for_done(
+ task: &mut Task,
+ project_path: &Path,
+ tmux_ops: &dyn TmuxOperations,
+ git_ops: &dyn GitOperations,
+) {
+ if let Some(session_name) = &task.session_name {
+ let _ = tmux_ops.kill_window(session_name);
+ }
+ if let Some(worktree) = &task.worktree_path {
+ let _ = git_ops.remove_worktree(project_path, worktree);
+ }
+ // Keep the branch so task can be reopened later
+ task.session_name = None;
+ task.worktree_path = None;
+ task.status = TaskStatus::Done;
+ task.updated_at = chrono::Utc::now();
+}
+
+/// Delete task resources: kill tmux window, remove worktree, delete branch
+fn delete_task_resources(
+ task: &Task,
+ project_path: &Path,
+ tmux_ops: &dyn TmuxOperations,
+ git_ops: &dyn GitOperations,
+) {
+ // Kill tmux window if exists
+ if let Some(ref session_name) = task.session_name {
+ let _ = tmux_ops.kill_window(session_name);
+ }
+
+ // Remove worktree and delete branch if exists
+ if task.worktree_path.is_some() {
+ if let Some(ref branch_name) = task.branch_name {
+ let slug = branch_name.strip_prefix("task/").unwrap_or(branch_name);
+ let _ = git_ops.remove_worktree(project_path, slug);
+ let _ = git_ops.delete_branch(project_path, branch_name);
+ }
+ }
+}
+
+/// Collect git diff content from a worktree
+/// Returns formatted diff sections (unstaged, staged, untracked)
+fn collect_task_diff(worktree_path: &str, git_ops: &dyn GitOperations) -> String {
+ let worktree = Path::new(worktree_path);
+ let mut sections = Vec::new();
+
+ // Unstaged changes (modified tracked files)
+ let unstaged = git_ops.diff(worktree);
+ if !unstaged.trim().is_empty() {
+ sections.push(format!("=== Unstaged Changes ===\n\n{}", unstaged));
+ }
+
+ // Staged changes
+ let staged = git_ops.diff_cached(worktree);
+ if !staged.trim().is_empty() {
+ sections.push(format!("=== Staged Changes ===\n\n{}", staged));
+ }
+
+ // Untracked files - show as diff (new file content)
+ let untracked = git_ops.list_untracked_files(worktree);
+ if !untracked.trim().is_empty() {
+ let mut untracked_section = String::from("=== Untracked Files ===\n");
+ for file in untracked.lines() {
+ if file.trim().is_empty() {
+ continue;
+ }
+ // Show diff for untracked file (as if adding new file)
+ let file_diff = git_ops.diff_untracked_file(worktree, file);
+ if !file_diff.trim().is_empty() {
+ untracked_section.push_str(&format!("\n{}", file_diff));
+ } else {
+ // Fallback: just show file name
+ untracked_section.push_str(&format!("\n+++ new file: {}\n", file));
+ }
+ }
+ sections.push(untracked_section);
+ }
+
+ if sections.is_empty() {
+ format!("(no changes)\n\nWorktree: {}", worktree_path)
+ } else {
+ sections.join("\n\n")
}
}
@@ -2666,133 +2660,51 @@ fn centered_rect_fixed_width(fixed_width: u16, percent_y: u16, r: Rect) -> Rect
}
}
-/// Capture content from a tmux pane (with ANSI escape sequences)
-fn capture_tmux_pane(window_name: &str) -> Vec<u8> {
- std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["capture-pane", "-t", window_name, "-p", "-e"])
- .output()
- .map(|o| o.stdout)
- .unwrap_or_default()
-}
-
/// Capture content from a tmux pane with history (with ANSI escape sequences)
-fn capture_tmux_pane_with_history(window_name: &str, history_lines: i32) -> Vec<u8> {
- // Capture visible pane content plus history
- // -p: print to stdout
- // -e: include escape sequences (colors)
- // -S: start line (negative = history)
- // -J: join wrapped lines (helps with varying pane widths)
- let content = std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["capture-pane", "-t", window_name, "-p", "-e", "-J"])
- .args(["-S", &format!("-{}", history_lines)])
- .output()
- .map(|o| o.stdout)
- .unwrap_or_default();
+fn capture_tmux_pane_with_history(window_name: &str, history_lines: i32, tmux_ops: &dyn TmuxOperations) -> Vec<u8> {
+ let content = tmux_ops.capture_pane_with_history(window_name, history_lines);
// Get the cursor position and pane height to know where the "real" content ends
// Lines below the cursor are unused pane buffer space
- let cursor_info = get_tmux_cursor_info(window_name);
+ let cursor_info = tmux_ops.get_cursor_info(window_name);
// Trim content to only include lines up to cursor position
shell_popup::trim_content_to_cursor(content, cursor_info)
}
-/// Get cursor Y position and pane height from tmux
-/// Returns (cursor_y, pane_height) - both 0-indexed
-fn get_tmux_cursor_info(window_name: &str) -> Option<(usize, usize)> {
- // Get both values in a single tmux call for efficiency
- let output = std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["display", "-p", "-t", window_name, "#{cursor_y} #{pane_height}"])
- .output()
- .ok()?;
-
- if output.status.success() {
- let output_str = String::from_utf8_lossy(&output.stdout);
- let parts: Vec<&str> = output_str.trim().split_whitespace().collect();
- if parts.len() == 2 {
- let cursor_y: usize = parts[0].parse().ok()?;
- let pane_height: usize = parts[1].parse().ok()?;
- return Some((cursor_y, pane_height));
- }
- }
- None
-}
-
-/// Check if a PR is merged
-/// PR state from GitHub
-#[derive(Debug, Clone, PartialEq)]
-enum PrState {
- Open,
- Merged,
- Closed,
- Unknown,
-}
-
-fn get_pr_state(pr_number: i32, project_path: &Path) -> Result<PrState> {
- let output = std::process::Command::new("gh")
- .current_dir(project_path)
- .args(["pr", "view", &pr_number.to_string(), "--json", "state"])
- .output()?;
-
- if !output.status.success() {
- return Ok(PrState::Unknown);
- }
-
- let stdout = String::from_utf8_lossy(&output.stdout);
- if stdout.contains("MERGED") {
- Ok(PrState::Merged)
- } else if stdout.contains("CLOSED") {
- Ok(PrState::Closed)
- } else if stdout.contains("OPEN") {
- Ok(PrState::Open)
- } else {
- Ok(PrState::Unknown)
- }
-}
-
-/// Generate PR title and description using Claude
-fn generate_pr_description(task_title: &str, worktree_path: Option<&str>, branch_name: Option<&str>) -> (String, String) {
+/// Generate PR title and description using the configured agent
+pub(crate) fn generate_pr_description(
+ task_title: &str,
+ worktree_path: Option<&str>,
+ _branch_name: Option<&str>,
+ git_ops: &dyn GitOperations,
+ agent_ops: &dyn AgentOperations,
+) -> (String, String) {
// Default values
let default_title = task_title.to_string();
let mut default_body = String::new();
// Try to get git diff for context
if let Some(worktree) = worktree_path {
+ let worktree_path = Path::new(worktree);
// Get diff from main
- let diff_output = std::process::Command::new("git")
- .current_dir(worktree)
- .args(["diff", "main", "--stat"])
- .output();
-
- if let Ok(output) = diff_output {
- let diff_stat = String::from_utf8_lossy(&output.stdout);
- if !diff_stat.is_empty() {
- default_body.push_str("## Changes\n```\n");
- default_body.push_str(&diff_stat);
- default_body.push_str("```\n");
- }
+ let diff_stat = git_ops.diff_stat_from_main(worktree_path);
+
+ if !diff_stat.is_empty() {
+ default_body.push_str("## Changes\n```\n");
+ default_body.push_str(&diff_stat);
+ default_body.push_str("```\n");
}
- // Try to use Claude to generate a better description
+ // Try to use the agent to generate a better description
let prompt = format!(
"Generate a concise PR description for these changes. Task: '{}'. Output only the description, no markdown code blocks around it. Keep it brief (2-3 sentences max).",
task_title
);
- let claude_output = std::process::Command::new("claude")
- .current_dir(worktree)
- .args(["--print", &prompt])
- .output();
-
- if let Ok(output) = claude_output {
- if output.status.success() {
- let generated = String::from_utf8_lossy(&output.stdout).trim().to_string();
- if !generated.is_empty() {
- default_body = format!("{}\n\n{}", generated, default_body);
- }
+ if let Ok(generated) = agent_ops.generate_text(worktree_path, &prompt) {
+ if !generated.is_empty() {
+ default_body = format!("{}\n\n{}", generated, default_body);
}
}
}
@@ -2801,126 +2713,68 @@ fn generate_pr_description(task_title: &str, worktree_path: Option<&str>, branch
}
/// Create a PR with provided title and body, return (pr_number, pr_url)
-fn create_pr_with_content(task: &Task, project_path: &Path, pr_title: &str, pr_body: &str) -> Result<(i32, String)> {
+fn create_pr_with_content(
+ task: &Task,
+ project_path: &Path,
+ pr_title: &str,
+ pr_body: &str,
+ git_ops: &dyn GitOperations,
+ git_provider_ops: &dyn GitProviderOperations,
+ agent_ops: &dyn AgentOperations,
+) -> Result<(i32, String)> {
let worktree = task.worktree_path.as_deref().unwrap_or(".");
+ let worktree_path = Path::new(worktree);
// Stage all changes
- std::process::Command::new("git")
- .current_dir(worktree)
- .args(["add", "-A"])
- .output()?;
+ git_ops.add_all(worktree_path)?;
// Check if there are changes to commit
- let status_output = std::process::Command::new("git")
- .current_dir(worktree)
- .args(["status", "--porcelain"])
- .output()?;
-
- let has_changes = !status_output.stdout.is_empty();
+ let has_changes = git_ops.has_changes(worktree_path);
// Commit if there are staged changes
if has_changes {
- let commit_msg = format!("{}\n\nCo-Authored-By: Claude <[email protected]>", pr_title);
- let commit_output = std::process::Command::new("git")
- .current_dir(worktree)
- .args(["commit", "-m", &commit_msg])
- .output()?;
-
- if !commit_output.status.success() {
- let stderr = String::from_utf8_lossy(&commit_output.stderr);
- // Only fail if it's not "nothing to commit"
- if !stderr.contains("nothing to commit") {
- anyhow::bail!("Failed to commit changes: {}", stderr);
- }
- }
+ let commit_msg = format!("{}\n\nCo-Authored-By: {}", pr_title, agent_ops.co_author_string());
+ git_ops.commit(worktree_path, &commit_msg)?;
}
// Push the branch
if let Some(branch) = &task.branch_name {
- let push_output = std::process::Command::new("git")
- .current_dir(worktree)
- .args(["push", "-u", "origin", branch])
- .output()?;
-
- if !push_output.status.success() {
- let stderr = String::from_utf8_lossy(&push_output.stderr);
- anyhow::bail!("Failed to push branch: {}", stderr);
- }
+ git_ops.push(worktree_path, branch, true)?;
}
// Create PR
- let output = std::process::Command::new("gh")
- .current_dir(project_path)
- .args([
- "pr", "create",
- "--title", pr_title,
- "--body", pr_body,
- "--head", task.branch_name.as_deref().unwrap_or(""),
- ])
- .output()?;
-
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!("Failed to create PR: {}", stderr);
- }
-
- let pr_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
-
- // Get PR number from URL
- let pr_number = pr_url
- .split('/')
- .last()
- .and_then(|s| s.parse::<i32>().ok())
- .unwrap_or(0);
-
- Ok((pr_number, pr_url))
+ git_provider_ops.create_pr(
+ project_path,
+ pr_title,
+ pr_body,
+ task.branch_name.as_deref().unwrap_or(""),
+ )
}
/// Push changes to an existing PR (commit and push only, no PR creation)
-fn push_changes_to_existing_pr(task: &Task, _project_path: &Path) -> Result<String> {
+fn push_changes_to_existing_pr(
+ task: &Task,
+ git_ops: &dyn GitOperations,
+ agent_ops: &dyn AgentOperations,
+) -> Result<String> {
let worktree = task.worktree_path.as_deref().unwrap_or(".");
+ let worktree_path = Path::new(worktree);
// Stage all changes
- std::process::Command::new("git")
- .current_dir(worktree)
- .args(["add", "-A"])
- .output()?;
+ git_ops.add_all(worktree_path)?;
// Check if there are changes to commit
- let status_output = std::process::Command::new("git")
- .current_dir(worktree)
- .args(["status", "--porcelain"])
- .output()?;
-
- let has_changes = !status_output.stdout.is_empty();
+ let has_changes = git_ops.has_changes(worktree_path);
// Commit if there are staged changes
if has_changes {
- let commit_msg = "Address review comments\n\nCo-Authored-By: Claude <[email protected]>";
- let commit_output = std::process::Command::new("git")
- .current_dir(worktree)
- .args(["commit", "-m", commit_msg])
- .output()?;
-
- if !commit_output.status.success() {
- let stderr = String::from_utf8_lossy(&commit_output.stderr);
- if !stderr.contains("nothing to commit") {
- anyhow::bail!("Failed to commit changes: {}", stderr);
- }
- }
+ let commit_msg = format!("Address review comments\n\nCo-Authored-By: {}", agent_ops.co_author_string());
+ git_ops.commit(worktree_path, &commit_msg)?;
}
// Push the branch
if let Some(branch) = &task.branch_name {
- let push_output = std::process::Command::new("git")
- .current_dir(worktree)
- .args(["push", "origin", branch])
- .output()?;
-
- if !push_output.status.success() {
- let stderr = String::from_utf8_lossy(&push_output.stderr);
- anyhow::bail!("Failed to push changes: {}", stderr);
- }
+ git_ops.push(worktree_path, branch, false)?;
}
// Return the existing PR URL
@@ -2928,7 +2782,7 @@ fn push_changes_to_existing_pr(task: &Task, _project_path: &Path) -> Result<Stri
}
/// Send a key to a tmux pane
-fn send_key_to_tmux(window_name: &str, key: KeyCode) {
+fn send_key_to_tmux(window_name: &str, key: KeyCode, tmux_ops: &dyn TmuxOperations) {
let key_str = match key {
KeyCode::Char(c) => c.to_string(),
KeyCode::Enter => "Enter".to_string(),
@@ -2949,10 +2803,7 @@ fn send_key_to_tmux(window_name: &str, key: KeyCode) {
_ => return,
};
- let _ = std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["send-keys", "-t", window_name, &key_str])
- .output();
+ let _ = tmux_ops.send_keys_literal(window_name, &key_str);
}
/// Parse ANSI escape sequences to ratatui Lines with colors
@@ -3095,47 +2946,39 @@ fn parse_sgr(seq: &str, mut style: Style) -> Style {
}
/// Fuzzy find files in a directory (respects .gitignore)
-fn fuzzy_find_files(project_path: &Path, pattern: &str, max_results: usize) -> Vec<String> {
- use std::process::Command;
-
+fn fuzzy_find_files(project_path: &Path, pattern: &str, max_results: usize, git_ops: &dyn GitOperations) -> Vec<String> {
// Use git ls-files to get tracked files (respects .gitignore)
- let output = Command::new("git")
- .current_dir(project_path)
- .args(["ls-files", "--cached", "--others", "--exclude-standard"])
- .output();
-
- if let Ok(output) = output {
- let stdout = String::from_utf8_lossy(&output.stdout);
- let files: Vec<String> = stdout.lines().map(String::from).collect();
-
- if pattern.is_empty() {
- // Show first N files when pattern is empty
- return files.into_iter().take(max_results).collect();
- }
+ let files = git_ops.list_files(project_path);
- let pattern_lower = pattern.to_lowercase();
- let mut matches: Vec<(String, i32)> = files
- .into_iter()
- .filter_map(|path| {
- let path_lower = path.to_lowercase();
+ if files.is_empty() {
+ return vec![];
+ }
- // Simple fuzzy matching: check if all pattern chars appear in order
- let score = fuzzy_score(&path_lower, &pattern_lower);
- if score > 0 {
- Some((path, score))
- } else {
- None
- }
- })
- .collect();
+ if pattern.is_empty() {
+ // Show first N files when pattern is empty
+ return files.into_iter().take(max_results).collect();
+ }
- // Sort by score (higher is better)
- matches.sort_by(|a, b| b.1.cmp(&a.1));
+ let pattern_lower = pattern.to_lowercase();
+ let mut matches: Vec<(String, i32)> = files
+ .into_iter()
+ .filter_map(|path| {
+ let path_lower = path.to_lowercase();
- return matches.into_iter().take(max_results).map(|(path, _)| path).collect();
- }
+ // Simple fuzzy matching: check if all pattern chars appear in order
+ let score = fuzzy_score(&path_lower, &pattern_lower);
+ if score > 0 {
+ Some((path, score))
+ } else {
+ None
+ }
+ })
+ .collect();
+
+ // Sort by score (higher is better)
+ matches.sort_by(|a, b| b.1.cmp(&a.1));
- vec![]
+ matches.into_iter().take(max_results).map(|(path, _)| path).collect()
}
/// Calculate fuzzy match score (higher is better, 0 means no match)
@@ -3181,3 +3024,7 @@ fn fuzzy_score(haystack: &str, needle: &str) -> i32 {
0
}
}
+
+#[cfg(test)]
+#[path = "app_tests.rs"]
+mod tests;
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
new file mode 100644
index 0000000..e8ab573
--- /dev/null
+++ b/src/tui/app_tests.rs
@@ -0,0 +1,1050 @@
+//! Unit tests for app.rs logic
+
+use super::*;
+
+#[cfg(feature = "test-mocks")]
+use crate::agent::MockAgentOperations;
+#[cfg(feature = "test-mocks")]
+use crate::git::{MockGitOperations, MockGitProviderOperations};
+#[cfg(feature = "test-mocks")]
+use crate::tmux::MockTmuxOperations;
+
+/// Test that generate_pr_description correctly combines git diff and agent-generated text
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_generate_pr_description_with_diff_and_agent() {
+ let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
+
+ // Setup: git returns a diff stat
+ mock_git
+ .expect_diff_stat_from_main()
+ .withf(|path: &Path| path == Path::new("/tmp/worktree"))
+ .times(1)
+ .returning(|_| " src/main.rs | 10 +++++++---\n 1 file changed".to_string());
+
+ // Setup: agent generates a description
+ mock_agent
+ .expect_generate_text()
+ .withf(|path: &Path, prompt: &str| {
+ path == Path::new("/tmp/worktree") && prompt.contains("Add login feature")
+ })
+ .times(1)
+ .returning(|_, _| {
+ Ok("This PR implements user authentication with session management.".to_string())
+ });
+
+ // Execute
+ let (title, body) = generate_pr_description(
+ "Add login feature",
+ Some("/tmp/worktree"),
+ None,
+ &mock_git,
+ &mock_agent,
+ );
+
+ // Verify
+ assert_eq!(title, "Add login feature");
+ assert!(body.contains("This PR implements user authentication"));
+ assert!(body.contains("## Changes"));
+ assert!(body.contains("src/main.rs"));
+}
+
+/// Test that generate_pr_description handles missing worktree gracefully
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_generate_pr_description_without_worktree() {
+ let mock_git = MockGitOperations::new();
+ let mock_agent = MockAgentOperations::new();
+
+ // No expectations set - functions should not be called when worktree is None
+
+ let (title, body) = generate_pr_description(
+ "Simple task",
+ None, // No worktree
+ None,
+ &mock_git,
+ &mock_agent,
+ );
+
+ assert_eq!(title, "Simple task");
+ assert!(body.is_empty());
+}
+
+/// Test that generate_pr_description handles empty diff gracefully
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_generate_pr_description_with_empty_diff() {
+ let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
+
+ // Git returns empty diff (no changes from main)
+ mock_git
+ .expect_diff_stat_from_main()
+ .returning(|_| String::new());
+
+ // Agent still generates description
+ mock_agent
+ .expect_generate_text()
+ .returning(|_, _| Ok("Minor documentation update.".to_string()));
+
+ let (title, body) = generate_pr_description(
+ "Update docs",
+ Some("/tmp/worktree"),
+ None,
+ &mock_git,
+ &mock_agent,
+ );
+
+ assert_eq!(title, "Update docs");
+ assert!(body.contains("Minor documentation update"));
+ assert!(!body.contains("## Changes")); // No changes section when diff is empty
+}
+
+/// Test that generate_pr_description handles agent failure gracefully
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_generate_pr_description_agent_failure() {
+ let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
+
+ mock_git
+ .expect_diff_stat_from_main()
+ .returning(|_| " file.rs | 5 +++++\n".to_string());
+
+ // Agent fails to generate
+ mock_agent
+ .expect_generate_text()
+ .returning(|_, _| Err(anyhow::anyhow!("Agent not available")));
+
+ let (title, body) = generate_pr_description(
+ "Fix bug",
+ Some("/tmp/worktree"),
+ None,
+ &mock_git,
+ &mock_agent,
+ );
+
+ assert_eq!(title, "Fix bug");
+ // Body should still have the diff, just no agent-generated text
+ assert!(body.contains("## Changes"));
+ assert!(body.contains("file.rs"));
+}
+
+// =============================================================================
+// Tests for ensure_project_tmux_session
+// =============================================================================
+
+/// Test that ensure_project_tmux_session creates session when it doesn't exist
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_ensure_project_tmux_session_creates_when_missing() {
+ let mut mock_tmux = MockTmuxOperations::new();
+
+ // Session doesn't exist
+ mock_tmux
+ .expect_has_session()
+ .with(mockall::predicate::eq("my-project"))
+ .times(1)
+ .returning(|_| false);
+
+ // Should create the session
+ mock_tmux
+ .expect_create_session()
+ .with(
+ mockall::predicate::eq("my-project"),
+ mockall::predicate::eq("/home/user/project"),
+ )
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ ensure_project_tmux_session("my-project", Path::new("/home/user/project"), &mock_tmux);
+}
+
+/// Test that ensure_project_tmux_session skips creation when session exists
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_ensure_project_tmux_session_skips_when_exists() {
+ let mut mock_tmux = MockTmuxOperations::new();
+
+ // Session already exists
+ mock_tmux
+ .expect_has_session()
+ .with(mockall::predicate::eq("existing-project"))
+ .times(1)
+ .returning(|_| true);
+
+ // create_session should NOT be called
+ // (mockall will fail if unexpected calls are made)
+
+ ensure_project_tmux_session("existing-project", Path::new("/tmp/project"), &mock_tmux);
+}
+
+// =============================================================================
+// Tests for create_pr_with_content
+// =============================================================================
+
+/// Test successful PR creation with changes
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_create_pr_with_content_success() {
+ let mut mock_git = MockGitOperations::new();
+ let mut mock_git_provider = MockGitProviderOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
+
+ let task = Task {
+ id: "test-123".to_string(),
+ title: "Test task".to_string(),
+ description: None,
+ status: TaskStatus::Running,
+ agent: "claude".to_string(),
+ project_id: "proj-1".to_string(),
+ session_name: Some("test-session".to_string()),
+ worktree_path: Some("/tmp/worktree".to_string()),
+ branch_name: Some("feature/test".to_string()),
+ pr_number: None,
+ pr_url: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ };
+
+ // Expect: add all files
+ mock_git
+ .expect_add_all()
+ .withf(|path: &Path| path == Path::new("/tmp/worktree"))
+ .times(1)
+ .returning(|_| Ok(()));
+
+ // Expect: check for changes
+ mock_git
+ .expect_has_changes()
+ .withf(|path: &Path| path == Path::new("/tmp/worktree"))
+ .times(1)
+ .returning(|_| true);
+
+ // Expect: commit with co-author
+ mock_git
+ .expect_commit()
+ .withf(|path: &Path, msg: &str| {
+ path == Path::new("/tmp/worktree") && msg.contains("Test PR") && msg.contains("Co-Authored-By")
+ })
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ // Expect: push with upstream
+ mock_git
+ .expect_push()
+ .withf(|path: &Path, branch: &str, set_upstream: &bool| {
+ path == Path::new("/tmp/worktree") && branch == "feature/test" && *set_upstream
+ })
+ .times(1)
+ .returning(|_, _, _| Ok(()));
+
+ // Agent co-author string
+ mock_agent
+ .expect_co_author_string()
+ .return_const("Claude <[email protected]>".to_string());
+
+ // Expect: create PR
+ mock_git_provider
+ .expect_create_pr()
+ .withf(|path: &Path, title: &str, body: &str, branch: &str| {
+ path == Path::new("/project") && title == "Test PR" && body == "Test body" && branch == "feature/test"
+ })
+ .times(1)
+ .returning(|_, _, _, _| Ok((42, "https://github.com/org/repo/pull/42".to_string())));
+
+ let result = create_pr_with_content(
+ &task,
+ Path::new("/project"),
+ "Test PR",
+ "Test body",
+ &mock_git,
+ &mock_git_provider,
+ &mock_agent,
+ );
+
+ assert!(result.is_ok());
+ let (pr_number, pr_url) = result.unwrap();
+ assert_eq!(pr_number, 42);
+ assert_eq!(pr_url, "https://github.com/org/repo/pull/42");
+}
+
+/// Test PR creation with no changes to commit
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_create_pr_with_content_no_changes() {
+ let mut mock_git = MockGitOperations::new();
+ let mut mock_git_provider = MockGitProviderOperations::new();
+ let mock_agent = MockAgentOperations::new();
+
+ let task = Task {
+ id: "test-123".to_string(),
+ title: "Test task".to_string(),
+ description: None,
+ status: TaskStatus::Running,
+ agent: "claude".to_string(),
+ project_id: "proj-1".to_string(),
+ session_name: Some("test-session".to_string()),
+ worktree_path: Some("/tmp/worktree".to_string()),
+ branch_name: Some("feature/test".to_string()),
+ pr_number: None,
+ pr_url: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ };
+
+ mock_git
+ .expect_add_all()
+ .returning(|_| Ok(()));
+
+ // No changes to commit
+ mock_git
+ .expect_has_changes()
+ .returning(|_| false);
+
+ // commit should NOT be called (no expectation set)
+
+ mock_git
+ .expect_push()
+ .returning(|_, _, _| Ok(()));
+
+ mock_git_provider
+ .expect_create_pr()
+ .returning(|_, _, _, _| Ok((1, "https://github.com/pr/1".to_string())));
+
+ let result = create_pr_with_content(
+ &task,
+ Path::new("/project"),
+ "PR Title",
+ "PR Body",
+ &mock_git,
+ &mock_git_provider,
+ &mock_agent,
+ );
+
+ assert!(result.is_ok());
+}
+
+/// Test PR creation failure on push
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_create_pr_with_content_push_failure() {
+ let mut mock_git = MockGitOperations::new();
+ let mock_git_provider = MockGitProviderOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
+
+ let task = Task {
+ id: "test-123".to_string(),
+ title: "Test task".to_string(),
+ description: None,
+ status: TaskStatus::Running,
+ agent: "claude".to_string(),
+ project_id: "proj-1".to_string(),
+ session_name: None,
+ worktree_path: Some("/tmp/worktree".to_string()),
+ branch_name: Some("feature/test".to_string()),
+ pr_number: None,
+ pr_url: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ };
+
+ mock_git.expect_add_all().returning(|_| Ok(()));
+ mock_git.expect_has_changes().returning(|_| true);
+ mock_git.expect_commit().returning(|_, _| Ok(()));
+ mock_agent
+ .expect_co_author_string()
+ .return_const("Claude <[email protected]>".to_string());
+
+ // Push fails
+ mock_git
+ .expect_push()
+ .returning(|_, _, _| Err(anyhow::anyhow!("Permission denied")));
+
+ let result = create_pr_with_content(
+ &task,
+ Path::new("/project"),
+ "PR",
+ "Body",
+ &mock_git,
+ &mock_git_provider,
+ &mock_agent,
+ );
+
+ assert!(result.is_err());
+ assert!(result.unwrap_err().to_string().contains("Permission denied"));
+}
+
+// =============================================================================
+// Tests for push_changes_to_existing_pr
+// =============================================================================
+
+/// Test pushing changes to existing PR
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_push_changes_to_existing_pr_success() {
+ let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
+
+ let task = Task {
+ id: "test-456".to_string(),
+ title: "Existing PR task".to_string(),
+ description: None,
+ status: TaskStatus::Review,
+ agent: "claude".to_string(),
+ project_id: "proj-1".to_string(),
+ session_name: Some("test-session".to_string()),
+ worktree_path: Some("/tmp/worktree".to_string()),
+ branch_name: Some("feature/existing".to_string()),
+ pr_number: Some(99),
+ pr_url: Some("https://github.com/org/repo/pull/99".to_string()),
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ };
+
+ mock_git.expect_add_all().returning(|_| Ok(()));
+ mock_git.expect_has_changes().returning(|_| true);
+
+ // Commit message should include "Address review comments"
+ mock_git
+ .expect_commit()
+ .withf(|_: &Path, msg: &str| msg.contains("Address review comments"))
+ .returning(|_, _| Ok(()));
+
+ // Push without setting upstream (false)
+ mock_git
+ .expect_push()
+ .withf(|_: &Path, branch: &str, set_upstream: &bool| {
+ branch == "feature/existing" && !*set_upstream
+ })
+ .returning(|_, _, _| Ok(()));
+
+ mock_agent
+ .expect_co_author_string()
+ .return_const("Claude <[email protected]>".to_string());
+
+ let result = push_changes_to_existing_pr(&task, &mock_git, &mock_agent);
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), "https://github.com/org/repo/pull/99");
+}
+
+/// Test pushing when no changes exist
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_push_changes_to_existing_pr_no_changes() {
+ let mut mock_git = MockGitOperations::new();
+ let mock_agent = MockAgentOperations::new();
+
+ let task = Task {
+ id: "test-789".to_string(),
+ title: "Task with no changes".to_string(),
+ description: None,
+ status: TaskStatus::Review,
+ agent: "claude".to_string(),
+ project_id: "proj-1".to_string(),
+ session_name: None,
+ worktree_path: Some("/tmp/worktree".to_string()),
+ branch_name: Some("feature/no-changes".to_string()),
+ pr_number: Some(50),
+ pr_url: Some("https://github.com/org/repo/pull/50".to_string()),
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ };
+
+ mock_git.expect_add_all().returning(|_| Ok(()));
+ mock_git.expect_has_changes().returning(|_| false);
+ // No commit expected
+ mock_git.expect_push().returning(|_, _, _| Ok(()));
+
+ let result = push_changes_to_existing_pr(&task, &mock_git, &mock_agent);
+
+ assert!(result.is_ok());
+}
+
+/// Test push with no existing PR URL
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_push_changes_to_existing_pr_no_url() {
+ let mut mock_git = MockGitOperations::new();
+ let mock_agent = MockAgentOperations::new();
+
+ let task = Task {
+ id: "test-abc".to_string(),
+ title: "Task without PR URL".to_string(),
+ description: None,
+ status: TaskStatus::Review,
+ agent: "claude".to_string(),
+ project_id: "proj-1".to_string(),
+ session_name: None,
+ worktree_path: Some("/tmp/worktree".to_string()),
+ branch_name: Some("feature/branch".to_string()),
+ pr_number: None,
+ pr_url: None, // No PR URL
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ };
+
+ mock_git.expect_add_all().returning(|_| Ok(()));
+ mock_git.expect_has_changes().returning(|_| false);
+ mock_git.expect_push().returning(|_, _, _| Ok(()));
+
+ let result = push_changes_to_existing_pr(&task, &mock_git, &mock_agent);
+
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), "Changes pushed to existing PR");
+}
+
+// =============================================================================
+// Tests for fuzzy_find_files
+// =============================================================================
+
+/// Test fuzzy file search with matching pattern
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_fuzzy_find_files_basic() {
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_list_files()
+ .returning(|_| vec![
+ "src/main.rs".to_string(),
+ "src/lib.rs".to_string(),
+ "src/tui/app.rs".to_string(),
+ "src/tui/board.rs".to_string(),
+ "Cargo.toml".to_string(),
+ ]);
+
+ let results = fuzzy_find_files(Path::new("/project"), "app", 10, &mock_git);
+
+ assert!(!results.is_empty());
+ assert!(results.contains(&"src/tui/app.rs".to_string()));
+}
+
+/// Test fuzzy file search with empty pattern returns first N files
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_fuzzy_find_files_empty_pattern() {
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_list_files()
+ .returning(|_| vec![
+ "a.rs".to_string(),
+ "b.rs".to_string(),
+ "c.rs".to_string(),
+ "d.rs".to_string(),
+ "e.rs".to_string(),
+ ]);
+
+ let results = fuzzy_find_files(Path::new("/project"), "", 3, &mock_git);
+
+ assert_eq!(results.len(), 3);
+ assert_eq!(results[0], "a.rs");
+ assert_eq!(results[1], "b.rs");
+ assert_eq!(results[2], "c.rs");
+}
+
+/// Test fuzzy file search with no matches
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_fuzzy_find_files_no_matches() {
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_list_files()
+ .returning(|_| vec!["main.rs".to_string(), "lib.rs".to_string()]);
+
+ let results = fuzzy_find_files(Path::new("/project"), "xyz123", 10, &mock_git);
+
+ assert!(results.is_empty());
+}
+
+/// Test fuzzy file search with empty file list
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_fuzzy_find_files_empty_list() {
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git.expect_list_files().returning(|_| vec![]);
+
+ let results = fuzzy_find_files(Path::new("/project"), "app", 10, &mock_git);
+
+ assert!(results.is_empty());
+}
+
+/// Test fuzzy file search respects max_results
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_fuzzy_find_files_max_results() {
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_list_files()
+ .returning(|_| vec![
+ "src/app1.rs".to_string(),
+ "src/app2.rs".to_string(),
+ "src/app3.rs".to_string(),
+ "src/app4.rs".to_string(),
+ "src/app5.rs".to_string(),
+ ]);
+
+ let results = fuzzy_find_files(Path::new("/project"), "app", 2, &mock_git);
+
+ assert_eq!(results.len(), 2);
+}
+
+// =============================================================================
+// Tests for fuzzy_score
+// =============================================================================
+
+/// Test fuzzy score with exact match
+#[test]
+fn test_fuzzy_score_exact_match() {
+ let score = fuzzy_score("main.rs", "main.rs");
+ assert!(score > 0);
+}
+
+/// Test fuzzy score with partial match
+#[test]
+fn test_fuzzy_score_partial_match() {
+ let score = fuzzy_score("src/main.rs", "main");
+ assert!(score > 0);
+}
+
+/// Test fuzzy score with no match
+#[test]
+fn test_fuzzy_score_no_match() {
+ let score = fuzzy_score("main.rs", "xyz");
+ assert_eq!(score, 0);
+}
+
+/// Test fuzzy score with empty needle
+#[test]
+fn test_fuzzy_score_empty_needle() {
+ let score = fuzzy_score("main.rs", "");
+ assert_eq!(score, 1);
+}
+
+/// Test fuzzy score bonus for word start
+#[test]
+fn test_fuzzy_score_word_boundary_bonus() {
+ // "app" at start of segment should score higher than in middle
+ let score_start = fuzzy_score("src/app.rs", "app");
+ let score_middle = fuzzy_score("src/myapp.rs", "app");
+ assert!(score_start > score_middle);
+}
+
+/// Test fuzzy score bonus for consecutive matches
+#[test]
+fn test_fuzzy_score_consecutive_bonus() {
+ // Consecutive "main" should score higher than scattered chars within a word
+ let score_consecutive = fuzzy_score("main.rs", "main");
+ let score_scattered = fuzzy_score("myaweirdin.rs", "main");
+ assert!(score_consecutive > score_scattered);
+}
+
+// =============================================================================
+// Tests for send_key_to_tmux
+// =============================================================================
+
+/// Test sending character key to tmux
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_key_to_tmux_char() {
+ let mut mock_tmux = MockTmuxOperations::new();
+
+ mock_tmux
+ .expect_send_keys_literal()
+ .with(
+ mockall::predicate::eq("test-window"),
+ mockall::predicate::eq("a"),
+ )
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ send_key_to_tmux("test-window", KeyCode::Char('a'), &mock_tmux);
+}
+
+/// Test sending Enter key to tmux
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_key_to_tmux_enter() {
+ let mut mock_tmux = MockTmuxOperations::new();
+
+ mock_tmux
+ .expect_send_keys_literal()
+ .with(
+ mockall::predicate::eq("test-window"),
+ mockall::predicate::eq("Enter"),
+ )
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ send_key_to_tmux("test-window", KeyCode::Enter, &mock_tmux);
+}
+
+/// Test sending special keys to tmux
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_key_to_tmux_special_keys() {
+ let mut mock_tmux = MockTmuxOperations::new();
+
+ // Test Escape
+ mock_tmux
+ .expect_send_keys_literal()
+ .with(mockall::predicate::eq("win"), mockall::predicate::eq("Escape"))
+ .returning(|_, _| Ok(()));
+
+ send_key_to_tmux("win", KeyCode::Esc, &mock_tmux);
+
+ // Test Backspace
+ let mut mock_tmux2 = MockTmuxOperations::new();
+ mock_tmux2
+ .expect_send_keys_literal()
+ .with(mockall::predicate::eq("win"), mockall::predicate::eq("BSpace"))
+ .returning(|_, _| Ok(()));
+
+ send_key_to_tmux("win", KeyCode::Backspace, &mock_tmux2);
+}
+
+/// Test sending function key to tmux
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_key_to_tmux_function_key() {
+ let mut mock_tmux = MockTmuxOperations::new();
+
+ mock_tmux
+ .expect_send_keys_literal()
+ .with(mockall::predicate::eq("win"), mockall::predicate::eq("F5"))
+ .returning(|_, _| Ok(()));
+
+ send_key_to_tmux("win", KeyCode::F(5), &mock_tmux);
+}
+
+// =============================================================================
+// Tests for capture_tmux_pane_with_history
+// =============================================================================
+
+/// Test capturing tmux pane content
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_capture_tmux_pane_with_history() {
+ let mut mock_tmux = MockTmuxOperations::new();
+
+ mock_tmux
+ .expect_capture_pane_with_history()
+ .with(mockall::predicate::eq("test-window"), mockall::predicate::eq(500))
+ .returning(|_, _| b"Line 1\nLine 2\nLine 3\n".to_vec());
+
+ mock_tmux
+ .expect_get_cursor_info()
+ .with(mockall::predicate::eq("test-window"))
+ .returning(|_| Some((2, 3))); // cursor at line 2, pane has 3 lines
+
+ let content = capture_tmux_pane_with_history("test-window", 500, &mock_tmux);
+
+ // Content should be trimmed to cursor position
+ assert!(!content.is_empty());
+}
+
+// =============================================================================
+// Tests for centered_rect helpers (pure functions, no mocks needed)
+// =============================================================================
+
+/// Test centered_rect creates correct dimensions
+#[test]
+fn test_centered_rect() {
+ let area = Rect::new(0, 0, 100, 50);
+ let popup = centered_rect(50, 50, area);
+
+ // Should be centered horizontally and vertically
+ assert!(popup.x > 0);
+ assert!(popup.y > 0);
+ assert!(popup.width < 100);
+ assert!(popup.height < 50);
+}
+
+/// Test centered_rect_fixed_width creates correct dimensions
+#[test]
+fn test_centered_rect_fixed_width() {
+ let area = Rect::new(0, 0, 100, 50);
+ let popup = centered_rect_fixed_width(40, 50, area);
+
+ // Width should be fixed at 40
+ assert_eq!(popup.width, 40);
+ // Should be centered
+ assert_eq!(popup.x, 30); // (100 - 40) / 2
+}
+
+/// Test centered_rect_fixed_width caps width to terminal size
+#[test]
+fn test_centered_rect_fixed_width_capped() {
+ let area = Rect::new(0, 0, 30, 50); // Small terminal
+ let popup = centered_rect_fixed_width(100, 50, area); // Request large width
+
+ // Width should be capped
+ assert!(popup.width <= 30);
+}
+
+// =============================================================================
+// Tests for hex_to_color
+// =============================================================================
+
+/// Test hex_to_color with valid hex
+#[test]
+fn test_hex_to_color_valid() {
+ let color = hex_to_color("#FF0000");
+ assert_eq!(color, Color::Rgb(255, 0, 0));
+}
+
+/// Test hex_to_color with invalid hex falls back to white
+#[test]
+fn test_hex_to_color_invalid() {
+ let color = hex_to_color("invalid");
+ assert_eq!(color, Color::White);
+}
+
+// =============================================================================
+// Tests for generate_task_slug
+// =============================================================================
+
+/// Test generate_task_slug with normal title
+#[test]
+fn test_generate_task_slug_normal() {
+ let slug = generate_task_slug("12345678-abcd-efgh", "Add login feature");
+ assert!(slug.starts_with("12345678-"));
+ assert!(slug.contains("Add-login-feature"));
+}
+
+/// Test generate_task_slug with special characters
+#[test]
+fn test_generate_task_slug_special_chars() {
+ let slug = generate_task_slug("abc12345", "Fix bug #123 (urgent!)");
+ assert!(slug.starts_with("abc12345-"));
+ // Special chars should be replaced with dashes
+ assert!(!slug.contains("#"));
+ assert!(!slug.contains("("));
+ assert!(!slug.contains("!"));
+}
+
+/// Test generate_task_slug truncates long titles
+#[test]
+fn test_generate_task_slug_long_title() {
+ let long_title = "This is a very long task title that should be truncated to thirty characters";
+ let slug = generate_task_slug("abcd1234", long_title);
+ // 8 char id prefix + "-" + max 30 chars = max 39 chars
+ assert!(slug.len() <= 39);
+}
+
+/// Test generate_task_slug with empty title
+#[test]
+fn test_generate_task_slug_empty_title() {
+ let slug = generate_task_slug("12345678", "");
+ assert_eq!(slug, "12345678-");
+}
+
+// =============================================================================
+// Tests for cleanup_task_for_done
+// =============================================================================
+
+/// Test cleanup_task_for_done cleans up resources
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_cleanup_task_for_done_with_resources() {
+ use crate::db::Task;
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+
+ mock_tmux
+ .expect_kill_window()
+ .with(mockall::predicate::eq("project:task-window"))
+ .times(1)
+ .returning(|_| Ok(()));
+
+ mock_git
+ .expect_remove_worktree()
+ .with(
+ mockall::predicate::eq(Path::new("/project")),
+ mockall::predicate::eq("/tmp/worktree"),
+ )
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ let mut task = Task::new("Test task", "claude", "project-1");
+ task.session_name = Some("project:task-window".to_string());
+ task.worktree_path = Some("/tmp/worktree".to_string());
+ task.status = TaskStatus::Review;
+
+ cleanup_task_for_done(
+ &mut task,
+ Path::new("/project"),
+ &mock_tmux,
+ &mock_git,
+ );
+
+ assert!(task.session_name.is_none());
+ assert!(task.worktree_path.is_none());
+ assert_eq!(task.status, TaskStatus::Done);
+}
+
+/// Test cleanup_task_for_done handles missing resources gracefully
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_cleanup_task_for_done_no_resources() {
+ use crate::db::Task;
+
+ let mock_tmux = MockTmuxOperations::new();
+ let mock_git = MockGitOperations::new();
+ // No expectations - functions should not be called
+
+ let mut task = Task::new("Test task", "claude", "project-1");
+ // No session_name or worktree_path set
+
+ cleanup_task_for_done(
+ &mut task,
+ Path::new("/project"),
+ &mock_tmux,
+ &mock_git,
+ );
+
+ assert_eq!(task.status, TaskStatus::Done);
+}
+
+// =============================================================================
+// Tests for delete_task_resources
+// =============================================================================
+
+/// Test delete_task_resources cleans up all resources
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_delete_task_resources_full_cleanup() {
+ use crate::db::Task;
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+
+ mock_tmux
+ .expect_kill_window()
+ .with(mockall::predicate::eq("project:task-window"))
+ .times(1)
+ .returning(|_| Ok(()));
+
+ mock_git
+ .expect_remove_worktree()
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ mock_git
+ .expect_delete_branch()
+ .with(
+ mockall::predicate::eq(Path::new("/project")),
+ mockall::predicate::eq("task/abc-feature"),
+ )
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ let mut task = Task::new("Feature task", "claude", "project-1");
+ task.session_name = Some("project:task-window".to_string());
+ task.worktree_path = Some("/tmp/worktree".to_string());
+ task.branch_name = Some("task/abc-feature".to_string());
+
+ delete_task_resources(
+ &task,
+ Path::new("/project"),
+ &mock_tmux,
+ &mock_git,
+ );
+}
+
+/// Test delete_task_resources handles task without resources
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_delete_task_resources_no_resources() {
+ use crate::db::Task;
+
+ let mock_tmux = MockTmuxOperations::new();
+ let mock_git = MockGitOperations::new();
+ // No expectations - nothing should be called
+
+ let task = Task::new("Simple task", "claude", "project-1");
+ // No session_name, worktree_path, or branch_name
+
+ delete_task_resources(
+ &task,
+ Path::new("/project"),
+ &mock_tmux,
+ &mock_git,
+ );
+}
+
+// =============================================================================
+// Tests for collect_task_diff
+// =============================================================================
+
+/// Test collect_task_diff with all types of changes
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_collect_task_diff_all_changes() {
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_diff()
+ .returning(|_| "diff --git a/file.rs\n-old\n+new".to_string());
+
+ mock_git
+ .expect_diff_cached()
+ .returning(|_| "diff --git a/staged.rs\n+added".to_string());
+
+ mock_git
+ .expect_list_untracked_files()
+ .returning(|_| "new_file.rs\n".to_string());
+
+ mock_git
+ .expect_diff_untracked_file()
+ .returning(|_, _| "+++ new_file.rs\n+content".to_string());
+
+ let result = collect_task_diff("/tmp/worktree", &mock_git);
+
+ assert!(result.contains("Unstaged Changes"));
+ assert!(result.contains("Staged Changes"));
+ assert!(result.contains("Untracked Files"));
+}
+
+/// Test collect_task_diff with no changes
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_collect_task_diff_no_changes() {
+ 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(|_| String::new());
+
+ let result = collect_task_diff("/tmp/worktree", &mock_git);
+
+ assert!(result.contains("(no changes)"));
+ assert!(result.contains("/tmp/worktree"));
+}
+
+/// Test collect_task_diff with only unstaged changes
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_collect_task_diff_only_unstaged() {
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_diff()
+ .returning(|_| "diff --git a/modified.rs".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/worktree", &mock_git);
+
+ assert!(result.contains("Unstaged Changes"));
+ assert!(!result.contains("Staged Changes"));
+ assert!(!result.contains("Untracked Files"));
+}
diff --git a/tests/git_tests.rs b/tests/git_tests.rs
index 8ed76eb..d71a880 100644
--- a/tests/git_tests.rs
+++ b/tests/git_tests.rs
@@ -43,37 +43,6 @@ fn test_worktree_exists_false_for_nonexistent() {
assert!(!git::worktree_exists(temp_dir.path(), "nonexistent-task"));
}
-#[test]
-fn test_worktree_info_task_id() {
- let info = git::WorktreeInfo {
- path: PathBuf::from("/project/.agtx/worktrees/task-123"),
- branch: Some("task/task-123".to_string()),
- is_bare: false,
- };
- assert_eq!(info.task_id(), Some("task-123"));
-}
-
-#[test]
-fn test_worktree_info_task_id_not_agtx_worktree() {
- // A worktree not in the .agtx/worktrees directory should return None
- let info = git::WorktreeInfo {
- path: PathBuf::from("/project/other-worktree"),
- branch: Some("feature-branch".to_string()),
- is_bare: false,
- };
- assert_eq!(info.task_id(), None);
-}
-
-#[test]
-fn test_worktree_info_bare() {
- let info = git::WorktreeInfo {
- path: PathBuf::from("/project"),
- branch: None,
- is_bare: true,
- };
- assert!(info.is_bare);
- assert!(info.branch.is_none());
-}
// =============================================================================
// Integration tests (require git)
@@ -168,18 +137,6 @@ fn test_create_and_remove_worktree() {
assert!(worktree_path.join(".git").exists());
assert!(git::worktree_exists(temp_dir.path(), "test-task"));
- // List worktrees should include it
- let worktrees = git::list_worktrees(temp_dir.path()).unwrap();
- assert!(worktrees.len() >= 2); // main + our worktree
-
- // Canonicalize paths to handle macOS /var -> /private/var symlink
- let worktree_path_canonical = worktree_path.canonicalize().unwrap();
- let task_worktree = worktrees.iter().find(|w| {
- w.path.canonicalize().ok() == Some(worktree_path_canonical.clone())
- });
- assert!(task_worktree.is_some());
- assert_eq!(task_worktree.unwrap().branch, Some("task/test-task".to_string()));
-
// Remove worktree
git::remove_worktree(temp_dir.path(), "test-task").unwrap();
@@ -199,19 +156,6 @@ fn test_create_worktree_idempotent() {
assert!(path1.exists());
}
-#[test]
-fn test_list_worktrees_empty_repo() {
- let temp_dir = setup_git_repo();
-
- // Should have at least the main worktree
- let worktrees = git::list_worktrees(temp_dir.path()).unwrap();
- assert!(!worktrees.is_empty());
-
- // Main worktree should have branch "main"
- let main_worktree = worktrees.iter().find(|w| w.branch == Some("main".to_string()));
- assert!(main_worktree.is_some());
-}
-
// =============================================================================
// Error case tests
// =============================================================================
@@ -271,13 +215,6 @@ fn test_create_worktree_with_master_branch() {
assert!(worktree_path.exists());
assert!(worktree_path.join(".git").exists());
-
- // Verify branch was created
- let worktrees = git::list_worktrees(temp_dir.path()).unwrap();
- let task_worktree = worktrees.iter().find(|w| {
- w.branch == Some("task/master-task".to_string())
- });
- assert!(task_worktree.is_some());
}
#[test]
@@ -303,17 +240,6 @@ fn test_remove_worktree_nonexistent() {
let _ = result;
}
-#[test]
-fn test_list_worktrees_on_non_git_directory() {
- let temp_dir = TempDir::new().unwrap();
- // Don't initialize git
-
- let result = git::list_worktrees(temp_dir.path());
-
- // Should return error or empty list, not panic
- assert!(result.is_err() || result.unwrap().is_empty());
-}
-
#[test]
fn test_is_git_repo_nonexistent_path() {
let path = PathBuf::from("/nonexistent/path/that/does/not/exist");
@@ -351,10 +277,6 @@ fn test_create_multiple_worktrees() {
assert_ne!(path2, path3);
assert_ne!(path1, path3);
- // List should show all of them
- let worktrees = git::list_worktrees(temp_dir.path()).unwrap();
- assert!(worktrees.len() >= 4); // main + 3 tasks
-
// Clean up
git::remove_worktree(temp_dir.path(), "task-1").unwrap();
git::remove_worktree(temp_dir.path(), "task-2").unwrap();
@@ -380,33 +302,6 @@ fn test_worktree_with_uncommitted_changes() {
assert!(result.is_ok());
}
-#[test]
-fn test_worktree_info_task_id_edge_cases() {
- // Test with path that has "worktrees" but not ".agtx"
- let info = git::WorktreeInfo {
- path: PathBuf::from("/project/worktrees/task-123"),
- branch: Some("task/task-123".to_string()),
- is_bare: false,
- };
- // Parent is "worktrees" so it should match
- assert_eq!(info.task_id(), Some("task-123"));
-
- // Test with deeply nested path
- let info2 = git::WorktreeInfo {
- path: PathBuf::from("/a/b/c/.agtx/worktrees/deep-task"),
- branch: None,
- is_bare: false,
- };
- assert_eq!(info2.task_id(), Some("deep-task"));
-
- // Test with root path
- let info3 = git::WorktreeInfo {
- path: PathBuf::from("/"),
- branch: None,
- is_bare: false,
- };
- assert_eq!(info3.task_id(), None);
-}
// =============================================================================
// initialize_worktree tests
diff --git a/tests/mock_infrastructure_tests.rs b/tests/mock_infrastructure_tests.rs
new file mode 100644
index 0000000..feb9174
--- /dev/null
+++ b/tests/mock_infrastructure_tests.rs
@@ -0,0 +1,165 @@
+//! Tests for mock infrastructure
+//!
+//! These tests verify that the mock implementations work correctly.
+//! They serve as a foundation for writing actual app logic tests.
+//!
+//! Run with: cargo test --features test-mocks
+
+#![cfg(feature = "test-mocks")]
+
+use std::path::Path;
+use std::sync::Arc;
+
+use agtx::agent::{AgentOperations, MockAgentOperations};
+use agtx::git::{GitOperations, GitProviderOperations, MockGitOperations, MockGitProviderOperations};
+use agtx::tmux::{MockTmuxOperations, TmuxOperations};
+
+/// Test that mocks can be created and configured
+/// This is a basic smoke test to verify the mock infrastructure works
+#[test]
+fn test_mock_infrastructure_works() {
+ // Create mocks
+ let mut mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+ let mut mock_git_provider = MockGitProviderOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
+
+ // Configure expectations
+ mock_tmux.expect_has_session()
+ .returning(|_| false);
+
+ mock_tmux.expect_create_session()
+ .returning(|_, _| Ok(()));
+
+ mock_git.expect_list_files()
+ .returning(|_| vec!["src/main.rs".to_string(), "Cargo.toml".to_string()]);
+
+ mock_git_provider.expect_get_pr_state()
+ .returning(|_, _| Ok(agtx::git::PullRequestState::Open));
+
+ mock_agent.expect_co_author_string()
+ .return_const("Test Agent <[email protected]>".to_string());
+
+ // Verify mocks work as expected
+ assert!(!mock_tmux.has_session("test-session"));
+ assert!(mock_tmux.create_session("test-session", "/tmp").is_ok());
+
+ let files = mock_git.list_files(Path::new("/tmp"));
+ assert_eq!(files.len(), 2);
+ assert!(files.contains(&"src/main.rs".to_string()));
+
+ let pr_state = mock_git_provider.get_pr_state(Path::new("/tmp"), 123).unwrap();
+ assert_eq!(pr_state, agtx::git::PullRequestState::Open);
+
+ assert_eq!(mock_agent.co_author_string(), "Test Agent <[email protected]>");
+}
+
+/// Test git operations mock for PR workflow
+#[test]
+fn test_git_operations_mock_for_pr_workflow() {
+ let mut mock_git = MockGitOperations::new();
+
+ // Setup expectations for a typical PR creation flow
+ mock_git.expect_add_all()
+ .times(1)
+ .returning(|_| Ok(()));
+
+ mock_git.expect_has_changes()
+ .times(1)
+ .returning(|_| true);
+
+ mock_git.expect_commit()
+ .times(1)
+ .withf(|_: &Path, msg: &str| msg.contains("Test commit"))
+ .returning(|_, _| Ok(()));
+
+ mock_git.expect_push()
+ .times(1)
+ .withf(|_, branch, set_upstream| branch == "feature/test" && *set_upstream)
+ .returning(|_, _, _| Ok(()));
+
+ // Execute the workflow
+ let worktree = Path::new("/tmp/worktree");
+
+ mock_git.add_all(worktree).unwrap();
+ assert!(mock_git.has_changes(worktree));
+ mock_git.commit(worktree, "Test commit message").unwrap();
+ mock_git.push(worktree, "feature/test", true).unwrap();
+}
+
+/// Test tmux operations mock for session management
+#[test]
+fn test_tmux_session_management() {
+ let mut mock_tmux = MockTmuxOperations::new();
+
+ // Session doesn't exist initially
+ mock_tmux.expect_has_session()
+ .with(mockall::predicate::eq("my-project"))
+ .times(1)
+ .returning(|_| false);
+
+ // Create session
+ mock_tmux.expect_create_session()
+ .with(
+ mockall::predicate::eq("my-project"),
+ mockall::predicate::eq("/home/user/project"),
+ )
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ // Create window in session
+ mock_tmux.expect_create_window()
+ .times(1)
+ .returning(|_, _, _, _| Ok(()));
+
+ // Session exists after creation
+ mock_tmux.expect_has_session()
+ .with(mockall::predicate::eq("my-project"))
+ .times(1)
+ .returning(|_| true);
+
+ // Execute
+ assert!(!mock_tmux.has_session("my-project"));
+ mock_tmux.create_session("my-project", "/home/user/project").unwrap();
+ mock_tmux.create_window("my-project", "task-1", "/home/user/project/.agtx/worktrees/task-1", None).unwrap();
+ assert!(mock_tmux.has_session("my-project"));
+}
+
+/// Test agent operations mock
+#[test]
+fn test_agent_operations_mock() {
+ let mut mock_agent = MockAgentOperations::new();
+
+ mock_agent.expect_generate_text()
+ .withf(|_: &Path, prompt: &str| prompt.contains("PR description"))
+ .times(1)
+ .returning(|_, _| Ok("This PR adds a new feature for testing.".to_string()));
+
+ mock_agent.expect_co_author_string()
+ .return_const("Claude <[email protected]>".to_string());
+
+ let result = mock_agent.generate_text(
+ Path::new("/tmp"),
+ "Generate a PR description for this change",
+ ).unwrap();
+
+ assert!(result.contains("new feature"));
+ assert_eq!(mock_agent.co_author_string(), "Claude <[email protected]>");
+}
+
+/// Test that mocks can be wrapped in Arc for thread-safe sharing
+#[test]
+fn test_mocks_can_be_arc_wrapped() {
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_list_files()
+ .returning(|_| vec!["file1.rs".to_string()]);
+
+ // Wrap in Arc (this is how App uses them)
+ let arc_git: Arc<dyn GitOperations> = Arc::new(mock_git);
+
+ // Can be cloned and used
+ let arc_git_clone: Arc<dyn GitOperations> = Arc::clone(&arc_git);
+
+ let files = arc_git_clone.list_files(Path::new("/tmp"));
+ assert_eq!(files.len(), 1);
+}
diff --git a/tests/operations_tests.rs b/tests/operations_tests.rs
deleted file mode 100644
index 60d437b..0000000
--- a/tests/operations_tests.rs
+++ /dev/null
@@ -1,253 +0,0 @@
-#![cfg(feature = "test-mocks")]
-
-use agtx::operations::{GitOperations, MockGitOperations, MockTmuxOperations, TmuxOperations};
-use std::path::Path;
-
-// === Tmux Operations Tests ===
-
-#[test]
-fn test_tmux_window_created_on_task_start() {
- let mut mock_tmux = MockTmuxOperations::new();
-
- // Expect window creation when task moves to Planning
- mock_tmux
- .expect_create_window()
- .withf(|session, window_name, working_dir| {
- session == "myproject"
- && window_name.starts_with("task-")
- && working_dir.contains(".agtx/worktrees")
- })
- .times(1)
- .returning(|_, _, _| Ok(()));
-
- // Simulate task starting
- let result = mock_tmux.create_window(
- "myproject",
- "task-abc123-my-feature",
- "/path/to/project/.agtx/worktrees/abc123-my-feature",
- );
-
- assert!(result.is_ok());
-}
-
-#[test]
-fn test_tmux_window_killed_on_task_done() {
- let mut mock_tmux = MockTmuxOperations::new();
-
- // Expect window to be killed when task moves to Done
- mock_tmux
- .expect_kill_window()
- .withf(|target| target == "myproject:task-abc123-my-feature")
- .times(1)
- .returning(|_| Ok(()));
-
- // Simulate task completion
- let result = mock_tmux.kill_window("myproject:task-abc123-my-feature");
-
- assert!(result.is_ok());
-}
-
-#[test]
-fn test_tmux_window_not_killed_on_review() {
- let mut mock_tmux = MockTmuxOperations::new();
-
- // Window should NOT be killed when moving to Review (we keep it open now)
- mock_tmux.expect_kill_window().times(0);
-
- // No kill_window call should happen
- // (In real code, we simply don't call kill_window when moving to Review)
-}
-
-#[test]
-fn test_tmux_send_keys_for_claude_command() {
- let mut mock_tmux = MockTmuxOperations::new();
-
- mock_tmux
- .expect_send_keys()
- .withf(|target, keys| {
- target == "myproject:task-abc123"
- && keys.contains("claude")
- && keys.contains("--dangerously-skip-permissions")
- })
- .times(1)
- .returning(|_, _| Ok(()));
-
- let result = mock_tmux.send_keys(
- "myproject:task-abc123",
- "claude --dangerously-skip-permissions 'implement feature'",
- );
-
- assert!(result.is_ok());
-}
-
-// === Git Operations Tests ===
-
-#[test]
-fn test_worktree_created_on_task_planning() {
- let mut mock_git = MockGitOperations::new();
-
- // Expect worktree creation when task moves to Planning
- mock_git
- .expect_create_worktree()
- .withf(|project_path, task_slug| {
- project_path == Path::new("/path/to/project") && task_slug == "abc123-my-feature"
- })
- .times(1)
- .returning(|_, slug| Ok(format!("/path/to/project/.agtx/worktrees/{}", slug)));
-
- let result = mock_git.create_worktree(Path::new("/path/to/project"), "abc123-my-feature");
-
- assert!(result.is_ok());
- assert!(result.unwrap().contains("abc123-my-feature"));
-}
-
-#[test]
-fn test_worktree_removed_on_task_done() {
- let mut mock_git = MockGitOperations::new();
-
- // Expect worktree removal when task moves to Done
- mock_git
- .expect_remove_worktree()
- .withf(|project_path, worktree_path| {
- project_path == Path::new("/path/to/project")
- && worktree_path == "/path/to/project/.agtx/worktrees/abc123-my-feature"
- })
- .times(1)
- .returning(|_, _| Ok(()));
-
- let result = mock_git.remove_worktree(
- Path::new("/path/to/project"),
- "/path/to/project/.agtx/worktrees/abc123-my-feature",
- );
-
- assert!(result.is_ok());
-}
-
-#[test]
-fn test_worktree_not_removed_on_review() {
- let mut mock_git = MockGitOperations::new();
-
- // Worktree should NOT be removed when moving to Review
- mock_git.expect_remove_worktree().times(0);
-
- // No remove_worktree call should happen when going to Review
-}
-
-#[test]
-fn test_worktree_exists_check() {
- let mut mock_git = MockGitOperations::new();
-
- mock_git
- .expect_worktree_exists()
- .withf(|project_path, task_slug| {
- project_path == Path::new("/path/to/project") && task_slug == "abc123-my-feature"
- })
- .times(1)
- .returning(|_, _| true);
-
- let exists = mock_git.worktree_exists(Path::new("/path/to/project"), "abc123-my-feature");
-
- assert!(exists);
-}
-
-// === Combined Workflow Tests ===
-
-#[test]
-fn test_full_task_lifecycle_creates_and_cleans_resources() {
- let mut mock_tmux = MockTmuxOperations::new();
- let mut mock_git = MockGitOperations::new();
-
- // 1. Backlog -> Planning: Create worktree and tmux window
- mock_git
- .expect_create_worktree()
- .times(1)
- .returning(|_, slug| Ok(format!("/worktrees/{}", slug)));
-
- mock_tmux
- .expect_create_window()
- .times(1)
- .returning(|_, _, _| Ok(()));
-
- mock_tmux
- .expect_send_keys()
- .times(1)
- .returning(|_, _| Ok(()));
-
- // Simulate Planning phase
- let worktree = mock_git
- .create_worktree(Path::new("/project"), "task-123")
- .unwrap();
- mock_tmux
- .create_window("proj", "task-123", &worktree)
- .unwrap();
- mock_tmux
- .send_keys("proj:task-123", "claude --dangerously-skip-permissions 'plan'")
- .unwrap();
-
- // 2. Planning -> Running: Send implementation command
- mock_tmux
- .expect_send_keys()
- .times(1)
- .returning(|_, _| Ok(()));
-
- mock_tmux
- .send_keys("proj:task-123", "Please implement the plan")
- .unwrap();
-
- // 3. Running -> Review: Window stays open (no kill)
- // (nothing happens here - window persists)
-
- // 4. Review -> Done: Cleanup
- mock_tmux
- .expect_kill_window()
- .times(1)
- .returning(|_| Ok(()));
-
- mock_git
- .expect_remove_worktree()
- .times(1)
- .returning(|_, _| Ok(()));
-
- mock_tmux.kill_window("proj:task-123").unwrap();
- mock_git
- .remove_worktree(Path::new("/project"), &worktree)
- .unwrap();
-}
-
-#[test]
-fn test_resume_from_review_does_not_recreate_resources() {
- let mut mock_tmux = MockTmuxOperations::new();
- let mut mock_git = MockGitOperations::new();
-
- // When resuming from Review -> Running, we should NOT create new resources
- mock_git.expect_create_worktree().times(0);
- mock_tmux.expect_create_window().times(0);
-
- // The existing window and worktree should be reused
- // (In real code, we just change the task status)
-}
-
-#[test]
-fn test_delete_task_cleans_up_all_resources() {
- let mut mock_tmux = MockTmuxOperations::new();
- let mut mock_git = MockGitOperations::new();
-
- // Deleting a task should clean up both tmux window and worktree
- mock_tmux
- .expect_kill_window()
- .withf(|target| target == "proj:task-abc123")
- .times(1)
- .returning(|_| Ok(()));
-
- mock_git
- .expect_remove_worktree()
- .withf(|_, worktree| worktree.contains("abc123"))
- .times(1)
- .returning(|_, _| Ok(()));
-
- // Simulate delete
- mock_tmux.kill_window("proj:task-abc123").unwrap();
- mock_git
- .remove_worktree(Path::new("/project"), "/project/.agtx/worktrees/abc123")
- .unwrap();
-}
diff --git a/tests/workflow_tests.rs b/tests/workflow_tests.rs
deleted file mode 100644
index 538c0d4..0000000
--- a/tests/workflow_tests.rs
+++ /dev/null
@@ -1,133 +0,0 @@
-use agtx::db::{Task, TaskStatus};
-
-fn create_test_task(title: &str, status: TaskStatus) -> Task {
- let mut task = Task::new(title, "claude", "test-project");
- task.status = status;
- task
-}
-
-// === Task State Transition Tests ===
-
-/// Valid workflow transitions:
-/// Backlog β†’ Planning β†’ Running β†’ Review β†’ Done
-/// ↑__________| (resume via 'r')
-
-#[test]
-fn test_valid_forward_transitions() {
- // Backlog can move to Planning
- let task = create_test_task("Test", TaskStatus::Backlog);
- assert!(is_valid_forward_transition(task.status, TaskStatus::Planning));
-
- // Planning can move to Running
- let task = create_test_task("Test", TaskStatus::Planning);
- assert!(is_valid_forward_transition(task.status, TaskStatus::Running));
-
- // Running can move to Review
- let task = create_test_task("Test", TaskStatus::Running);
- assert!(is_valid_forward_transition(task.status, TaskStatus::Review));
-
- // Review can move to Done
- let task = create_test_task("Test", TaskStatus::Review);
- assert!(is_valid_forward_transition(task.status, TaskStatus::Done));
-}
-
-#[test]
-fn test_invalid_forward_transitions() {
- // Cannot skip columns
- assert!(!is_valid_forward_transition(TaskStatus::Backlog, TaskStatus::Running));
- assert!(!is_valid_forward_transition(TaskStatus::Backlog, TaskStatus::Review));
- assert!(!is_valid_forward_transition(TaskStatus::Backlog, TaskStatus::Done));
- assert!(!is_valid_forward_transition(TaskStatus::Planning, TaskStatus::Review));
- assert!(!is_valid_forward_transition(TaskStatus::Planning, TaskStatus::Done));
- assert!(!is_valid_forward_transition(TaskStatus::Running, TaskStatus::Done));
-}
-
-#[test]
-fn test_done_cannot_move_forward() {
- // Done is the final state
- assert!(!is_valid_forward_transition(TaskStatus::Done, TaskStatus::Backlog));
- assert!(!is_valid_forward_transition(TaskStatus::Done, TaskStatus::Planning));
- assert!(!is_valid_forward_transition(TaskStatus::Done, TaskStatus::Running));
- assert!(!is_valid_forward_transition(TaskStatus::Done, TaskStatus::Review));
-}
-
-#[test]
-fn test_review_can_resume_to_running() {
- // Review β†’ Running is the only valid backward transition (resume)
- assert!(is_valid_resume_transition(TaskStatus::Review, TaskStatus::Running));
-}
-
-#[test]
-fn test_invalid_backward_transitions() {
- // Cannot move backward except Review β†’ Running
- assert!(!is_valid_resume_transition(TaskStatus::Done, TaskStatus::Review));
- assert!(!is_valid_resume_transition(TaskStatus::Running, TaskStatus::Planning));
- assert!(!is_valid_resume_transition(TaskStatus::Planning, TaskStatus::Backlog));
-}
-
-#[test]
-fn test_next_status() {
- assert_eq!(next_status(TaskStatus::Backlog), Some(TaskStatus::Planning));
- assert_eq!(next_status(TaskStatus::Planning), Some(TaskStatus::Running));
- assert_eq!(next_status(TaskStatus::Running), Some(TaskStatus::Review));
- assert_eq!(next_status(TaskStatus::Review), Some(TaskStatus::Done));
- assert_eq!(next_status(TaskStatus::Done), None);
-}
-
-#[test]
-fn test_column_indices() {
- let columns = TaskStatus::columns();
-
- assert_eq!(columns[0], TaskStatus::Backlog);
- assert_eq!(columns[1], TaskStatus::Planning);
- assert_eq!(columns[2], TaskStatus::Running);
- assert_eq!(columns[3], TaskStatus::Review);
- assert_eq!(columns[4], TaskStatus::Done);
-}
-
-#[test]
-fn test_task_status_preserves_through_transitions() {
- let mut task = create_test_task("My Feature", TaskStatus::Backlog);
-
- // Simulate workflow
- task.status = TaskStatus::Planning;
- assert_eq!(task.status, TaskStatus::Planning);
- assert_eq!(task.title, "My Feature"); // Other fields preserved
-
- task.status = TaskStatus::Running;
- assert_eq!(task.status, TaskStatus::Running);
-
- task.status = TaskStatus::Review;
- assert_eq!(task.status, TaskStatus::Review);
-
- // Resume back to Running
- task.status = TaskStatus::Running;
- assert_eq!(task.status, TaskStatus::Running);
-
- task.status = TaskStatus::Review;
- task.status = TaskStatus::Done;
- assert_eq!(task.status, TaskStatus::Done);
-}
-
-// === Helper functions that mirror the app logic ===
-
-/// Check if moving forward one step is valid
-fn is_valid_forward_transition(from: TaskStatus, to: TaskStatus) -> bool {
- next_status(from) == Some(to)
-}
-
-/// Check if resume transition is valid (only Review β†’ Running)
-fn is_valid_resume_transition(from: TaskStatus, to: TaskStatus) -> bool {
- from == TaskStatus::Review && to == TaskStatus::Running
-}
-
-/// Get the next status in the workflow
-fn next_status(status: TaskStatus) -> Option<TaskStatus> {
- match status {
- TaskStatus::Backlog => Some(TaskStatus::Planning),
- TaskStatus::Planning => Some(TaskStatus::Running),
- TaskStatus::Running => Some(TaskStatus::Review),
- TaskStatus::Review => Some(TaskStatus::Done),
- TaskStatus::Done => None,
- }
-}