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.

Fixed git worktree bug + rustfmt (#49)

tvarsis53a6d68f16a5
diff --git a/src/agent/mod.rs b/src/agent/mod.rs
index b92d534..822bf1f 100644
--- a/src/agent/mod.rs
+++ b/src/agent/mod.rs
@@ -65,12 +65,42 @@ impl Agent {
/// Get the list of known agents
pub fn known_agents() -> Vec<Agent> {
vec![
- Agent::new("claude", "claude", "Anthropic's Claude Code CLI", "Claude <[email protected]>"),
- Agent::new("codex", "codex", "OpenAI's Codex CLI", "Codex <[email protected]>"),
- Agent::new("copilot", "copilot", "GitHub Copilot CLI", "GitHub Copilot <[email protected]>"),
- Agent::new("gemini", "gemini", "Google Gemini CLI", "Gemini <[email protected]>"),
- Agent::new("opencode", "opencode", "AI-powered coding assistant", "OpenCode <[email protected]>"),
- Agent::new("cursor", "agent", "Cursor Agent CLI", "Cursor Agent <[email protected]>"),
+ Agent::new(
+ "claude",
+ "claude",
+ "Anthropic's Claude Code CLI",
+ "Claude <[email protected]>",
+ ),
+ Agent::new(
+ "codex",
+ "codex",
+ "OpenAI's Codex CLI",
+ "Codex <[email protected]>",
+ ),
+ Agent::new(
+ "copilot",
+ "copilot",
+ "GitHub Copilot CLI",
+ "GitHub Copilot <[email protected]>",
+ ),
+ Agent::new(
+ "gemini",
+ "gemini",
+ "Google Gemini CLI",
+ "Gemini <[email protected]>",
+ ),
+ Agent::new(
+ "opencode",
+ "opencode",
+ "AI-powered coding assistant",
+ "OpenCode <[email protected]>",
+ ),
+ Agent::new(
+ "cursor",
+ "agent",
+ "Cursor Agent CLI",
+ "Cursor Agent <[email protected]>",
+ ),
// TODO: investigate CLI usage before enabling
// Agent::new("aider", "aider", "AI pair programming in your terminal", "Aider <[email protected]>"),
// Agent::new("cline", "cline", "AI coding assistant for VS Code", "Cline <[email protected]>"),
@@ -124,7 +154,6 @@ pub fn parse_agent_selection(input: &str, agent_count: usize) -> Option<usize> {
None
}
-
/// Build the command arguments for spawning an agent
pub fn build_spawn_args(agent: &Agent, prompt: &str, task_id: &str) -> Vec<String> {
let mut args = agent.args.clone();
diff --git a/src/agent/operations.rs b/src/agent/operations.rs
index f0b0324..3a4cab0 100644
--- a/src/agent/operations.rs
+++ b/src/agent/operations.rs
@@ -139,14 +139,11 @@ impl RealAgentRegistry {
impl AgentRegistry for RealAgentRegistry {
fn get(&self, agent_name: &str) -> Arc<dyn AgentOperations> {
- self.agents
- .get(agent_name)
- .cloned()
- .unwrap_or_else(|| {
- self.agents
- .get(&self.default_name)
- .cloned()
- .expect("Default agent must exist in registry")
- })
+ self.agents.get(agent_name).cloned().unwrap_or_else(|| {
+ self.agents
+ .get(&self.default_name)
+ .cloned()
+ .expect("Default agent must exist in registry")
+ })
}
}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index beab35d..25c4a42 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -243,7 +243,10 @@ impl GlobalConfig {
/// Always uses ~/.config/agtx/ on all platforms
pub fn config_path() -> Result<PathBuf> {
let home = std::env::var("HOME").context("Could not determine home directory")?;
- Ok(PathBuf::from(home).join(".config").join("agtx").join("config.toml"))
+ Ok(PathBuf::from(home)
+ .join(".config")
+ .join("agtx")
+ .join("config.toml"))
}
/// Get the path to the global data directory
@@ -506,15 +509,18 @@ impl WorkflowPlugin {
/// Check if the given agent is supported by this plugin.
/// Returns true if supported_agents is empty (all agents allowed) or contains the agent.
pub fn supports_agent(&self, agent_name: &str) -> bool {
- self.supported_agents.is_empty()
- || self.supported_agents.iter().any(|a| a == agent_name)
+ self.supported_agents.is_empty() || self.supported_agents.iter().any(|a| a == agent_name)
}
/// Load a plugin by name, checking project-local then global directories
pub fn load(name: &str, project_path: Option<&Path>) -> Result<Self> {
// 1. Check project-local
if let Some(pp) = project_path {
- let local_path = pp.join(".agtx").join("plugins").join(name).join("plugin.toml");
+ let local_path = pp
+ .join(".agtx")
+ .join("plugins")
+ .join(name)
+ .join("plugin.toml");
if local_path.exists() {
let content = std::fs::read_to_string(&local_path)?;
return toml::from_str(&content).context("Failed to parse plugin.toml");
diff --git a/src/db/models.rs b/src/db/models.rs
index 41ea0e7..76b1e4d 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -77,7 +77,11 @@ pub struct Task {
}
impl Task {
- pub fn new(title: impl Into<String>, agent: impl Into<String>, project_id: impl Into<String>) -> Self {
+ pub fn new(
+ title: impl Into<String>,
+ agent: impl Into<String>,
+ project_id: impl Into<String>,
+ ) -> Self {
let id = uuid::Uuid::new_v4().to_string();
let now = Utc::now();
Self {
@@ -103,7 +107,10 @@ impl Task {
/// Returns the task description if present, otherwise the title.
pub fn content_text(&self) -> String {
- self.description.as_deref().unwrap_or(&self.title).to_string()
+ self.description
+ .as_deref()
+ .unwrap_or(&self.title)
+ .to_string()
}
/// Generate tmux session name: task-{id}--{project}--{slug}
diff --git a/src/db/schema.rs b/src/db/schema.rs
index 90dba51..81d1fde 100644
--- a/src/db/schema.rs
+++ b/src/db/schema.rs
@@ -110,13 +110,28 @@ impl Database {
)?;
// Migration: add new columns if they don't exist
- let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN branch_name TEXT", []);
- let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN pr_number INTEGER", []);
- let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN pr_url TEXT", []);
- let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN plugin TEXT", []);
- let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN cycle INTEGER NOT NULL DEFAULT 1", []);
- let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN referenced_tasks TEXT", []);
- let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN escalation_note TEXT", []);
+ let _ = self
+ .conn
+ .execute("ALTER TABLE tasks ADD COLUMN branch_name TEXT", []);
+ let _ = self
+ .conn
+ .execute("ALTER TABLE tasks ADD COLUMN pr_number INTEGER", []);
+ let _ = self
+ .conn
+ .execute("ALTER TABLE tasks ADD COLUMN pr_url TEXT", []);
+ let _ = self
+ .conn
+ .execute("ALTER TABLE tasks ADD COLUMN plugin TEXT", []);
+ let _ = self.conn.execute(
+ "ALTER TABLE tasks ADD COLUMN cycle INTEGER NOT NULL DEFAULT 1",
+ [],
+ );
+ let _ = self
+ .conn
+ .execute("ALTER TABLE tasks ADD COLUMN referenced_tasks TEXT", []);
+ let _ = self
+ .conn
+ .execute("ALTER TABLE tasks ADD COLUMN escalation_note TEXT", []);
// MCP transition request queue
self.conn.execute_batch(
@@ -139,7 +154,9 @@ impl Database {
)?;
// Migration: add reason column to transition_requests if it doesn't exist
- let _ = self.conn.execute("ALTER TABLE transition_requests ADD COLUMN reason TEXT", []);
+ let _ = self
+ .conn
+ .execute("ALTER TABLE transition_requests ADD COLUMN reason TEXT", []);
Ok(())
}
@@ -278,13 +295,9 @@ impl Database {
}
pub fn get_task(&self, task_id: &str) -> Result<Option<Task>> {
- let mut stmt = self
- .conn
- .prepare("SELECT * FROM tasks WHERE id = ?1")?;
+ let mut stmt = self.conn.prepare("SELECT * FROM tasks WHERE id = ?1")?;
- let task = stmt
- .query_row(params![task_id], Self::task_from_row)
- .ok();
+ let task = stmt.query_row(params![task_id], Self::task_from_row).ok();
Ok(task)
}
@@ -440,13 +453,11 @@ impl Database {
)
.map(|dt| dt.with_timezone(&chrono::Utc))
.unwrap_or_else(|_| chrono::Utc::now()),
- processed_at: row
- .get::<_, Option<String>>("processed_at")?
- .and_then(|s| {
- chrono::DateTime::parse_from_rfc3339(&s)
- .map(|dt| dt.with_timezone(&chrono::Utc))
- .ok()
- }),
+ processed_at: row.get::<_, Option<String>>("processed_at")?.and_then(|s| {
+ chrono::DateTime::parse_from_rfc3339(&s)
+ .map(|dt| dt.with_timezone(&chrono::Utc))
+ .ok()
+ }),
error: row.get("error")?,
})
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index ee2f2e1..7004457 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -33,9 +33,7 @@ pub fn repo_root(path: &Path) -> Result<std::path::PathBuf> {
.output()
.context("Failed to get git root")?;
- let root = String::from_utf8_lossy(&output.stdout)
- .trim()
- .to_string();
+ let root = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(std::path::PathBuf::from(root))
}
@@ -82,10 +80,7 @@ pub fn merge_branch(path: &Path, branch: &str, message: &str) -> Result<()> {
.context("Failed to merge branch")?;
if !output.status.success() {
- anyhow::bail!(
- "Merge failed: {}",
- String::from_utf8_lossy(&output.stderr)
- );
+ anyhow::bail!("Merge failed: {}", String::from_utf8_lossy(&output.stderr));
}
Ok(())
diff --git a/src/git/operations.rs b/src/git/operations.rs
index 34a680c..361b61d 100644
--- a/src/git/operations.rs
+++ b/src/git/operations.rs
@@ -10,7 +10,12 @@ use mockall::automock;
#[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>;
+ fn create_worktree(
+ &self,
+ project_path: &Path,
+ task_slug: &str,
+ base_branch: &str,
+ ) -> Result<String>;
/// Remove a worktree
fn remove_worktree(&self, project_path: &Path, worktree_path: &str) -> Result<()>;
@@ -72,8 +77,13 @@ pub trait GitOperations: Send + Sync {
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)?;
+ fn create_worktree(
+ &self,
+ project_path: &Path,
+ task_slug: &str,
+ base_branch: &str,
+ ) -> Result<String> {
+ let path = super::create_worktree_from_base(project_path, task_slug, base_branch)?;
Ok(path.to_string_lossy().to_string())
}
@@ -251,6 +261,12 @@ impl GitOperations for RealGitOps {
init_script: Option<String>,
copy_dirs: Vec<String>,
) -> Vec<String> {
- super::initialize_worktree(project_path, worktree_path, copy_files.as_deref(), init_script.as_deref(), &copy_dirs)
+ super::initialize_worktree(
+ project_path,
+ worktree_path,
+ copy_files.as_deref(),
+ init_script.as_deref(),
+ &copy_dirs,
+ )
}
}
diff --git a/src/git/provider.rs b/src/git/provider.rs
index 062d273..856f34f 100644
--- a/src/git/provider.rs
+++ b/src/git/provider.rs
@@ -71,10 +71,14 @@ impl GitProviderOperations for RealGitHubOps {
let output = std::process::Command::new("gh")
.current_dir(project_path)
.args([
- "pr", "create",
- "--title", title,
- "--body", body,
- "--head", head_branch,
+ "pr",
+ "create",
+ "--title",
+ title,
+ "--body",
+ body,
+ "--head",
+ head_branch,
])
.output()?;
diff --git a/src/git/worktree.rs b/src/git/worktree.rs
index a6c7d7d..4d662e0 100644
--- a/src/git/worktree.rs
+++ b/src/git/worktree.rs
@@ -6,8 +6,18 @@ use std::process::Command;
const AGTX_DIR: &str = ".agtx";
const WORKTREES_DIR: &str = "worktrees";
-/// Create a new git worktree for a task from the main branch
+/// Create a new git worktree for a task from the detected default branch.
pub fn create_worktree(project_path: &Path, task_slug: &str) -> Result<PathBuf> {
+ let base_branch = detect_main_branch(project_path)?;
+ create_worktree_from_base(project_path, task_slug, &base_branch)
+}
+
+/// Create a new git worktree for a task from the specified base branch.
+pub fn create_worktree_from_base(
+ project_path: &Path,
+ task_slug: &str,
+ base_branch: &str,
+) -> Result<PathBuf> {
let worktree_path = project_path
.join(AGTX_DIR)
.join(WORKTREES_DIR)
@@ -28,10 +38,9 @@ pub fn create_worktree(project_path: &Path, task_slug: &str) -> Result<PathBuf>
std::fs::create_dir_all(parent)?;
}
- // Detect the main branch (main or master)
- let main_branch = detect_main_branch(project_path)?;
+ let base_branch = resolve_base_branch(project_path, base_branch)?;
- // Create worktree with a new branch based on main
+ // Create worktree with a new branch based on the requested base branch
let branch_name = format!("task/{}", task_slug);
// First, try to delete the branch if it exists (from a previous failed attempt)
@@ -44,7 +53,7 @@ pub fn create_worktree(project_path: &Path, task_slug: &str) -> Result<PathBuf>
.current_dir(project_path)
.args(["worktree", "add"])
.arg(&worktree_path)
- .args(["-b", &branch_name, &main_branch])
+ .args(["-b", &branch_name, &base_branch])
.output()
.context("Failed to create git worktree")?;
@@ -56,6 +65,25 @@ pub fn create_worktree(project_path: &Path, task_slug: &str) -> Result<PathBuf>
Ok(worktree_path)
}
+fn resolve_base_branch(project_path: &Path, base_branch: &str) -> Result<String> {
+ let base_branch = base_branch.trim();
+ if base_branch.is_empty() {
+ return detect_main_branch(project_path);
+ }
+
+ let output = Command::new("git")
+ .current_dir(project_path)
+ .args(["rev-parse", "--verify", base_branch])
+ .output()
+ .context("Failed to verify configured base branch")?;
+
+ if output.status.success() {
+ Ok(base_branch.to_string())
+ } else {
+ anyhow::bail!("Configured base branch '{}' was not found", base_branch);
+ }
+}
+
/// Agent config directories that are always copied from project root to worktrees.
/// These contain commands, skills, and configuration that agents need.
pub const AGENT_CONFIG_DIRS: &[&str] = &[
@@ -121,7 +149,10 @@ pub fn initialize_worktree(
if src.is_dir() {
if let Err(e) = copy_dir_recursive(&src, &dst) {
- warnings.push(format!("Failed to copy directory '{}' to worktree: {}", file_name, e));
+ warnings.push(format!(
+ "Failed to copy directory '{}' to worktree: {}",
+ file_name, e
+ ));
}
} else {
if let Some(parent) = dst.parent() {
@@ -145,7 +176,12 @@ pub fn initialize_worktree(
if let Some(script) = init_script {
let script = script.trim();
if !script.is_empty() {
- match Command::new("sh").arg("-c").arg(script).current_dir(worktree_path).output() {
+ match Command::new("sh")
+ .arg("-c")
+ .arg(script)
+ .current_dir(worktree_path)
+ .output()
+ {
Ok(result) => {
if !result.status.success() {
let stderr = String::from_utf8_lossy(&result.stderr);
diff --git a/src/main.rs b/src/main.rs
index ab6abdb..3e1b5b4 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,4 +1,8 @@
-use agtx::{agent, config::{self, GlobalConfig}, git, tui, AppMode, FeatureFlags};
+use agtx::{
+ agent,
+ config::{self, GlobalConfig},
+ git, tui, AppMode, FeatureFlags,
+};
use anyhow::Result;
use crossterm::{
cursor,
@@ -16,7 +20,8 @@ async fn main() -> Result<()> {
// Extract flags (--experimental) from any position
let experimental = args.iter().any(|a| a == "--experimental");
- let positional_args: Vec<&str> = args.iter()
+ let positional_args: Vec<&str> = args
+ .iter()
.skip(1)
.filter(|a| !a.starts_with("--"))
.map(|s| s.as_str())
@@ -117,18 +122,30 @@ fn prompt_agent_selection(agents: &[agent::Agent]) -> Result<&agent::Agent> {
stdout.execute(cursor::Hide)?;
// Print ASCII art banner
- let gold = style::Color::Rgb { r: 234, g: 212, b: 154 }; // #ead49a
+ let gold = style::Color::Rgb {
+ r: 234,
+ g: 212,
+ b: 154,
+ }; // #ead49a
let banner: &[(&str, &str)] = &[
(" β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—", ""),
("β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•", ""),
- ("β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ•”β• ", " Autonomous multi-session spec-driven"),
- ("β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— ", " AI coding orchestration in the terminal"),
+ (
+ "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ•”β• ",
+ " Autonomous multi-session spec-driven",
+ ),
+ (
+ "β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— ",
+ " AI coding orchestration in the terminal",
+ ),
("β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•—", ""),
("β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β• β•šβ•β•", ""),
];
stdout.execute(style::Print("\r\n"))?;
for (art, tagline) in banner {
- stdout.execute(style::PrintStyledContent(style::style(format!(" {}", art)).with(gold)))?;
+ stdout.execute(style::PrintStyledContent(
+ style::style(format!(" {}", art)).with(gold),
+ ))?;
if !tagline.is_empty() {
stdout.execute(style::PrintStyledContent((*tagline).dark_grey()))?;
}
@@ -136,7 +153,9 @@ fn prompt_agent_selection(agents: &[agent::Agent]) -> Result<&agent::Agent> {
}
stdout.execute(style::Print("\r\n"))?;
stdout.execute(style::Print(" Select your default coding agent "))?;
- stdout.execute(style::PrintStyledContent("(can be changed later via config)\r\n\r\n".dark_grey()))?;
+ stdout.execute(style::PrintStyledContent(
+ "(can be changed later via config)\r\n\r\n".dark_grey(),
+ ))?;
// Draw the list
let draw = |stdout: &mut io::Stdout, selected: usize| -> Result<()> {
@@ -179,9 +198,7 @@ fn prompt_agent_selection(agents: &[agent::Agent]) -> Result<&agent::Agent> {
KeyCode::Esc | KeyCode::Char('q') => {
break Err(anyhow::anyhow!("Selection cancelled"));
}
- KeyCode::Char('c')
- if key.modifiers.contains(event::KeyModifiers::CONTROL) =>
- {
+ KeyCode::Char('c') if key.modifiers.contains(event::KeyModifiers::CONTROL) => {
break Err(anyhow::anyhow!("Selection cancelled"));
}
_ => continue,
diff --git a/src/mcp/server.rs b/src/mcp/server.rs
index 13d02ac..bd66a01 100644
--- a/src/mcp/server.rs
+++ b/src/mcp/server.rs
@@ -2,12 +2,11 @@ use std::path::PathBuf;
use std::process::Command;
use rmcp::{
- ServerHandler, ServiceExt,
handler::server::{router::tool::ToolRouter, wrapper::Parameters},
model::{ServerCapabilities, ServerInfo},
- schemars,
- tool, tool_handler, tool_router,
+ schemars, tool, tool_handler, tool_router,
transport::io::stdio,
+ ServerHandler, ServiceExt,
};
use serde::{Deserialize, Serialize};
@@ -199,7 +198,8 @@ impl AgtxMcpServer {
}
fn open_project_db(&self) -> Result<Database, String> {
- Database::open_project(&self.project_path).map_err(|e| format!("Failed to open project database: {}", e))
+ Database::open_project(&self.project_path)
+ .map_err(|e| format!("Failed to open project database: {}", e))
}
fn open_global_db(&self) -> Result<Database, String> {
@@ -255,7 +255,8 @@ impl AgtxMcpServer {
path: p.path,
})
.collect();
- serde_json::to_string_pretty(&summaries).unwrap_or_else(|e| format!("Error serializing: {}", e))
+ serde_json::to_string_pretty(&summaries)
+ .unwrap_or_else(|e| format!("Error serializing: {}", e))
}
Err(e) => format!("Error listing projects: {}", e),
},
@@ -263,7 +264,9 @@ impl AgtxMcpServer {
}
}
- #[tool(description = "List tasks for the current project, optionally filtered by status (backlog, planning, running, review, done)")]
+ #[tool(
+ description = "List tasks for the current project, optionally filtered by status (backlog, planning, running, review, done)"
+ )]
fn list_tasks(&self, Parameters(params): Parameters<ListTasksParams>) -> String {
match self.open_project_db() {
Ok(db) => {
@@ -290,7 +293,8 @@ impl AgtxMcpServer {
plugin: t.plugin,
})
.collect();
- serde_json::to_string_pretty(&summaries).unwrap_or_else(|e| format!("Error serializing: {}", e))
+ serde_json::to_string_pretty(&summaries)
+ .unwrap_or_else(|e| format!("Error serializing: {}", e))
}
Err(e) => format!("Error listing tasks: {}", e),
}
@@ -299,7 +303,9 @@ impl AgtxMcpServer {
}
}
- #[tool(description = "Get full details of a specific task by its ID. Includes allowed_actions based on the task's current status and plugin rules.")]
+ #[tool(
+ description = "Get full details of a specific task by its ID. Includes allowed_actions based on the task's current status and plugin rules."
+ )]
fn get_task(&self, Parameters(params): Parameters<GetTaskParams>) -> String {
match self.open_project_db() {
Ok(db) => match db.get_task(&params.task_id) {
@@ -323,7 +329,8 @@ impl AgtxMcpServer {
updated_at: t.updated_at.to_rfc3339(),
allowed_actions: allowed,
};
- serde_json::to_string_pretty(&detail).unwrap_or_else(|e| format!("Error serializing: {}", e))
+ serde_json::to_string_pretty(&detail)
+ .unwrap_or_else(|e| format!("Error serializing: {}", e))
}
Ok(None) => format!("Task not found: {}", params.task_id),
Err(e) => format!("Error getting task: {}", e),
@@ -332,7 +339,9 @@ impl AgtxMcpServer {
}
}
- #[tool(description = "Queue a task state transition. The agtx TUI will process it and execute all side effects (worktree creation, agent spawning, etc). Use get_transition_status to check completion. Actions: research (start research phase for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume, escalate_to_user (flag task for user attention with an optional reason)")]
+ #[tool(
+ description = "Queue a task state transition. The agtx TUI will process it and execute all side effects (worktree creation, agent spawning, etc). Use get_transition_status to check completion. Actions: research (start research phase for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume, escalate_to_user (flag task for user attention with an optional reason)"
+ )]
fn move_task(&self, Parameters(params): Parameters<MoveTaskParams>) -> String {
let valid_actions = [
"research",
@@ -384,7 +393,9 @@ impl AgtxMcpServer {
}
}
- #[tool(description = "Check the status of a queued transition request. Returns pending, completed, or error with details.")]
+ #[tool(
+ description = "Check the status of a queued transition request. Returns pending, completed, or error with details."
+ )]
fn get_transition_status(
&self,
Parameters(params): Parameters<GetTransitionStatusParams>,
@@ -416,7 +427,9 @@ impl AgtxMcpServer {
}
}
- #[tool(description = "Check if task branches have merge conflicts with the main branch. Pass a task_id to check one task, or omit it to check all Review tasks. Uses a read-only git check β€” no files are modified.")]
+ #[tool(
+ description = "Check if task branches have merge conflicts with the main branch. Pass a task_id to check one task, or omit it to check all Review tasks. Uses a read-only git check β€” no files are modified."
+ )]
fn check_conflicts(&self, Parameters(params): Parameters<CheckConflictsParams>) -> String {
let main_branch = match crate::git::detect_main_branch(&self.project_path) {
Ok(b) => b,
@@ -483,10 +496,13 @@ impl AgtxMcpServer {
main_branch,
results,
};
- serde_json::to_string_pretty(&response).unwrap_or_else(|e| format!("Error serializing: {}", e))
+ serde_json::to_string_pretty(&response)
+ .unwrap_or_else(|e| format!("Error serializing: {}", e))
}
- #[tool(description = "Fetch and consume pending notifications. Returns new events (task created, phase completed, etc.) and removes them from the queue. Note: notifications are also pushed to your input automatically when you are idle, so you usually don't need to call this manually.")]
+ #[tool(
+ description = "Fetch and consume pending notifications. Returns new events (task created, phase completed, etc.) and removes them from the queue. Note: notifications are also pushed to your input automatically when you are idle, so you usually don't need to call this manually."
+ )]
fn get_notifications(&self, _params: Parameters<GetNotificationsParams>) -> String {
match self.open_project_db() {
Ok(db) => match db.consume_notifications() {
@@ -510,7 +526,9 @@ impl AgtxMcpServer {
}
}
- #[tool(description = "Read the last N lines of a task's agent tmux pane. Use this to understand what the agent is showing β€” e.g., when a task has been idle for a while. Returns pane content as text.")]
+ #[tool(
+ description = "Read the last N lines of a task's agent tmux pane. Use this to understand what the agent is showing β€” e.g., when a task has been idle for a while. Returns pane content as text."
+ )]
fn read_pane_content(&self, Parameters(params): Parameters<ReadPaneParams>) -> String {
let db = match self.open_project_db() {
Ok(db) => db,
@@ -532,7 +550,16 @@ impl AgtxMcpServer {
let lines_arg = format!("-{}", lines);
let output = Command::new("tmux")
- .args(["-L", "agtx", "capture-pane", "-t", &session_name, "-p", "-S", &lines_arg])
+ .args([
+ "-L",
+ "agtx",
+ "capture-pane",
+ "-t",
+ &session_name,
+ "-p",
+ "-S",
+ &lines_arg,
+ ])
.output();
match output {
@@ -551,7 +578,9 @@ impl AgtxMcpServer {
}
}
- #[tool(description = "Send a message to a task's agent pane (followed by Enter). Only works for tasks in Planning or Running status. Use this to nudge a stuck agent, answer a CLI prompt (e.g. 'y' for yes), or provide guidance.")]
+ #[tool(
+ description = "Send a message to a task's agent pane (followed by Enter). Only works for tasks in Planning or Running status. Use this to nudge a stuck agent, answer a CLI prompt (e.g. 'y' for yes), or provide guidance."
+ )]
fn send_to_task(&self, Parameters(params): Parameters<SendToTaskParams>) -> String {
let db = match self.open_project_db() {
Ok(db) => db,
@@ -579,7 +608,14 @@ impl AgtxMcpServer {
// Send the message text
let send_text = Command::new("tmux")
- .args(["-L", "agtx", "send-keys", "-t", &session_name, &params.message])
+ .args([
+ "-L",
+ "agtx",
+ "send-keys",
+ "-t",
+ &session_name,
+ &params.message,
+ ])
.output();
if let Err(e) = send_text {
diff --git a/src/skills.rs b/src/skills.rs
index 82e7704..29bb705 100644
--- a/src/skills.rs
+++ b/src/skills.rs
@@ -62,7 +62,9 @@ pub fn skill_name_to_command(skill_name: &str) -> String {
pub fn skill_dir_to_filename(skill_dir_name: &str, agent_name: &str) -> String {
match agent_name {
"gemini" => {
- let short = skill_dir_name.strip_prefix("agtx-").unwrap_or(skill_dir_name);
+ let short = skill_dir_name
+ .strip_prefix("agtx-")
+ .unwrap_or(skill_dir_name);
format!("{}.toml", short)
}
"opencode" => {
@@ -70,7 +72,9 @@ pub fn skill_dir_to_filename(skill_dir_name: &str, agent_name: &str) -> String {
format!("{}.md", skill_dir_name)
}
_ => {
- let short = skill_dir_name.strip_prefix("agtx-").unwrap_or(skill_dir_name);
+ let short = skill_dir_name
+ .strip_prefix("agtx-")
+ .unwrap_or(skill_dir_name);
format!("{}.md", short)
}
}
@@ -199,8 +203,8 @@ pub fn enumerate_available_skills(agent_name: &str) -> Vec<(String, String)> {
Some(cmd) => cmd,
None => canonical,
};
- let description = extract_description(skill_content)
- .unwrap_or_else(|| skill_name.replace('-', " "));
+ let description =
+ extract_description(skill_content).unwrap_or_else(|| skill_name.replace('-', " "));
results.push((command, description));
}
results
@@ -239,7 +243,10 @@ fn extract_description_from_toml(path: &std::path::Path) -> Option<String> {
/// Scan the active agent's native command directory for available skills.
/// Returns `(command, description)` tuples in agent-native invocation format.
-pub fn scan_agent_skills(agent_name: &str, project_path: &std::path::Path) -> Vec<(String, String)> {
+pub fn scan_agent_skills(
+ agent_name: &str,
+ project_path: &std::path::Path,
+) -> Vec<(String, String)> {
let mut results = Vec::new();
match agent_name {
diff --git a/src/tmux/operations.rs b/src/tmux/operations.rs
index 4de33b5..0733f1c 100644
--- a/src/tmux/operations.rs
+++ b/src/tmux/operations.rs
@@ -172,7 +172,11 @@ impl TmuxOperations for RealTmuxOps {
.ok()?;
if output.status.success() {
let cmd = String::from_utf8_lossy(&output.stdout).trim().to_string();
- if !cmd.is_empty() { Some(cmd) } else { None }
+ if !cmd.is_empty() {
+ Some(cmd)
+ } else {
+ None
+ }
} else {
None
}
diff --git a/src/tui/app.rs b/src/tui/app.rs
index fde998b..40e5c69 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -8,13 +8,18 @@ use ratatui::{prelude::*, widgets::*};
use std::collections::{HashMap, HashSet};
use std::io::{self, Stdout};
use std::path::{Path, PathBuf};
-use std::sync::{atomic::{AtomicBool, Ordering}, mpsc, Arc};
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ mpsc, Arc,
+};
use std::time::Instant;
use crate::agent::{self, AgentOperations};
use crate::config::{GlobalConfig, MergedConfig, ProjectConfig, ThemeConfig, WorkflowPlugin};
use crate::db::{Database, PhaseStatus, Task, TaskStatus, TransitionRequest};
-use crate::git::{self, GitOperations, GitProviderOperations, PullRequestState, RealGitHubOps, RealGitOps};
+use crate::git::{
+ self, GitOperations, GitProviderOperations, PullRequestState, RealGitHubOps, RealGitOps,
+};
use crate::skills;
use crate::tmux::{self, RealTmuxOps, TmuxOperations};
use crate::AppMode;
@@ -31,7 +36,12 @@ fn hex_to_color(hex: &str) -> Color {
}
/// Build footer help text based on current UI state
-fn build_footer_text(input_mode: InputMode, sidebar_focused: bool, selected_column: usize, has_cyclic_plugin: bool) -> String {
+fn build_footer_text(
+ input_mode: InputMode,
+ sidebar_focused: bool,
+ selected_column: usize,
+ has_cyclic_plugin: bool,
+) -> String {
match input_mode {
InputMode::Normal => {
if sidebar_focused {
@@ -48,8 +58,13 @@ fn build_footer_text(input_mode: InputMode, sidebar_focused: bool, selected_colu
}
}
InputMode::InputTitle => " Enter task title... [Esc] cancel [Enter] next ".to_string(),
- InputMode::SelectPlugin => " [j/k] select plugin [Tab] cycle [Enter] next [Esc] cancel ".to_string(),
- InputMode::InputDescription => " [#] files [/] skills [!] tasks [Esc] cancel [\\+Enter] newline [Enter] save ".to_string(),
+ InputMode::SelectPlugin => {
+ " [j/k] select plugin [Tab] cycle [Enter] next [Esc] cancel ".to_string()
+ }
+ InputMode::InputDescription => {
+ " [#] files [/] skills [!] tasks [Esc] cancel [\\+Enter] newline [Enter] save "
+ .to_string()
+ }
}
}
@@ -72,7 +87,9 @@ impl ratatui::backend::Backend for AppBackend {
match self {
Self::Crossterm(b) => b.draw(content),
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.draw(content).map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .draw(content)
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
@@ -80,7 +97,9 @@ impl ratatui::backend::Backend for AppBackend {
match self {
Self::Crossterm(b) => b.hide_cursor(),
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.hide_cursor().map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .hide_cursor()
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
@@ -88,7 +107,9 @@ impl ratatui::backend::Backend for AppBackend {
match self {
Self::Crossterm(b) => b.show_cursor(),
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.show_cursor().map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .show_cursor()
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
@@ -96,16 +117,23 @@ impl ratatui::backend::Backend for AppBackend {
match self {
Self::Crossterm(b) => b.get_cursor_position(),
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.get_cursor_position().map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .get_cursor_position()
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
- fn set_cursor_position<P: Into<ratatui::layout::Position>>(&mut self, position: P) -> io::Result<()> {
+ fn set_cursor_position<P: Into<ratatui::layout::Position>>(
+ &mut self,
+ position: P,
+ ) -> io::Result<()> {
match self {
Self::Crossterm(b) => b.set_cursor_position(position),
// TestBackend's set_cursor_position is also generic, so just forward
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.set_cursor_position(position).map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .set_cursor_position(position)
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
@@ -113,7 +141,9 @@ impl ratatui::backend::Backend for AppBackend {
match self {
Self::Crossterm(b) => b.clear(),
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.clear().map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .clear()
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
@@ -121,7 +151,9 @@ impl ratatui::backend::Backend for AppBackend {
match self {
Self::Crossterm(b) => b.clear_region(clear_type),
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.clear_region(clear_type).map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .clear_region(clear_type)
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
@@ -129,7 +161,9 @@ impl ratatui::backend::Backend for AppBackend {
match self {
Self::Crossterm(b) => b.size(),
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.size().map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .size()
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
@@ -137,7 +171,9 @@ impl ratatui::backend::Backend for AppBackend {
match self {
Self::Crossterm(b) => b.window_size(),
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.window_size().map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .window_size()
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
@@ -145,14 +181,16 @@ impl ratatui::backend::Backend for AppBackend {
match self {
Self::Crossterm(b) => b.flush(),
#[cfg(feature = "test-mocks")]
- Self::Test(b) => b.flush().map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
+ Self::Test(b) => b
+ .flush()
+ .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
}
}
}
/// Shell popup dimensions - used for both rendering and tmux window sizing
-const SHELL_POPUP_WIDTH: u16 = 128; // Total width including borders
-const SHELL_POPUP_CONTENT_WIDTH: u16 = 126; // Content width (SHELL_POPUP_WIDTH - 2 for borders)
+const SHELL_POPUP_WIDTH: u16 = 128; // Total width including borders
+const SHELL_POPUP_CONTENT_WIDTH: u16 = 126; // Content width (SHELL_POPUP_WIDTH - 2 for borders)
const SHELL_POPUP_HEIGHT_PERCENT: u16 = 75; // Percentage of terminal height
/// Application state (separate from terminal for borrow checker)
@@ -381,14 +419,14 @@ struct FileSearchState {
matches: Vec<String>,
selected: usize,
start_pos: usize, // Position in input_buffer where trigger was typed
- trigger_char: char, // The character that triggered the search (# or @)
+ trigger_char: char, // The character that triggered the search (# or @)
}
/// A discovered skill command from an agent's native directory
#[derive(Debug, Clone)]
struct SkillEntry {
- command: String, // agent-native: "/agtx:plan" or "$agtx-plan"
- description: String, // from frontmatter or file stem
+ command: String, // agent-native: "/agtx:plan" or "$agtx-plan"
+ description: String, // from frontmatter or file stem
}
/// State for skill search dropdown (triggered by `/`)
@@ -480,7 +518,12 @@ impl App {
// Setup based on mode
let (db, project_path, project_name, project_config) = match &mode {
- AppMode::Dashboard => (None, None, "Dashboard".to_string(), ProjectConfig::default()),
+ AppMode::Dashboard => (
+ None,
+ None,
+ "Dashboard".to_string(),
+ ProjectConfig::default(),
+ ),
AppMode::Project(path) => {
let canonical = path.canonicalize().unwrap_or_else(|_| path.clone());
let name = canonical
@@ -584,14 +627,20 @@ impl App {
// Detect existing orchestrator session (survives agtx restarts)
if app.state.flags.experimental {
let orch_target = format!("{}:orchestrator", app.state.project_name);
- if app.state.tmux_ops.window_exists(&orch_target).unwrap_or(false) {
+ if app
+ .state
+ .tmux_ops
+ .window_exists(&orch_target)
+ .unwrap_or(false)
+ {
app.state.orchestrator_session = Some(orch_target);
app.state.orchestrator_ready.store(true, Ordering::Release);
// Catch up: notify orchestrator about tasks that completed while TUI was down
if let Some(ref db) = app.state.db {
// Check existing notifications to avoid duplicates
- let existing: HashSet<String> = db.peek_notifications()
+ let existing: HashSet<String> = db
+ .peek_notifications()
.unwrap_or_default()
.into_iter()
.map(|n| n.message)
@@ -602,15 +651,23 @@ impl App {
continue;
}
let plugin = match &task.plugin {
- Some(name) => WorkflowPlugin::load(name, app.state.project_path.as_deref()).ok(),
+ Some(name) => {
+ WorkflowPlugin::load(name, app.state.project_path.as_deref()).ok()
+ }
None => skills::load_bundled_plugin("agtx"),
};
if let Some(ref wt) = task.worktree_path {
if phase_artifact_exists(wt, task.status, &plugin, task.cycle) {
- let short_id = if task.id.len() >= 8 { &task.id[..8] } else { &task.id };
+ let short_id = if task.id.len() >= 8 {
+ &task.id[..8]
+ } else {
+ &task.id
+ };
let message = format!(
"Task \"{}\" ({}) completed phase: {}",
- task.title, short_id, task.status.as_str()
+ task.title,
+ short_id,
+ task.status.as_str()
);
if !existing.contains(&message) {
let notif = crate::db::Notification::new(message);
@@ -801,7 +858,11 @@ 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, self.state.tmux_ops.as_ref());
+ popup.cached_content = capture_tmux_pane_with_history(
+ &popup.window_name,
+ 500,
+ self.state.tmux_ops.as_ref(),
+ );
}
// Apply results from background session refresh (non-blocking)
@@ -890,27 +951,42 @@ impl App {
// Header
let plugin_label = state.config.workflow_plugin.as_deref().unwrap_or("agtx");
- let left = Span::styled(format!(" {} ", state.project_name), Style::default().fg(Color::Cyan).bold());
+ let left = Span::styled(
+ format!(" {} ", state.project_name),
+ Style::default().fg(Color::Cyan).bold(),
+ );
let mut right_spans: Vec<Span> = Vec::new();
if state.flags.experimental {
let orch_active = state.orchestrator_session.is_some();
if orch_active {
right_spans.push(Span::styled("● ", Style::default().fg(Color::Green)));
- right_spans.push(Span::styled("orchestrator ", Style::default().fg(Color::Green)));
+ right_spans.push(Span::styled(
+ "orchestrator ",
+ Style::default().fg(Color::Green),
+ ));
}
- right_spans.push(Span::styled("[O] ", Style::default().fg(hex_to_color(&state.config.theme.color_dimmed))));
+ right_spans.push(Span::styled(
+ "[O] ",
+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)),
+ ));
}
right_spans.extend([
- Span::styled(format!("{} ", plugin_label), Style::default().fg(hex_to_color(&state.config.theme.color_accent))),
- Span::styled("[P] ", Style::default().fg(hex_to_color(&state.config.theme.color_dimmed))),
+ Span::styled(
+ format!("{} ", plugin_label),
+ Style::default().fg(hex_to_color(&state.config.theme.color_accent)),
+ ),
+ Span::styled(
+ "[P] ",
+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)),
+ ),
]);
let left_len = state.project_name.len() + 2;
let right_len: usize = right_spans.iter().map(|s| s.content.len()).sum();
let padding = (chunks[0].width as usize).saturating_sub(left_len + right_len + 2); // 2 for borders
let mut spans = vec![left, Span::raw(" ".repeat(padding))];
spans.extend(right_spans);
- let header = Paragraph::new(Line::from(spans))
- .block(Block::default().borders(Borders::ALL));
+ let header =
+ Paragraph::new(Line::from(spans)).block(Block::default().borders(Borders::ALL));
frame.render_widget(header, chunks[0]);
// Board columns (5 columns: Backlog, Planning, Running, Review, Done)
@@ -926,7 +1002,12 @@ impl App {
.split(chunks[1]);
for (i, status) in TaskStatus::columns().iter().enumerate() {
- let tasks: Vec<&Task> = state.board.tasks.iter().filter(|t| t.status == *status).collect();
+ let tasks: Vec<&Task> = state
+ .board
+ .tasks
+ .iter()
+ .filter(|t| t.status == *status)
+ .collect();
let is_selected_column = state.board.selected_column == i;
@@ -977,7 +1058,11 @@ impl App {
frame.render_widget(column_block, columns[i]);
// Render task cards with scroll offset
- let visible_tasks: Vec<_> = tasks.iter().skip(scroll_offset).take(max_visible_cards).collect();
+ let visible_tasks: Vec<_> = tasks
+ .iter()
+ .skip(scroll_offset)
+ .take(max_visible_cards)
+ .collect();
for (j, task) in visible_tasks.iter().enumerate() {
let actual_index = scroll_offset + j;
let is_selected = is_selected_column && state.board.selected_row == actual_index;
@@ -985,15 +1070,28 @@ impl App {
let card_area = Rect {
x: inner_area.x,
y: inner_area.y + (j as u16 * card_height),
- width: if needs_scrollbar { inner_area.width.saturating_sub(1) } else { inner_area.width },
- height: card_height.min(inner_area.height.saturating_sub(j as u16 * card_height)),
+ width: if needs_scrollbar {
+ inner_area.width.saturating_sub(1)
+ } else {
+ inner_area.width
+ },
+ height: card_height
+ .min(inner_area.height.saturating_sub(j as u16 * card_height)),
};
if card_area.height < 3 {
break;
}
- Self::draw_task_card(frame, task, card_area, is_selected, &state.config.theme, state.phase_status_cache.get(&task.id), state.spinner_frame);
+ Self::draw_task_card(
+ frame,
+ task,
+ card_area,
+ is_selected,
+ &state.config.theme,
+ state.phase_status_cache.get(&task.id),
+ state.spinner_frame,
+ );
}
// Draw scrollbar if needed
@@ -1008,7 +1106,8 @@ impl App {
let total_tasks = tasks.len();
let scrollbar_height = inner_area.height as usize;
let thumb_height = (max_visible_cards * scrollbar_height / total_tasks).max(1);
- let thumb_pos = (scroll_offset * scrollbar_height / total_tasks).min(scrollbar_height - thumb_height);
+ let thumb_pos = (scroll_offset * scrollbar_height / total_tasks)
+ .min(scrollbar_height - thumb_height);
for y in 0..scrollbar_height {
let char = if y >= thumb_pos && y < thumb_pos + thumb_height {
@@ -1031,7 +1130,9 @@ impl App {
}
// Footer with help (or transient warning)
- let has_cyclic_plugin = state.board.selected_task()
+ let has_cyclic_plugin = state
+ .board
+ .selected_task()
.and_then(|t| t.plugin.as_ref())
.and_then(|name| WorkflowPlugin::load(name, state.project_path.as_deref()).ok())
.map_or(false, |p| p.cyclic);
@@ -1039,12 +1140,26 @@ impl App {
if created.elapsed() < std::time::Duration::from_secs(5) {
(msg.clone(), Style::default().fg(Color::Yellow))
} else {
- (build_footer_text(state.input_mode, state.sidebar_focused, state.board.selected_column, has_cyclic_plugin),
- Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)))
+ (
+ build_footer_text(
+ state.input_mode,
+ state.sidebar_focused,
+ state.board.selected_column,
+ has_cyclic_plugin,
+ ),
+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)),
+ )
}
} else {
- (build_footer_text(state.input_mode, state.sidebar_focused, state.board.selected_column, has_cyclic_plugin),
- Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)))
+ (
+ build_footer_text(
+ state.input_mode,
+ state.sidebar_focused,
+ state.board.selected_column,
+ has_cyclic_plugin,
+ ),
+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)),
+ )
};
let footer = Paragraph::new(footer_text.as_str())
@@ -1053,12 +1168,19 @@ impl App {
frame.render_widget(footer, chunks[2]);
// Input overlay if in input mode
- if matches!(state.input_mode, InputMode::InputTitle | InputMode::SelectPlugin | InputMode::InputDescription) {
+ if matches!(
+ state.input_mode,
+ InputMode::InputTitle | InputMode::SelectPlugin | InputMode::InputDescription
+ ) {
let input_area = centered_rect(55, 55, area);
frame.render_widget(Clear, input_area);
let is_editing = state.editing_task_id.is_some();
- let block_title = if is_editing { " Edit Task " } else { " New Task " };
+ let block_title = if is_editing {
+ " Edit Task "
+ } else {
+ " New Task "
+ };
let text_color = hex_to_color(&state.config.theme.color_text);
let highlight_color = hex_to_color(&state.config.theme.color_accent);
let dimmed_color = hex_to_color(&state.config.theme.color_dimmed);
@@ -1081,7 +1203,9 @@ impl App {
breadcrumb_spans.push(Span::raw(" "));
for (i, label) in step_labels.iter().enumerate() {
let style = if i == step {
- Style::default().fg(selected_color).add_modifier(Modifier::BOLD)
+ Style::default()
+ .fg(selected_color)
+ .add_modifier(Modifier::BOLD)
} else if i < step {
Style::default().fg(highlight_color)
} else {
@@ -1110,7 +1234,8 @@ impl App {
]));
}
if step >= 2 {
- let plugin_name = state.wizard_plugin_options
+ let plugin_name = state
+ .wizard_plugin_options
.get(state.wizard_selected_plugin)
.map(|o| o.label.as_str())
.unwrap_or("agtx");
@@ -1119,16 +1244,23 @@ impl App {
Span::styled(plugin_name, Style::default().fg(text_color)),
]));
}
- if step >= 1 { lines.push(Line::from("")); }
+ if step >= 1 {
+ lines.push(Line::from(""));
+ }
// Active area content
match state.input_mode {
InputMode::InputTitle => {
- let (before_cursor, after_cursor) = state.input_buffer.split_at(
- state.input_cursor.min(state.input_buffer.len())
- );
+ let (before_cursor, after_cursor) = state
+ .input_buffer
+ .split_at(state.input_cursor.min(state.input_buffer.len()));
lines.push(Line::from(vec![
- Span::styled(" Title: ", Style::default().fg(selected_color).add_modifier(Modifier::BOLD)),
+ Span::styled(
+ " Title: ",
+ Style::default()
+ .fg(selected_color)
+ .add_modifier(Modifier::BOLD),
+ ),
Span::styled(before_cursor, Style::default().fg(text_color)),
Span::styled("β–ˆ", Style::default().fg(selected_color)),
Span::styled(after_cursor, Style::default().fg(text_color)),
@@ -1143,7 +1275,9 @@ impl App {
|| opt.name == active_plugin;
let check = if is_project_default { " βœ“" } else { "" };
let name_style = if is_sel {
- Style::default().fg(selected_color).add_modifier(Modifier::BOLD)
+ Style::default()
+ .fg(selected_color)
+ .add_modifier(Modifier::BOLD)
} else {
Style::default().fg(text_color)
};
@@ -1156,22 +1290,32 @@ impl App {
}
}
InputMode::InputDescription => {
- let (before_cursor, after_cursor) = state.input_buffer.split_at(
- state.input_cursor.min(state.input_buffer.len())
- );
+ let (before_cursor, after_cursor) = state
+ .input_buffer
+ .split_at(state.input_cursor.min(state.input_buffer.len()));
let full_text = format!(" Prompt: {}β–ˆ{}", before_cursor, after_cursor);
// Split on newlines to handle multi-line descriptions
for part in full_text.split('\n') {
if !state.highlighted_references.is_empty() {
- let styled = build_highlighted_text(part, &state.highlighted_references, text_color, highlight_color);
+ let styled = build_highlighted_text(
+ part,
+ &state.highlighted_references,
+ text_color,
+ highlight_color,
+ );
for line in styled.lines {
- let owned_spans: Vec<Span<'static>> = line.spans.into_iter()
+ let owned_spans: Vec<Span<'static>> = line
+ .spans
+ .into_iter()
.map(|s| Span::styled(s.content.into_owned(), s.style))
.collect();
lines.push(Line::from(owned_spans));
}
} else {
- lines.push(Line::from(Span::styled(part.to_string(), Style::default().fg(text_color))));
+ lines.push(Line::from(Span::styled(
+ part.to_string(),
+ Style::default().fg(text_color),
+ )));
}
}
}
@@ -1201,13 +1345,22 @@ impl App {
width: input_area.width.saturating_sub(4),
height: dropdown_height,
};
- let dropdown_area = if dropdown_area.y + dropdown_area.height > area.height {
- Rect { y: input_area.y.saturating_sub(dropdown_height), ..dropdown_area }
- } else { dropdown_area };
+ let dropdown_area = if dropdown_area.y + dropdown_area.height > area.height
+ {
+ Rect {
+ y: input_area.y.saturating_sub(dropdown_height),
+ ..dropdown_area
+ }
+ } else {
+ dropdown_area
+ };
frame.render_widget(Clear, dropdown_area);
let file_selected_color = hex_to_color(&state.config.theme.color_selected);
- let items: Vec<ListItem> = search.matches.iter().enumerate()
+ let items: Vec<ListItem> = search
+ .matches
+ .iter()
+ .enumerate()
.map(|(i, path)| {
let style = if i == search.selected {
Style::default().bg(file_selected_color).fg(Color::Black)
@@ -1215,7 +1368,8 @@ impl App {
Style::default().fg(Color::White)
};
ListItem::new(format!(" {} ", path)).style(style)
- }).collect();
+ })
+ .collect();
let list = List::new(items).block(
Block::default()
.title(" Files [↑↓] select [Tab/Enter] insert [Esc] cancel ")
@@ -1236,28 +1390,43 @@ impl App {
width: input_area.width.saturating_sub(4),
height: dropdown_height,
};
- let dropdown_area = if dropdown_area.y + dropdown_area.height > area.height {
- Rect { y: input_area.y.saturating_sub(dropdown_height), ..dropdown_area }
- } else { dropdown_area };
+ let dropdown_area = if dropdown_area.y + dropdown_area.height > area.height
+ {
+ Rect {
+ y: input_area.y.saturating_sub(dropdown_height),
+ ..dropdown_area
+ }
+ } else {
+ dropdown_area
+ };
frame.render_widget(Clear, dropdown_area);
let skill_sel_color = hex_to_color(&state.config.theme.color_selected);
let accent = hex_to_color(&state.config.theme.color_accent);
let dim = hex_to_color(&state.config.theme.color_dimmed);
- let items: Vec<ListItem> = search.matches.iter().enumerate()
+ let items: Vec<ListItem> = search
+ .matches
+ .iter()
+ .enumerate()
.map(|(i, entry)| {
let (style, cmd_style, dsc_style) = if i == search.selected {
let s = Style::default().bg(skill_sel_color).fg(Color::Black);
(s, s, s)
} else {
- (Style::default(), Style::default().fg(accent), Style::default().fg(dim))
+ (
+ Style::default(),
+ Style::default().fg(accent),
+ Style::default().fg(dim),
+ )
};
let cmd_padded = format!(" {:<24}", entry.command);
ListItem::new(Line::from(vec![
Span::styled(cmd_padded, cmd_style),
Span::styled(&entry.description, dsc_style),
- ])).style(style)
- }).collect();
+ ]))
+ .style(style)
+ })
+ .collect();
let list = List::new(items).block(
Block::default()
.title(" Skills [↑↓] select [Tab/Enter] insert [Esc] cancel ")
@@ -1278,28 +1447,43 @@ impl App {
width: input_area.width.saturating_sub(4),
height: dropdown_height,
};
- let dropdown_area = if dropdown_area.y + dropdown_area.height > area.height {
- Rect { y: input_area.y.saturating_sub(dropdown_height), ..dropdown_area }
- } else { dropdown_area };
+ let dropdown_area = if dropdown_area.y + dropdown_area.height > area.height
+ {
+ Rect {
+ y: input_area.y.saturating_sub(dropdown_height),
+ ..dropdown_area
+ }
+ } else {
+ dropdown_area
+ };
frame.render_widget(Clear, dropdown_area);
let task_sel_color = hex_to_color(&state.config.theme.color_selected);
let accent = hex_to_color(&state.config.theme.color_accent);
let dim = hex_to_color(&state.config.theme.color_dimmed);
- let items: Vec<ListItem> = search.matches.iter().enumerate()
+ let items: Vec<ListItem> = search
+ .matches
+ .iter()
+ .enumerate()
.map(|(i, (_, title, status))| {
let (style, title_style, status_style) = if i == search.selected {
let s = Style::default().bg(task_sel_color).fg(Color::Black);
(s, s, s)
} else {
- (Style::default(), Style::default().fg(accent), Style::default().fg(dim))
+ (
+ Style::default(),
+ Style::default().fg(accent),
+ Style::default().fg(dim),
+ )
};
let status_badge = format!(" [{}]", status.as_str());
ListItem::new(Line::from(vec![
Span::styled(format!(" {}", title), title_style),
Span::styled(status_badge, status_style),
- ])).style(style)
- }).collect();
+ ]))
+ .style(style)
+ })
+ .collect();
let list = List::new(items).block(
Block::default()
.title(" Tasks [↑↓] select [Tab/Enter] insert [Esc] cancel ")
@@ -1344,7 +1528,8 @@ impl App {
frame.render_widget(input, popup_chunks[0]);
// Results list
- let items: Vec<ListItem> = search.matches
+ let items: Vec<ListItem> = search
+ .matches
.iter()
.enumerate()
.map(|(i, (_, title, status))| {
@@ -1367,13 +1552,14 @@ impl App {
})
.collect();
- let list = List::new(items)
- .block(
- Block::default()
- .title(" [↑↓] select [Enter] jump [Esc] cancel ")
- .borders(Borders::ALL)
- .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_dimmed))),
- );
+ let list = List::new(items).block(
+ Block::default()
+ .title(" [↑↓] select [Enter] jump [Esc] cancel ")
+ .borders(Borders::ALL)
+ .border_style(
+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)),
+ ),
+ );
frame.render_widget(list, popup_chunks[1]);
}
@@ -1387,7 +1573,9 @@ impl App {
let main_block = Block::default()
.title(" Create Pull Request ")
.borders(Borders::ALL)
- .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_selected)));
+ .border_style(
+ Style::default().fg(hex_to_color(&state.config.theme.color_selected)),
+ );
frame.render_widget(main_block, popup_area);
// Spinner animation based on frame count
@@ -1395,11 +1583,16 @@ impl App {
let spinner_idx = (std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
- .as_millis() / 100) as usize % spinner_chars.len();
+ .as_millis()
+ / 100) as usize
+ % spinner_chars.len();
let spinner = spinner_chars[spinner_idx];
let agent_name = state.config.default_agent.clone();
- let loading_text = format!("{} Generating PR description with {}...", spinner, agent_name);
+ 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);
@@ -1407,16 +1600,16 @@ impl App {
// Center vertically within the popup
let inner = popup_area.inner(ratatui::layout::Margin {
horizontal: 2,
- vertical: popup_area.height.saturating_sub(3) / 2
+ vertical: popup_area.height.saturating_sub(3) / 2,
});
frame.render_widget(loading, inner);
} else {
let popup_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
- Constraint::Length(3), // Title input
- Constraint::Min(0), // Body input
- Constraint::Length(1), // Help line
+ Constraint::Length(3), // Title input
+ Constraint::Min(0), // Body input
+ Constraint::Length(1), // Help line
])
.margin(1)
.split(popup_area);
@@ -1425,7 +1618,9 @@ impl App {
let main_block = Block::default()
.title(" Create Pull Request ")
.borders(Borders::ALL)
- .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)));
+ .border_style(
+ Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)),
+ );
frame.render_widget(main_block, popup_area);
// Title input
@@ -1486,8 +1681,14 @@ impl App {
frame.render_widget(Clear, popup_area);
let (title, border_color) = match popup.status {
- PrCreationStatus::Creating => (" Creating Pull Request ", hex_to_color(&state.config.theme.color_selected)),
- PrCreationStatus::Pushing => (" Pushing Changes ", hex_to_color(&state.config.theme.color_selected)),
+ PrCreationStatus::Creating => (
+ " Creating Pull Request ",
+ hex_to_color(&state.config.theme.color_selected),
+ ),
+ PrCreationStatus::Pushing => (
+ " Pushing Changes ",
+ hex_to_color(&state.config.theme.color_selected),
+ ),
PrCreationStatus::Success => (" Pull Request Created ", Color::Green),
PrCreationStatus::Error => (" Error Creating PR ", Color::Red),
};
@@ -1498,7 +1699,10 @@ impl App {
.border_style(Style::default().fg(border_color));
frame.render_widget(main_block, popup_area);
- let inner = popup_area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 2 });
+ let inner = popup_area.inner(ratatui::layout::Margin {
+ horizontal: 2,
+ vertical: 2,
+ });
match popup.status {
PrCreationStatus::Creating => {
@@ -1506,7 +1710,9 @@ impl App {
let spinner_idx = (std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
- .as_millis() / 100) as usize % spinner_chars.len();
+ .as_millis()
+ / 100) as usize
+ % spinner_chars.len();
let spinner = spinner_chars[spinner_idx];
let text = format!("{} Pushing branch and creating PR...", spinner);
@@ -1520,7 +1726,9 @@ impl App {
let spinner_idx = (std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
- .as_millis() / 100) as usize % spinner_chars.len();
+ .as_millis()
+ / 100) as usize
+ % spinner_chars.len();
let spinner = spinner_chars[spinner_idx];
let text = format!("{} PR exists. Pushing changes...", spinner);
@@ -1562,10 +1770,15 @@ impl App {
let main_block = Block::default()
.title(" Move to Done? ")
.borders(Borders::ALL)
- .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_selected)));
+ .border_style(
+ Style::default().fg(hex_to_color(&state.config.theme.color_selected)),
+ );
frame.render_widget(main_block, popup_area);
- let inner = popup_area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 2 });
+ let inner = popup_area.inner(ratatui::layout::Margin {
+ horizontal: 2,
+ vertical: 2,
+ });
let text = match popup.pr_state {
DoneConfirmPrState::Open => format!(
"PR #{} is still open.\n\nAre you sure you want to move this task to Done?\n\nWorktree will be deleted, tmux coding session killed.\nBranch kept locally.\n\n[y] Yes, move to Done [n/Esc] Cancel",
@@ -1608,10 +1821,15 @@ impl App {
let main_block = Block::default()
.title(format!(" {} Phase Incomplete ", phase_name))
.borders(Borders::ALL)
- .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_selected)));
+ .border_style(
+ Style::default().fg(hex_to_color(&state.config.theme.color_selected)),
+ );
frame.render_widget(main_block, popup_area);
- let inner = popup_area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 2 });
+ let inner = popup_area.inner(ratatui::layout::Margin {
+ horizontal: 2,
+ vertical: 2,
+ });
let text = format!(
"The agent is still working and the {} artifact\nhas not been created yet.\n\nAre you sure you want to move this task forward?\n\n[y] Yes, move [n/Esc] Cancel",
phase_name.to_lowercase()
@@ -1634,7 +1852,10 @@ impl App {
.border_style(Style::default().fg(Color::Red));
frame.render_widget(main_block, popup_area);
- let inner = popup_area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 2 });
+ let inner = popup_area.inner(ratatui::layout::Margin {
+ horizontal: 2,
+ vertical: 2,
+ });
let text = format!(
"Are you sure you want to delete:\n\n\"{}\"\n\nThis will also remove the worktree and tmux session.\n\n[y] Yes, delete [n/Esc] Cancel",
popup.task_title
@@ -1654,10 +1875,15 @@ impl App {
let main_block = Block::default()
.title(" Move to Review ")
.borders(Borders::ALL)
- .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)));
+ .border_style(
+ Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)),
+ );
frame.render_widget(main_block, popup_area);
- let inner = popup_area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 2 });
+ let inner = popup_area.inner(ratatui::layout::Margin {
+ horizontal: 2,
+ vertical: 2,
+ });
let text = format!(
"Moving task to Review:\n\n\"{}\"\n\nDo you want to create a Pull Request?\n\n[y] Yes, create PR [n] No, just move [Esc] Cancel",
popup.task_title
@@ -1677,10 +1903,15 @@ impl App {
let main_block = Block::default()
.title(" Select Workflow Plugin ")
.borders(Borders::ALL)
- .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)));
+ .border_style(
+ Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)),
+ );
frame.render_widget(main_block, popup_area);
- let inner = popup_area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 1 });
+ let inner = popup_area.inner(ratatui::layout::Margin {
+ horizontal: 2,
+ vertical: 1,
+ });
let mut lines: Vec<Line> = Vec::new();
for (i, opt) in popup.options.iter().enumerate() {
@@ -1689,7 +1920,9 @@ impl App {
let check = if opt.active { " βœ“" } else { "" };
let name_style = if is_selected {
- Style::default().fg(hex_to_color(&state.config.theme.color_selected)).add_modifier(Modifier::BOLD)
+ Style::default()
+ .fg(hex_to_color(&state.config.theme.color_selected))
+ .add_modifier(Modifier::BOLD)
} else {
Style::default().fg(hex_to_color(&state.config.theme.color_text))
};
@@ -1700,8 +1933,12 @@ impl App {
Span::styled(check, Style::default().fg(Color::Green)),
]));
- let desc_style = Style::default().fg(hex_to_color(&state.config.theme.color_description));
- lines.push(Line::from(Span::styled(format!(" {}", opt.description), desc_style)));
+ let desc_style =
+ Style::default().fg(hex_to_color(&state.config.theme.color_description));
+ lines.push(Line::from(Span::styled(
+ format!(" {}", opt.description),
+ desc_style,
+ )));
lines.push(Line::from(""));
}
@@ -1730,12 +1967,16 @@ impl App {
// Title bar
let title = format!(" Diff: {} ", popup.task_title);
- let title_bar = Paragraph::new(title)
- .style(Style::default().fg(Color::Black).bg(hex_to_color(&state.config.theme.color_popup_header)));
+ let title_bar = Paragraph::new(title).style(
+ Style::default()
+ .fg(Color::Black)
+ .bg(hex_to_color(&state.config.theme.color_popup_header)),
+ );
frame.render_widget(title_bar, popup_chunks[0]);
// Diff content with syntax highlighting
- let lines: Vec<Line> = popup.diff_content
+ let lines: Vec<Line> = popup
+ .diff_content
.lines()
.skip(popup.scroll_offset)
.take(popup_chunks[1].height.saturating_sub(2) as usize)
@@ -1755,12 +1996,10 @@ impl App {
})
.collect();
- let diff_content = Paragraph::new(lines)
- .block(
- Block::default()
- .borders(Borders::ALL)
- .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_popup_border))),
- );
+ let diff_content =
+ Paragraph::new(lines).block(Block::default().borders(Borders::ALL).border_style(
+ Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)),
+ ));
frame.render_widget(diff_content, popup_chunks[1]);
// Footer with scroll info
@@ -1770,14 +2009,18 @@ impl App {
popup.scroll_offset + 1,
total_lines
);
- let footer = Paragraph::new(footer_text)
- .style(Style::default().fg(Color::Black).bg(hex_to_color(&state.config.theme.color_dimmed)));
+ let footer = Paragraph::new(footer_text).style(
+ Style::default()
+ .fg(Color::Black)
+ .bg(hex_to_color(&state.config.theme.color_dimmed)),
+ );
frame.render_widget(footer, popup_chunks[2]);
}
}
fn draw_shell_popup(popup: &ShellPopup, frame: &mut Frame, area: Rect, theme: &ThemeConfig) {
- let popup_area = centered_rect_fixed_width(SHELL_POPUP_WIDTH, SHELL_POPUP_HEIGHT_PERCENT, area);
+ let popup_area =
+ centered_rect_fixed_width(SHELL_POPUP_WIDTH, SHELL_POPUP_HEIGHT_PERCENT, area);
// Parse ANSI escape sequences for colors
let styled_lines = parse_ansi_to_lines(&popup.cached_content);
@@ -1796,7 +2039,15 @@ impl App {
shell_popup::render_shell_popup(popup, frame, popup_area, styled_lines, &colors);
}
- fn draw_task_card(frame: &mut Frame, task: &Task, area: Rect, is_selected: bool, theme: &ThemeConfig, phase_status: Option<&(PhaseStatus, Instant)>, spinner_frame: usize) {
+ fn draw_task_card(
+ frame: &mut Frame,
+ task: &Task,
+ area: Rect,
+ is_selected: bool,
+ theme: &ThemeConfig,
+ phase_status: Option<&(PhaseStatus, Instant)>,
+ spinner_frame: usize,
+ ) {
let border_style = if is_selected {
Style::default().fg(hex_to_color(&theme.color_selected))
} else {
@@ -1804,7 +2055,9 @@ impl App {
};
let title_style = if is_selected {
- Style::default().fg(hex_to_color(&theme.color_selected)).bold()
+ Style::default()
+ .fg(hex_to_color(&theme.color_selected))
+ .bold()
} else {
Style::default().fg(hex_to_color(&theme.color_text)).bold()
};
@@ -1812,7 +2065,11 @@ impl App {
// Truncate title to fit (char-safe for UTF-8)
let max_title_len = area.width.saturating_sub(4) as usize;
let title: String = if task.title.chars().count() > max_title_len {
- let truncated: String = task.title.chars().take(max_title_len.saturating_sub(3)).collect();
+ let truncated: String = task
+ .title
+ .chars()
+ .take(max_title_len.saturating_sub(3))
+ .collect();
format!("{}...", truncated)
} else {
task.title.clone()
@@ -1832,29 +2089,47 @@ impl App {
frame.render_widget(card_block, area);
// Title line with optional phase indicator
- let show_indicator = matches!(task.status,
- TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review)
- || (task.status == TaskStatus::Backlog && task.session_name.is_some());
+ let show_indicator = matches!(
+ task.status,
+ TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review
+ ) || (task.status == TaskStatus::Backlog
+ && task.session_name.is_some());
if show_indicator {
- const SPINNER_FRAMES: &[&str] = &["\u{280b}", "\u{2819}", "\u{2839}", "\u{2838}", "\u{283c}", "\u{2834}", "\u{2826}", "\u{2827}", "\u{2807}", "\u{280f}"];
+ const SPINNER_FRAMES: &[&str] = &[
+ "\u{280b}", "\u{2819}", "\u{2839}", "\u{2838}", "\u{283c}", "\u{2834}", "\u{2826}",
+ "\u{2827}", "\u{2807}", "\u{280f}",
+ ];
let indicator = match phase_status {
- Some((PhaseStatus::Ready, _)) => Span::styled("\u{2713} ", Style::default().fg(Color::Green)),
+ Some((PhaseStatus::Ready, _)) => {
+ Span::styled("\u{2713} ", Style::default().fg(Color::Green))
+ }
Some((PhaseStatus::Working, _)) => {
let spinner = SPINNER_FRAMES[spinner_frame % SPINNER_FRAMES.len()];
Span::styled(format!("{} ", spinner), Style::default().fg(Color::Yellow))
}
- Some((PhaseStatus::Idle, _)) => Span::styled("\u{23f8} ", Style::default().fg(hex_to_color(&theme.color_dimmed))),
- Some((PhaseStatus::Exited, _)) => Span::styled("\u{2717} ", Style::default().fg(Color::Red)),
+ Some((PhaseStatus::Idle, _)) => Span::styled(
+ "\u{23f8} ",
+ Style::default().fg(hex_to_color(&theme.color_dimmed)),
+ ),
+ Some((PhaseStatus::Exited, _)) => {
+ Span::styled("\u{2717} ", Style::default().fg(Color::Red))
+ }
None => Span::raw(""),
};
// Escalation warning indicator
let warn_span = if task.escalation_note.is_some() {
- Span::styled("\u{26a0} ", Style::default().fg(hex_to_color(&theme.color_accent)).bold())
+ Span::styled(
+ "\u{26a0} ",
+ Style::default()
+ .fg(hex_to_color(&theme.color_accent))
+ .bold(),
+ )
} else {
Span::raw("")
};
- let title_spans = Line::from(vec![indicator, warn_span, Span::styled(title, title_style)]);
+ let title_spans =
+ Line::from(vec![indicator, warn_span, Span::styled(title, title_style)]);
let title_line = Paragraph::new(title_spans);
let title_area = Rect {
x: inner.x,
@@ -1876,7 +2151,11 @@ impl App {
// Footer line with agent name (for active tasks)
let show_agent = task.status != TaskStatus::Backlog || task.session_name.is_some();
- let footer_height = if show_agent && inner.height > 2 { 1u16 } else { 0u16 };
+ let footer_height = if show_agent && inner.height > 2 {
+ 1u16
+ } else {
+ 0u16
+ };
// Preview area (below title) - always show description
if inner.height > 1 + footer_height {
@@ -1893,13 +2172,23 @@ impl App {
// Truncate description to fit preview area
let max_chars = (preview_area.width as usize) * (preview_area.height as usize);
let truncated: String = if preview_text.chars().count() > max_chars {
- format!("{}...", preview_text.chars().take(max_chars.saturating_sub(3)).collect::<String>())
+ format!(
+ "{}...",
+ preview_text
+ .chars()
+ .take(max_chars.saturating_sub(3))
+ .collect::<String>()
+ )
} else {
preview_text.to_string()
};
let preview = Paragraph::new(truncated)
- .style(Style::default().fg(hex_to_color(&theme.color_description)).italic())
+ .style(
+ Style::default()
+ .fg(hex_to_color(&theme.color_description))
+ .italic(),
+ )
.wrap(Wrap { trim: true });
frame.render_widget(preview, preview_area);
}
@@ -1913,10 +2202,10 @@ impl App {
height: 1,
};
let agent_style = match task.agent.as_str() {
- "claude" => Style::default().fg(Color::Rgb(227, 148, 62)), // orange
+ "claude" => Style::default().fg(Color::Rgb(227, 148, 62)), // orange
"gemini" => Style::default().fg(Color::Rgb(234, 130, 180)), // pink
"opencode" => Style::default().fg(Color::White).bg(Color::Rgb(80, 80, 80)), // white on grey
- "codex" => Style::default().fg(Color::White).bg(Color::Rgb(20, 20, 20)), // white on black
+ "codex" => Style::default().fg(Color::White).bg(Color::Rgb(20, 20, 20)), // white on black
_ => Style::default().fg(Color::White),
};
let agent_label = Paragraph::new(format!(" {} ", task.agent))
@@ -1928,7 +2217,10 @@ impl App {
fn draw_sidebar(state: &AppState, frame: &mut Frame, area: Rect) {
// Show projects from database
- let current_path = state.project_path.as_ref().map(|p| p.to_string_lossy().to_string());
+ let current_path = state
+ .project_path
+ .as_ref()
+ .map(|p| p.to_string_lossy().to_string());
let items: Vec<ListItem> = state
.projects
@@ -1939,7 +2231,9 @@ impl App {
let is_current = current_path.as_ref() == Some(&project.path);
let style = if is_selected {
- Style::default().bg(hex_to_color(&state.config.theme.color_selected)).fg(Color::Black)
+ Style::default()
+ .bg(hex_to_color(&state.config.theme.color_selected))
+ .fg(Color::Black)
} else if is_current {
Style::default().fg(hex_to_color(&state.config.theme.color_selected))
} else {
@@ -1975,8 +2269,8 @@ impl App {
.direction(Direction::Vertical)
.constraints([
Constraint::Length(10), // Logo + subtitle
- Constraint::Min(0), // Project list or options
- Constraint::Length(3), // Footer
+ Constraint::Min(0), // Project list or options
+ Constraint::Length(3), // Footer
])
.split(area);
@@ -1984,17 +2278,37 @@ impl App {
let logo_color = Color::Rgb(234, 212, 154); // #ead49a
let logo = vec![
Line::from(""),
- Line::from(Span::styled(" β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—", Style::default().fg(logo_color).bold())),
- Line::from(Span::styled("β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•", Style::default().fg(logo_color).bold())),
- Line::from(Span::styled("β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ•”β• ", Style::default().fg(logo_color).bold())),
- Line::from(Span::styled("β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— ", Style::default().fg(logo_color).bold())),
- Line::from(Span::styled("β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•—", Style::default().fg(logo_color).bold())),
- Line::from(Span::styled("β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β• β•šβ•β•", Style::default().fg(logo_color).bold())),
+ Line::from(Span::styled(
+ " β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—",
+ Style::default().fg(logo_color).bold(),
+ )),
+ Line::from(Span::styled(
+ "β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•",
+ Style::default().fg(logo_color).bold(),
+ )),
+ Line::from(Span::styled(
+ "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ•”β• ",
+ Style::default().fg(logo_color).bold(),
+ )),
+ Line::from(Span::styled(
+ "β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— ",
+ Style::default().fg(logo_color).bold(),
+ )),
+ Line::from(Span::styled(
+ "β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•—",
+ Style::default().fg(logo_color).bold(),
+ )),
+ Line::from(Span::styled(
+ "β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β• β•šβ•β•",
+ Style::default().fg(logo_color).bold(),
+ )),
Line::from(""),
- Line::from(Span::styled("Autonomous multi-session spec-driven AI coding orchestration in the terminal", Style::default().fg(dimmed_color))),
+ Line::from(Span::styled(
+ "Autonomous multi-session spec-driven AI coding orchestration in the terminal",
+ Style::default().fg(dimmed_color),
+ )),
];
- let logo_widget = Paragraph::new(logo)
- .alignment(Alignment::Center);
+ let logo_widget = Paragraph::new(logo).alignment(Alignment::Center);
frame.render_widget(logo_widget, chunks[0]);
// Project list or options
@@ -2025,7 +2339,12 @@ impl App {
let options = Paragraph::new(
"\n [p] Open existing project\n [n] Create new project in current directory\n",
)
- .block(Block::default().title(" Options ").borders(Borders::ALL).border_style(Style::default().fg(dimmed_color)));
+ .block(
+ Block::default()
+ .title(" Options ")
+ .borders(Borders::ALL)
+ .border_style(Style::default().fg(dimmed_color)),
+ );
frame.render_widget(options, chunks[1]);
}
@@ -2040,7 +2359,9 @@ impl App {
// Handle PR status popup if open (loading/success/error)
if let Some(ref popup) = self.state.pr_status_popup {
// Only allow closing if not in Creating/Pushing state
- if popup.status != PrCreationStatus::Creating && popup.status != PrCreationStatus::Pushing {
+ if popup.status != PrCreationStatus::Creating
+ && popup.status != PrCreationStatus::Pushing
+ {
if matches!(key.code, KeyCode::Enter | KeyCode::Esc) {
self.state.pr_status_popup = None;
}
@@ -2096,14 +2417,12 @@ impl App {
// Handle based on mode (Dashboard vs Project)
match &self.state.mode {
AppMode::Dashboard => self.handle_dashboard_key(key.code),
- AppMode::Project(_) => {
- match self.state.input_mode {
- InputMode::Normal => self.handle_normal_key(key.code),
- InputMode::InputTitle => self.handle_title_input(key),
- InputMode::SelectPlugin => self.handle_plugin_select_wizard(key),
- InputMode::InputDescription => self.handle_description_input(key),
- }
- }
+ AppMode::Project(_) => match self.state.input_mode {
+ InputMode::Normal => self.handle_normal_key(key.code),
+ InputMode::InputTitle => self.handle_title_input(key),
+ InputMode::SelectPlugin => self.handle_plugin_select_wizard(key),
+ InputMode::InputDescription => self.handle_description_input(key),
+ },
}
}
@@ -2185,7 +2504,12 @@ impl App {
}
fn open_plugin_select_popup(&mut self) {
- let current = self.state.config.workflow_plugin.as_deref().unwrap_or("agtx");
+ let current = self
+ .state
+ .config
+ .workflow_plugin
+ .as_deref()
+ .unwrap_or("agtx");
let mut options = vec![PluginOption {
name: "agtx".to_string(),
label: "agtx".to_string(),
@@ -2193,7 +2517,9 @@ impl App {
active: current == "agtx",
}];
for (name, desc, _content) in skills::BUNDLED_PLUGINS {
- if *name == "agtx" { continue; }
+ if *name == "agtx" {
+ continue;
+ }
options.push(PluginOption {
name: name.to_string(),
label: name.to_string(),
@@ -2249,10 +2575,7 @@ impl App {
.iter()
.find(|(n, _, _)| *n == plugin_name)
{
- let plugin_dir = project_path
- .join(".agtx")
- .join("plugins")
- .join(plugin_name);
+ let plugin_dir = project_path.join(".agtx").join("plugins").join(plugin_name);
let _ = std::fs::create_dir_all(&plugin_dir);
let _ = std::fs::write(plugin_dir.join("plugin.toml"), content);
}
@@ -2294,8 +2617,13 @@ impl App {
let task_id = task.id.clone();
std::thread::spawn(move || {
cleanup_task_resources(
- &task_id, &branch_name, &session_name, &worktree_path,
- &project_path, tmux_ops.as_ref(), git_ops.as_ref(),
+ &task_id,
+ &branch_name,
+ &session_name,
+ &worktree_path,
+ &project_path,
+ tmux_ops.as_ref(),
+ git_ops.as_ref(),
);
});
}
@@ -2325,7 +2653,10 @@ 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 = self.state.agent_registry.get(&self.state.config.default_agent);
+ let agent_ops = self
+ .state
+ .agent_registry
+ .get(&self.state.config.default_agent);
std::thread::spawn(move || {
let (pr_title, pr_body) = generate_pr_description(
&title_for_thread,
@@ -2372,7 +2703,9 @@ impl App {
let pr_title = popup.pr_title.clone();
let pr_body = popup.pr_body.clone();
self.state.pr_confirm_popup = None;
- self.create_pr_and_move_to_review_with_content(&task_id, &pr_title, &pr_body)?;
+ self.create_pr_and_move_to_review_with_content(
+ &task_id, &pr_title, &pr_body,
+ )?;
}
}
KeyCode::Enter => {
@@ -2404,7 +2737,12 @@ impl App {
Ok(())
}
- fn create_pr_and_move_to_review_with_content(&mut self, task_id: &str, pr_title: &str, pr_body: &str) -> Result<()> {
+ fn create_pr_and_move_to_review_with_content(
+ &mut self,
+ task_id: &str,
+ pr_title: &str,
+ pr_body: &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)? {
// Keep tmux window open - session_name stays set for resume
@@ -2423,7 +2761,10 @@ impl App {
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 = self.state.agent_registry.get(&self.state.config.default_agent);
+ let agent_ops = self
+ .state
+ .agent_registry
+ .get(&self.state.config.default_agent);
// Create channel for result
let (tx, rx) = mpsc::channel();
@@ -2475,13 +2816,21 @@ impl App {
KeyCode::Enter => {
// Jump to selected task and open it
if let Some(ref search) = self.state.task_search {
- if let Some((task_id, _, status)) = search.matches.get(search.selected).cloned() {
+ if let Some((task_id, _, status)) = search.matches.get(search.selected).cloned()
+ {
// Find column index for this status
- let col_idx = TaskStatus::columns().iter().position(|s| *s == status).unwrap_or(0);
+ let col_idx = TaskStatus::columns()
+ .iter()
+ .position(|s| *s == status)
+ .unwrap_or(0);
self.state.board.selected_column = col_idx;
// Find row index for this task
- let tasks_in_col: Vec<_> = self.state.board.tasks.iter()
+ let tasks_in_col: Vec<_> = self
+ .state
+ .board
+ .tasks
+ .iter()
.filter(|t| t.status == status)
.collect();
if let Some(row_idx) = tasks_in_col.iter().position(|t| t.id == task_id) {
@@ -2510,7 +2859,9 @@ impl App {
}
false
}
- KeyCode::Char('k') | KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => {
+ KeyCode::Char('k') | KeyCode::Char('p')
+ if key.modifiers.contains(KeyModifiers::CONTROL) =>
+ {
if let Some(ref mut search) = self.state.task_search {
if search.selected > 0 {
search.selected -= 1;
@@ -2518,7 +2869,9 @@ impl App {
}
false
}
- KeyCode::Char('j') | KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => {
+ KeyCode::Char('j') | KeyCode::Char('n')
+ if key.modifiers.contains(KeyModifiers::CONTROL) =>
+ {
if let Some(ref mut search) = self.state.task_search {
if search.selected < search.matches.len().saturating_sub(1) {
search.selected += 1;
@@ -2530,7 +2883,12 @@ impl App {
if let Some(ref mut search) = self.state.task_search {
search.query.pop();
}
- let query = self.state.task_search.as_ref().map(|s| s.query.clone()).unwrap_or_default();
+ let query = self
+ .state
+ .task_search
+ .as_ref()
+ .map(|s| s.query.clone())
+ .unwrap_or_default();
let matches = self.get_all_task_matches(&query);
if let Some(ref mut search) = self.state.task_search {
search.matches = matches;
@@ -2542,7 +2900,12 @@ impl App {
if let Some(ref mut search) = self.state.task_search {
search.query.push(c);
}
- let query = self.state.task_search.as_ref().map(|s| s.query.clone()).unwrap_or_default();
+ let query = self
+ .state
+ .task_search
+ .as_ref()
+ .map(|s| s.query.clone())
+ .unwrap_or_default();
let matches = self.get_all_task_matches(&query);
if let Some(ref mut search) = self.state.task_search {
search.matches = matches;
@@ -2563,7 +2926,10 @@ impl App {
fn get_all_task_matches(&self, query: &str) -> Vec<(String, String, TaskStatus)> {
let query_lower = query.to_lowercase();
- let mut matches: Vec<(String, String, TaskStatus, i32)> = self.state.board.tasks
+ let mut matches: Vec<(String, String, TaskStatus, i32)> = self
+ .state
+ .board
+ .tasks
.iter()
.filter_map(|task| {
let title_lower = task.title.to_lowercase();
@@ -2584,7 +2950,8 @@ impl App {
// Sort by score (higher is better)
matches.sort_by(|a, b| b.3.cmp(&a.3));
- matches.into_iter()
+ matches
+ .into_iter()
.take(10)
.map(|(id, title, status, _)| (id, title, status))
.collect()
@@ -2653,7 +3020,11 @@ impl App {
// Forward all other keys to tmux window (including Esc)
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, self.state.tmux_ops.as_ref());
+ popup.cached_content = capture_tmux_pane_with_history(
+ &window_name,
+ 500,
+ self.state.tmux_ops.as_ref(),
+ );
}
}
}
@@ -2707,7 +3078,12 @@ impl App {
}
}
KeyCode::Enter => {
- if let Some(project) = self.state.projects.get(self.state.selected_project).cloned() {
+ if let Some(project) = self
+ .state
+ .projects
+ .get(self.state.selected_project)
+ .cloned()
+ {
self.switch_to_project(&project)?;
self.state.mode = AppMode::Project(PathBuf::from(&project.path));
self.state.sidebar_visible = false;
@@ -2766,7 +3142,12 @@ impl App {
if self.state.selected_project < self.state.projects.len().saturating_sub(1) {
self.state.selected_project += 1;
// Switch to project immediately on cursor move
- if let Some(project) = self.state.projects.get(self.state.selected_project).cloned() {
+ if let Some(project) = self
+ .state
+ .projects
+ .get(self.state.selected_project)
+ .cloned()
+ {
self.switch_to_project_keep_sidebar(&project)?;
}
}
@@ -2775,7 +3156,12 @@ impl App {
if self.state.selected_project > 0 {
self.state.selected_project -= 1;
// Switch to project immediately on cursor move
- if let Some(project) = self.state.projects.get(self.state.selected_project).cloned() {
+ if let Some(project) = self
+ .state
+ .projects
+ .get(self.state.selected_project)
+ .cloned()
+ {
self.switch_to_project_keep_sidebar(&project)?;
}
}
@@ -2908,22 +3294,28 @@ impl App {
}
}
KeyCode::Left if has_alt => {
- self.state.input_cursor = word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
+ self.state.input_cursor =
+ word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
}
KeyCode::Right if has_alt => {
- self.state.input_cursor = word_boundary_right(&self.state.input_buffer, self.state.input_cursor);
+ self.state.input_cursor =
+ word_boundary_right(&self.state.input_buffer, self.state.input_cursor);
}
// macOS: Option+Left/Right sends Alt+b / Alt+f
KeyCode::Char('b') if has_alt => {
- self.state.input_cursor = word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
+ self.state.input_cursor =
+ word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
}
KeyCode::Char('f') if has_alt => {
- self.state.input_cursor = word_boundary_right(&self.state.input_buffer, self.state.input_cursor);
+ self.state.input_cursor =
+ word_boundary_right(&self.state.input_buffer, self.state.input_cursor);
}
// Alt+Backspace: delete word backward (macOS Option+Delete)
KeyCode::Backspace if has_alt => {
let new_pos = word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
- self.state.input_buffer.drain(new_pos..self.state.input_cursor);
+ self.state
+ .input_buffer
+ .drain(new_pos..self.state.input_cursor);
self.state.input_cursor = new_pos;
}
KeyCode::Left => {
@@ -2964,7 +3356,9 @@ impl App {
fn handle_plugin_select_wizard(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
match key.code {
- KeyCode::Esc => { self.cancel_wizard(); }
+ KeyCode::Esc => {
+ self.cancel_wizard();
+ }
KeyCode::Char('j') | KeyCode::Down => {
let max = self.state.wizard_plugin_options.len().saturating_sub(1);
if self.state.wizard_selected_plugin < max {
@@ -2979,7 +3373,8 @@ impl App {
KeyCode::Tab => {
let len = self.state.wizard_plugin_options.len();
if len > 0 {
- self.state.wizard_selected_plugin = (self.state.wizard_selected_plugin + 1) % len;
+ self.state.wizard_selected_plugin =
+ (self.state.wizard_selected_plugin + 1) % len;
}
}
KeyCode::Enter => {
@@ -3004,7 +3399,9 @@ impl App {
self.state.task_ref_search = None;
}
KeyCode::Enter | KeyCode::Tab => {
- if let Some((task_id, title, _status)) = search.matches.get(search.selected).cloned() {
+ if let Some((task_id, title, _status)) =
+ search.matches.get(search.selected).cloned()
+ {
// Replace `!` + pattern with ![task-title]
let pattern_end = search.start_pos + 1 + search.pattern.len();
let suffix = self.state.input_buffer[pattern_end..].to_string();
@@ -3056,7 +3453,12 @@ impl App {
}
self.state.input_buffer.insert(self.state.input_cursor, c);
self.state.input_cursor += 1;
- let query = self.state.task_ref_search.as_ref().map(|s| s.pattern.clone()).unwrap_or_default();
+ let query = self
+ .state
+ .task_ref_search
+ .as_ref()
+ .map(|s| s.pattern.clone())
+ .unwrap_or_default();
let matches = self.get_all_task_matches(&query);
if let Some(ref mut search) = self.state.task_ref_search {
search.matches = matches;
@@ -3103,12 +3505,20 @@ impl App {
search.selected += 1;
}
}
- KeyCode::Char('k') | KeyCode::Char('p') if key.modifiers.contains(crossterm::event::KeyModifiers::CONTROL) => {
+ KeyCode::Char('k') | KeyCode::Char('p')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
if search.selected > 0 {
search.selected -= 1;
}
}
- KeyCode::Char('j') | KeyCode::Char('n') if key.modifiers.contains(crossterm::event::KeyModifiers::CONTROL) => {
+ KeyCode::Char('j') | KeyCode::Char('n')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
if search.selected < search.matches.len().saturating_sub(1) {
search.selected += 1;
}
@@ -3168,12 +3578,20 @@ impl App {
search.selected += 1;
}
}
- KeyCode::Char('k') | KeyCode::Char('p') if key.modifiers.contains(crossterm::event::KeyModifiers::CONTROL) => {
+ KeyCode::Char('k') | KeyCode::Char('p')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
if search.selected > 0 {
search.selected -= 1;
}
}
- KeyCode::Char('j') | KeyCode::Char('n') if key.modifiers.contains(crossterm::event::KeyModifiers::CONTROL) => {
+ KeyCode::Char('j') | KeyCode::Char('n')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
if search.selected < search.matches.len().saturating_sub(1) {
search.selected += 1;
}
@@ -3220,22 +3638,28 @@ impl App {
}
}
KeyCode::Left if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {
- self.state.input_cursor = word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
+ self.state.input_cursor =
+ word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
}
KeyCode::Right if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {
- self.state.input_cursor = word_boundary_right(&self.state.input_buffer, self.state.input_cursor);
+ self.state.input_cursor =
+ word_boundary_right(&self.state.input_buffer, self.state.input_cursor);
}
// macOS: Option+Left/Right sends Alt+b / Alt+f
KeyCode::Char('b') if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {
- self.state.input_cursor = word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
+ self.state.input_cursor =
+ word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
}
KeyCode::Char('f') if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {
- self.state.input_cursor = word_boundary_right(&self.state.input_buffer, self.state.input_cursor);
+ self.state.input_cursor =
+ word_boundary_right(&self.state.input_buffer, self.state.input_cursor);
}
// Alt+Backspace: delete word backward (macOS Option+Delete)
KeyCode::Backspace if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {
let new_pos = word_boundary_left(&self.state.input_buffer, self.state.input_cursor);
- self.state.input_buffer.drain(new_pos..self.state.input_cursor);
+ self.state
+ .input_buffer
+ .drain(new_pos..self.state.input_cursor);
self.state.input_cursor = new_pos;
}
KeyCode::Left => {
@@ -3267,9 +3691,15 @@ impl App {
}
KeyCode::Char('#') | KeyCode::Char('@') => {
// Start file search at cursor position
- let trigger = if let KeyCode::Char(c) = key.code { c } else { '#' };
+ let trigger = if let KeyCode::Char(c) = key.code {
+ c
+ } else {
+ '#'
+ };
let start_pos = self.state.input_cursor;
- self.state.input_buffer.insert(self.state.input_cursor, trigger);
+ self.state
+ .input_buffer
+ .insert(self.state.input_cursor, trigger);
self.state.input_cursor += 1;
self.state.file_search = Some(FileSearchState {
pattern: String::new(),
@@ -3280,7 +3710,16 @@ impl App {
});
self.update_file_search_matches();
}
- KeyCode::Char('/') if self.state.input_cursor == 0 || matches!(self.state.input_buffer.as_bytes().get(self.state.input_cursor.wrapping_sub(1)), Some(&b'\n') | Some(&b' ')) => {
+ KeyCode::Char('/')
+ if self.state.input_cursor == 0
+ || matches!(
+ self.state
+ .input_buffer
+ .as_bytes()
+ .get(self.state.input_cursor.wrapping_sub(1)),
+ Some(&b'\n') | Some(&b' ')
+ ) =>
+ {
// Start skill search at cursor position (at start of line or after space)
let start_pos = self.state.input_cursor;
self.state.input_buffer.insert(self.state.input_cursor, '/');
@@ -3288,19 +3727,28 @@ impl App {
// Start with bundled skills (always available, no filesystem needed)
let mut seen = std::collections::HashSet::new();
- let mut all_skills: Vec<SkillEntry> = skills::enumerate_available_skills(&self.state.config.default_agent)
- .into_iter()
- .map(|(command, description)| {
- seen.insert(command.clone());
- SkillEntry { command, description }
- })
- .collect();
+ let mut all_skills: Vec<SkillEntry> =
+ skills::enumerate_available_skills(&self.state.config.default_agent)
+ .into_iter()
+ .map(|(command, description)| {
+ seen.insert(command.clone());
+ SkillEntry {
+ command,
+ description,
+ }
+ })
+ .collect();
// Merge filesystem-discovered skills (project root), dedup by command
if let Some(ref project_path) = self.state.project_path {
- for (command, description) in skills::scan_agent_skills(&self.state.config.default_agent, project_path) {
+ for (command, description) in
+ skills::scan_agent_skills(&self.state.config.default_agent, project_path)
+ {
if seen.insert(command.clone()) {
- all_skills.push(SkillEntry { command, description });
+ all_skills.push(SkillEntry {
+ command,
+ description,
+ });
}
}
}
@@ -3313,7 +3761,21 @@ impl App {
start_pos,
});
}
- KeyCode::Char('!') if self.state.input_cursor == 0 || self.state.input_buffer.as_bytes().get(self.state.input_cursor.wrapping_sub(1)) == Some(&b'\n') || self.state.input_buffer.as_bytes().get(self.state.input_cursor.wrapping_sub(1)) == Some(&b' ') => {
+ KeyCode::Char('!')
+ if self.state.input_cursor == 0
+ || self
+ .state
+ .input_buffer
+ .as_bytes()
+ .get(self.state.input_cursor.wrapping_sub(1))
+ == Some(&b'\n')
+ || self
+ .state
+ .input_buffer
+ .as_bytes()
+ .get(self.state.input_cursor.wrapping_sub(1))
+ == Some(&b' ') =>
+ {
// Start task reference search at cursor position (at start of line or after space)
let start_pos = self.state.input_cursor;
self.state.input_buffer.insert(self.state.input_cursor, '!');
@@ -3337,9 +3799,12 @@ 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) {
+ 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, self.state.git_ops.as_ref());
+ search.matches =
+ fuzzy_find_files(project_path, pattern, 10, self.state.git_ops.as_ref());
search.selected = 0;
}
}
@@ -3350,12 +3815,18 @@ impl App {
if pattern.is_empty() {
search.matches = search.all_skills.clone();
} else {
- let mut scored: Vec<_> = search.all_skills.iter()
+ let mut scored: Vec<_> = search
+ .all_skills
+ .iter()
.filter_map(|entry| {
let cmd_score = fuzzy_score(&entry.command.to_lowercase(), &pattern);
let desc_score = fuzzy_score(&entry.description.to_lowercase(), &pattern);
let score = std::cmp::max(cmd_score, desc_score);
- if score > 0 { Some((entry.clone(), score)) } else { None }
+ if score > 0 {
+ Some((entry.clone(), score))
+ } else {
+ None
+ }
})
.collect();
scored.sort_by(|a, b| b.1.cmp(&a.1));
@@ -3368,15 +3839,28 @@ impl App {
fn save_task(&mut self) -> Result<()> {
if let Some(db) = &self.state.db {
let agent = self.state.config.default_agent.clone();
- let plugin_name = self.state.wizard_plugin_options
+ let plugin_name = self
+ .state
+ .wizard_plugin_options
.get(self.state.wizard_selected_plugin)
.map(|o| o.name.clone())
.unwrap_or_default();
- let plugin = if plugin_name.is_empty() { None } else { Some(plugin_name) };
+ let plugin = if plugin_name.is_empty() {
+ None
+ } else {
+ Some(plugin_name)
+ };
let refs = if self.state.wizard_referenced_task_ids.is_empty() {
None
} else {
- Some(self.state.wizard_referenced_task_ids.iter().cloned().collect::<Vec<_>>().join(","))
+ Some(
+ self.state
+ .wizard_referenced_task_ids
+ .iter()
+ .cloned()
+ .collect::<Vec<_>>()
+ .join(","),
+ )
};
if let Some(task_id) = &self.state.editing_task_id {
@@ -3417,13 +3901,20 @@ impl App {
/// Initialize plugin selection options for the wizard, filtered by selected agent.
fn init_plugin_selection(&mut self) {
let current = if let Some(task_id) = &self.state.editing_task_id {
- self.state.db.as_ref()
+ self.state
+ .db
+ .as_ref()
.and_then(|db| db.get_task(task_id).ok().flatten())
.and_then(|t| t.plugin.clone())
.or_else(|| self.state.config.workflow_plugin.clone())
.unwrap_or_else(|| "agtx".to_string())
} else {
- self.state.config.workflow_plugin.as_deref().unwrap_or("agtx").to_string()
+ self.state
+ .config
+ .workflow_plugin
+ .as_deref()
+ .unwrap_or("agtx")
+ .to_string()
};
let selected_agent_name = &self.state.config.default_agent;
@@ -3435,10 +3926,14 @@ impl App {
active: current == "agtx",
}];
for (name, desc, content) in skills::BUNDLED_PLUGINS {
- if *name == "agtx" { continue; }
+ if *name == "agtx" {
+ continue;
+ }
// Filter by agent compatibility
if let Ok(plugin) = toml::from_str::<WorkflowPlugin>(content) {
- if !plugin.supports_agent(selected_agent_name) { continue; }
+ if !plugin.supports_agent(selected_agent_name) {
+ continue;
+ }
}
options.push(PluginOption {
name: name.to_string(),
@@ -3459,9 +3954,15 @@ impl App {
if let Ok(Some(task)) = db.get_task(task_id) {
self.state.input_buffer = task.description.unwrap_or_default();
// Restore referenced task IDs if editing
- self.state.wizard_referenced_task_ids = task.referenced_tasks
+ self.state.wizard_referenced_task_ids = task
+ .referenced_tasks
.as_deref()
- .map(|s| s.split(',').filter(|id| !id.is_empty()).map(String::from).collect())
+ .map(|s| {
+ s.split(',')
+ .filter(|id| !id.is_empty())
+ .map(String::from)
+ .collect()
+ })
.unwrap_or_default();
} else {
self.state.input_buffer.clear();
@@ -3534,10 +4035,15 @@ impl App {
let diff_content = if let Some(worktree_path) = &task.worktree_path {
let mut exclude_prefixes: Vec<&str> = crate::git::AGENT_CONFIG_DIRS.to_vec();
let plugin = self.load_task_plugin(task);
- let plugin_dirs: Vec<String> = plugin.map_or_else(Vec::new, |p| p.copy_dirs.clone());
+ let plugin_dirs: Vec<String> =
+ plugin.map_or_else(Vec::new, |p| p.copy_dirs.clone());
let plugin_dir_refs: Vec<&str> = plugin_dirs.iter().map(|s| s.as_str()).collect();
exclude_prefixes.extend(plugin_dir_refs);
- collect_task_diff(worktree_path, self.state.git_ops.as_ref(), &exclude_prefixes)
+ collect_task_diff(
+ worktree_path,
+ self.state.git_ops.as_ref(),
+ &exclude_prefixes,
+ )
} else {
"(task has no worktree yet)".to_string()
};
@@ -3575,10 +4081,18 @@ impl App {
}
let handled = match (current_status, new_status) {
- (TaskStatus::Backlog, TaskStatus::Planning) => self.transition_to_planning(&mut task, &project_path)?,
- (TaskStatus::Planning, TaskStatus::Running) => self.transition_to_running(&mut task)?,
- (TaskStatus::Running, TaskStatus::Review) => self.transition_to_review(&mut task, &project_path)?,
- (TaskStatus::Review, TaskStatus::Done) => self.transition_to_done(&mut task, &project_path)?,
+ (TaskStatus::Backlog, TaskStatus::Planning) => {
+ self.transition_to_planning(&mut task, &project_path)?
+ }
+ (TaskStatus::Planning, TaskStatus::Running) => {
+ self.transition_to_running(&mut task)?
+ }
+ (TaskStatus::Running, TaskStatus::Review) => {
+ self.transition_to_review(&mut task, &project_path)?
+ }
+ (TaskStatus::Review, TaskStatus::Done) => {
+ self.transition_to_done(&mut task, &project_path)?
+ }
_ => false,
};
@@ -3598,7 +4112,6 @@ impl App {
self.state.stuck_task_idle_since.remove(&task.id);
self.state.phase_status_cache.remove(&task.id);
}
-
}
self.refresh_tasks()?;
Ok(())
@@ -3606,15 +4119,25 @@ impl App {
/// Check if the current phase is incomplete (artifact missing + agent still running).
/// Returns true if a confirmation popup was shown and the caller should return early.
- fn check_phase_incomplete(&mut self, task: &Task, current_status: TaskStatus, new_status: TaskStatus) -> bool {
+ fn check_phase_incomplete(
+ &mut self,
+ task: &Task,
+ current_status: TaskStatus,
+ new_status: TaskStatus,
+ ) -> bool {
if self.state.skip_move_confirm {
return false;
}
- if !matches!(current_status, TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review) {
+ if !matches!(
+ current_status,
+ TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review
+ ) {
return false;
}
let plugin = self.load_task_plugin(task);
- let Some(ref wt_path) = task.worktree_path else { return false };
+ let Some(ref wt_path) = task.worktree_path else {
+ return false;
+ };
if phase_artifact_exists(wt_path, current_status, &plugin, task.cycle) {
return false;
}
@@ -3642,10 +4165,14 @@ impl App {
let plugin = self.load_task_plugin(task);
// Block if planning phase doesn't accept {task} and no prior phase artifact exists
- if plugin.as_ref().map_or(false, |p| !p.phase_accepts_task("planning")) {
- let has_research = task.worktree_path.as_ref().map_or(false, |wt| {
- research_artifact_exists(wt, &task.id, &plugin)
- });
+ if plugin
+ .as_ref()
+ .map_or(false, |p| !p.phase_accepts_task("planning"))
+ {
+ let has_research = task
+ .worktree_path
+ .as_ref()
+ .map_or(false, |wt| research_artifact_exists(wt, &task.id, &plugin));
if !has_research {
self.state.warning_message = Some((
format!("Research phase required first β€” press R to start research"),
@@ -3655,7 +4182,8 @@ impl App {
}
}
- let (planning_agent, agent_switch) = needs_agent_switch(&self.state.config, task, "planning");
+ let (planning_agent, agent_switch) =
+ needs_agent_switch(&self.state.config, task, "planning");
let has_live_session = task.session_name.as_ref().map_or(false, |s| {
self.state.tmux_ops.window_exists(s).unwrap_or(false)
@@ -3665,16 +4193,38 @@ impl App {
// Reuse existing session from research
let target = task.session_name.clone().unwrap();
let task_content = task.content_text();
- let planning_phase = determine_phase_variant("planning", task.worktree_path.as_deref(), &task.id, &plugin, task.cycle);
- let skill_cmd = resolve_skill_command(&plugin, planning_phase, &planning_agent, &task_content, task.cycle);
- let prompt = resolve_prompt(&plugin, planning_phase, &task_content, &task.id, task.cycle);
+ let planning_phase = determine_phase_variant(
+ "planning",
+ task.worktree_path.as_deref(),
+ &task.id,
+ &plugin,
+ task.cycle,
+ );
+ let skill_cmd = resolve_skill_command(
+ &plugin,
+ planning_phase,
+ &planning_agent,
+ &task_content,
+ task.cycle,
+ );
+ let prompt =
+ resolve_prompt(&plugin, planning_phase, &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, planning_phase);
- let auto_dismiss = plugin.as_ref().map_or_else(Vec::new, |p| p.auto_dismiss.clone());
+ let auto_dismiss = plugin
+ .as_ref()
+ .map_or_else(Vec::new, |p| p.auto_dismiss.clone());
spawn_send_to_agent(
Arc::clone(&self.state.tmux_ops),
Arc::clone(&self.state.agent_registry),
- target, task.agent.clone(), planning_agent.clone(), agent_switch,
- skill_cmd, prompt, prompt_trigger, task_content, auto_dismiss,
+ target,
+ task.agent.clone(),
+ planning_agent.clone(),
+ agent_switch,
+ skill_cmd,
+ prompt,
+ prompt_trigger,
+ task_content,
+ auto_dismiss,
);
task.agent = planning_agent;
return Ok(false);
@@ -3687,10 +4237,17 @@ impl App {
// Create worktree + tmux window from scratch (non-blocking)
let task_content = task.content_text();
let prompt = resolve_prompt(&plugin, "planning", &task_content, &task.id, task.cycle);
- let skill_cmd = resolve_skill_command(&plugin, "planning", &planning_agent, &task_content, task.cycle);
+ let skill_cmd = resolve_skill_command(
+ &plugin,
+ "planning",
+ &planning_agent,
+ &task_content,
+ task.cycle,
+ );
let prompt_trigger = resolve_prompt_trigger(&plugin, "planning");
let all_agents = collect_phase_agents(&self.state.config);
let project_name = self.state.project_name.clone();
+ let base_branch = self.state.config.base_branch.clone();
let copy_files = self.state.config.copy_files.clone();
let init_script = self.state.config.init_script.clone();
let tmux_ops = Arc::clone(&self.state.tmux_ops);
@@ -3700,21 +4257,31 @@ impl App {
let task_title = task.title.clone();
let plugin_name = task.plugin.clone();
let planning_agent_clone = planning_agent.clone();
- let auto_dismiss = plugin.as_ref().map_or_else(Vec::new, |p| p.auto_dismiss.clone());
+ let auto_dismiss = plugin
+ .as_ref()
+ .map_or_else(Vec::new, |p| p.auto_dismiss.clone());
let project_path = project_path.to_path_buf();
// Pre-fetch referenced task info (DB isn't Send, so fetch before spawning thread)
- let referenced_tasks: Vec<ReferencedTaskInfo> = task.referenced_tasks.as_deref()
+ let referenced_tasks: Vec<ReferencedTaskInfo> = task
+ .referenced_tasks
+ .as_deref()
.map(|refs_str| {
- refs_str.split(',').filter(|s| !s.is_empty()).filter_map(|ref_id| {
- self.state.db.as_ref()
- .and_then(|db| db.get_task(ref_id).ok().flatten())
- .map(|ref_task| ReferencedTaskInfo {
- slug: generate_task_slug(&ref_task.id, &ref_task.title),
- branch_name: ref_task.branch_name.clone(),
- worktree_path: ref_task.worktree_path.clone(),
- })
- }).collect()
+ refs_str
+ .split(',')
+ .filter(|s| !s.is_empty())
+ .filter_map(|ref_id| {
+ self.state
+ .db
+ .as_ref()
+ .and_then(|db| db.get_task(ref_id).ok().flatten())
+ .map(|ref_task| ReferencedTaskInfo {
+ slug: generate_task_slug(&ref_task.id, &ref_task.title),
+ branch_name: ref_task.branch_name.clone(),
+ worktree_path: ref_task.worktree_path.clone(),
+ })
+ })
+ .collect()
})
.unwrap_or_default();
@@ -3727,9 +4294,19 @@ impl App {
tmp_task.plugin = plugin_name.clone();
let result = setup_task_worktree(
- &mut tmp_task, &project_path, &project_name, &prompt,
- copy_files, init_script, &plugin, &planning_agent_clone, &all_agents,
- tmux_ops.as_ref(), git_ops.as_ref(), agent_ops.as_ref(),
+ &mut tmp_task,
+ &project_path,
+ &project_name,
+ &prompt,
+ &base_branch,
+ copy_files,
+ init_script,
+ &plugin,
+ &planning_agent_clone,
+ &all_agents,
+ tmux_ops.as_ref(),
+ git_ops.as_ref(),
+ agent_ops.as_ref(),
&referenced_tasks,
);
@@ -3746,7 +4323,16 @@ impl App {
error: None,
});
if let Some(target) = wait_for_agent_ready(&tmux_ops, &target) {
- send_skill_and_prompt(&tmux_ops, &target, &skill_cmd, &prompt, &prompt_trigger, &task_content, &planning_agent_clone, &auto_dismiss);
+ send_skill_and_prompt(
+ &tmux_ops,
+ &target,
+ &skill_cmd,
+ &prompt,
+ &prompt_trigger,
+ &task_content,
+ &planning_agent_clone,
+ &auto_dismiss,
+ );
}
}
Err(e) => {
@@ -3772,18 +4358,40 @@ impl App {
fn transition_to_running(&mut self, task: &mut Task) -> Result<bool> {
if let Some(session_name) = &task.session_name {
let plugin = self.load_task_plugin(task);
- let (running_agent, agent_switch) = needs_agent_switch(&self.state.config, task, "running");
+ let (running_agent, agent_switch) =
+ needs_agent_switch(&self.state.config, task, "running");
let task_content = task.content_text();
- let run_phase = determine_phase_variant("running", task.worktree_path.as_deref(), &task.id, &plugin, task.cycle);
- let skill_cmd = resolve_skill_command(&plugin, run_phase, &running_agent, &task_content, task.cycle);
+ let run_phase = determine_phase_variant(
+ "running",
+ task.worktree_path.as_deref(),
+ &task.id,
+ &plugin,
+ task.cycle,
+ );
+ let skill_cmd = resolve_skill_command(
+ &plugin,
+ run_phase,
+ &running_agent,
+ &task_content,
+ task.cycle,
+ );
let prompt = resolve_prompt(&plugin, run_phase, &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, run_phase);
- let auto_dismiss = plugin.as_ref().map_or_else(Vec::new, |p| p.auto_dismiss.clone());
+ let auto_dismiss = plugin
+ .as_ref()
+ .map_or_else(Vec::new, |p| p.auto_dismiss.clone());
spawn_send_to_agent(
Arc::clone(&self.state.tmux_ops),
Arc::clone(&self.state.agent_registry),
- session_name.clone(), task.agent.clone(), running_agent.clone(), agent_switch,
- skill_cmd, prompt, prompt_trigger, task_content, auto_dismiss,
+ session_name.clone(),
+ task.agent.clone(),
+ running_agent.clone(),
+ agent_switch,
+ skill_cmd,
+ prompt,
+ prompt_trigger,
+ task_content,
+ auto_dismiss,
);
task.agent = running_agent;
}
@@ -3797,15 +4405,25 @@ impl App {
if let Some(session_name) = &task.session_name {
let plugin = self.load_task_plugin(task);
let task_content = task.content_text();
- let skill_cmd = resolve_skill_command(&plugin, "review", &review_agent, &task_content, task.cycle);
+ let skill_cmd =
+ resolve_skill_command(&plugin, "review", &review_agent, &task_content, task.cycle);
let prompt = resolve_prompt(&plugin, "review", &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, "review");
- let auto_dismiss = plugin.as_ref().map_or_else(Vec::new, |p| p.auto_dismiss.clone());
+ let auto_dismiss = plugin
+ .as_ref()
+ .map_or_else(Vec::new, |p| p.auto_dismiss.clone());
spawn_send_to_agent(
Arc::clone(&self.state.tmux_ops),
Arc::clone(&self.state.agent_registry),
- session_name.clone(), task.agent.clone(), review_agent.clone(), agent_switch,
- skill_cmd, prompt, prompt_trigger, task_content, auto_dismiss,
+ session_name.clone(),
+ task.agent.clone(),
+ review_agent.clone(),
+ agent_switch,
+ skill_cmd,
+ prompt,
+ prompt_trigger,
+ task_content,
+ auto_dismiss,
);
}
task.agent = review_agent.clone();
@@ -3827,7 +4445,8 @@ impl App {
self.state.pr_creation_rx = Some(rx);
std::thread::spawn(move || {
- let result = push_changes_to_existing_pr(&task_clone, git_ops.as_ref(), agent_ops.as_ref());
+ let result =
+ push_changes_to_existing_pr(&task_clone, git_ops.as_ref(), agent_ops.as_ref());
match result {
Ok(pr_url) => {
if let Ok(db) = crate::db::Database::open_project(&project_path_clone) {
@@ -3859,7 +4478,10 @@ impl App {
/// Returns Ok(true) if a confirmation popup was shown, Ok(false) to continue with db update.
fn transition_to_done(&mut self, task: &mut Task, project_path: &Path) -> Result<bool> {
if let Some(pr_number) = task.pr_number {
- let pr_state = self.state.git_provider_ops.get_pr_state(project_path, pr_number)?;
+ let pr_state = self
+ .state
+ .git_provider_ops
+ .get_pr_state(project_path, pr_number)?;
let confirm_state = match pr_state {
PullRequestState::Merged => DoneConfirmPrState::Merged,
PullRequestState::Closed => DoneConfirmPrState::Closed,
@@ -3875,9 +4497,10 @@ impl App {
}
// No PR β€” check for uncommitted changes
- let has_uncommitted = task.worktree_path.as_ref().map_or(false, |wt| {
- self.state.git_ops.has_changes(Path::new(wt))
- });
+ let has_uncommitted = task
+ .worktree_path
+ .as_ref()
+ .map_or(false, |wt| self.state.git_ops.has_changes(Path::new(wt)));
if has_uncommitted {
self.state.done_confirm_popup = Some(DoneConfirmPopup {
task_id: task.id.clone(),
@@ -3900,8 +4523,13 @@ impl App {
let project_path_clone = project_path.to_path_buf();
std::thread::spawn(move || {
cleanup_task_resources(
- &task_id_clone, &branch_name, &session_name, &worktree_path,
- &project_path_clone, tmux_ops.as_ref(), git_ops.as_ref(),
+ &task_id_clone,
+ &branch_name,
+ &session_name,
+ &worktree_path,
+ &project_path_clone,
+ tmux_ops.as_ref(),
+ git_ops.as_ref(),
);
});
Ok(false)
@@ -3910,14 +4538,22 @@ impl App {
/// Start a research session for a Backlog task (creates worktree, reused in planning)
fn start_research(&mut self, task_id: &str) -> Result<()> {
// Don't start if a setup is already in progress
- if self.state.setup_rx.is_some() { return Ok(()) }
+ if self.state.setup_rx.is_some() {
+ return Ok(());
+ }
let mut task = {
- let Some(db) = &self.state.db else { return Ok(()) };
- let Some(task) = db.get_task(task_id)? else { return Ok(()) };
+ let Some(db) = &self.state.db else {
+ return Ok(());
+ };
+ let Some(task) = db.get_task(task_id)? else {
+ return Ok(());
+ };
task
};
- let Some(project_path) = self.state.project_path.clone() else { return Ok(()) };
+ let Some(project_path) = self.state.project_path.clone() else {
+ return Ok(());
+ };
// Stamp plugin on task for research (only if not already set at task creation)
if task.plugin.is_none() {
@@ -3927,8 +4563,9 @@ impl App {
let plugin = self.load_task_plugin(&task);
// Block if plugin has no research command (e.g. OpenSpec uses planning as first phase)
- let has_research_cmd = plugin.as_ref()
- .map_or(false, |p| p.commands.research.is_some() || p.commands.preresearch.is_some());
+ let has_research_cmd = plugin.as_ref().map_or(false, |p| {
+ p.commands.research.is_some() || p.commands.preresearch.is_some()
+ });
if !has_research_cmd {
self.state.warning_message = Some((
"This plugin has no research phase β€” move to Planning instead".to_string(),
@@ -3943,6 +4580,7 @@ impl App {
let all_agents = collect_phase_agents(&self.state.config);
let project_name = self.state.project_name.clone();
+ let base_branch = self.state.config.base_branch.clone();
let copy_files = self.state.config.copy_files.clone();
let init_script = self.state.config.init_script.clone();
@@ -3953,7 +4591,9 @@ impl App {
let task_id = task.id.clone();
let task_title = task.title.clone();
let task_cycle = task.cycle;
- let auto_dismiss = plugin.as_ref().map_or_else(Vec::new, |p| p.auto_dismiss.clone());
+ let auto_dismiss = plugin
+ .as_ref()
+ .map_or_else(Vec::new, |p| p.auto_dismiss.clone());
let (tx, rx) = mpsc::channel();
self.state.setup_rx = Some(rx);
@@ -3971,6 +4611,7 @@ impl App {
&project_path,
&project_name,
"",
+ &base_branch,
copy_files,
init_script,
&plugin,
@@ -3991,14 +4632,32 @@ impl App {
let use_preresearch = plugin.as_ref().map_or(false, |p| {
p.commands.preresearch.is_some()
&& !p.artifacts.preresearch.is_empty()
- && !p.artifacts.preresearch.iter().all(|a| {
- Path::new(&worktree_path).join(a).exists()
- })
+ && !p
+ .artifacts
+ .preresearch
+ .iter()
+ .all(|a| Path::new(&worktree_path).join(a).exists())
});
- let research_phase = if use_preresearch { "preresearch" } else { "research" };
+ let research_phase = if use_preresearch {
+ "preresearch"
+ } else {
+ "research"
+ };
- let prompt = resolve_prompt(&plugin, research_phase, &task_content, &task_id, task_cycle);
- let skill_cmd = resolve_skill_command(&plugin, research_phase, &agent_name, &task_content, task_cycle);
+ let prompt = resolve_prompt(
+ &plugin,
+ research_phase,
+ &task_content,
+ &task_id,
+ task_cycle,
+ );
+ let skill_cmd = resolve_skill_command(
+ &plugin,
+ research_phase,
+ &agent_name,
+ &task_content,
+ task_cycle,
+ );
let prompt_trigger = resolve_prompt_trigger(&plugin, research_phase);
let _ = tx.send(SetupResult {
@@ -4014,7 +4673,16 @@ impl App {
// Wait for agent ready and send skill+prompt
if let Some(target) = wait_for_agent_ready(&tmux_ops, &target) {
- send_skill_and_prompt(&tmux_ops, &target, &skill_cmd, &prompt, &prompt_trigger, &task_content, &agent_name, &auto_dismiss);
+ send_skill_and_prompt(
+ &tmux_ops,
+ &target,
+ &skill_cmd,
+ &prompt,
+ &prompt_trigger,
+ &task_content,
+ &agent_name,
+ &auto_dismiss,
+ );
}
}
Err(e) => {
@@ -4051,7 +4719,10 @@ impl App {
}
let (mut task, project_path) = match (
- self.state.db.as_ref().and_then(|db| db.get_task(task_id).ok().flatten()),
+ self.state
+ .db
+ .as_ref()
+ .and_then(|db| db.get_task(task_id).ok().flatten()),
self.state.project_path.clone(),
) {
(Some(t), Some(p)) => (t, p),
@@ -4059,7 +4730,10 @@ impl App {
};
if task.status != TaskStatus::Backlog {
- anyhow::bail!("Task must be in Backlog to move to Running (current: {})", task.status.as_str());
+ anyhow::bail!(
+ "Task must be in Backlog to move to Running (current: {})",
+ task.status.as_str()
+ );
}
// Stamp plugin on task before checking research requirement
@@ -4069,7 +4743,10 @@ impl App {
// Block if running phase doesn't accept {task} and no prior phase artifact exists
let plugin_check = self.load_task_plugin(&task);
- if plugin_check.as_ref().map_or(false, |p| !p.phase_accepts_task("running")) {
+ if plugin_check
+ .as_ref()
+ .map_or(false, |p| !p.phase_accepts_task("running"))
+ {
let has_prior = task.worktree_path.as_ref().map_or(false, |wt| {
research_artifact_exists(wt, &task.id, &plugin_check)
|| phase_artifact_exists(wt, TaskStatus::Planning, &plugin_check, task.cycle)
@@ -4091,9 +4768,16 @@ impl App {
let running_agent = self.state.config.agent_for_phase("running").to_string();
let all_agents = collect_phase_agents(&self.state.config);
let prompt = resolve_prompt(&plugin, "running", &task_content, &task.id, task.cycle);
- let skill_cmd = resolve_skill_command(&plugin, "running", &running_agent, &task_content, task.cycle);
+ let skill_cmd = resolve_skill_command(
+ &plugin,
+ "running",
+ &running_agent,
+ &task_content,
+ task.cycle,
+ );
let prompt_trigger = resolve_prompt_trigger(&plugin, "running");
let project_name = self.state.project_name.clone();
+ let base_branch = self.state.config.base_branch.clone();
let copy_files = self.state.config.copy_files.clone();
let init_script = self.state.config.init_script.clone();
let tmux_ops = Arc::clone(&self.state.tmux_ops);
@@ -4102,7 +4786,9 @@ impl App {
let task_id = task.id.clone();
let task_title = task.title.clone();
let running_agent_clone = running_agent.clone();
- let auto_dismiss = plugin.as_ref().map_or_else(Vec::new, |p| p.auto_dismiss.clone());
+ let auto_dismiss = plugin
+ .as_ref()
+ .map_or_else(Vec::new, |p| p.auto_dismiss.clone());
let (tx, rx) = mpsc::channel();
self.state.setup_rx = Some(rx);
@@ -4117,6 +4803,7 @@ impl App {
&project_path,
&project_name,
&prompt,
+ &base_branch,
copy_files,
init_script,
&plugin,
@@ -4142,7 +4829,16 @@ impl App {
});
if let Some(target) = wait_for_agent_ready(&tmux_ops, &target) {
- send_skill_and_prompt(&tmux_ops, &target, &skill_cmd, &prompt, &prompt_trigger, &task_content, &running_agent_clone, &auto_dismiss);
+ send_skill_and_prompt(
+ &tmux_ops,
+ &target,
+ &skill_cmd,
+ &prompt,
+ &prompt_trigger,
+ &task_content,
+ &running_agent_clone,
+ &auto_dismiss,
+ );
}
}
Err(e) => {
@@ -4173,7 +4869,8 @@ impl App {
}
// Switch agent if running phase uses a different agent than review
- let (running_agent, agent_switch) = needs_agent_switch(&self.state.config, &task, "running");
+ let (running_agent, agent_switch) =
+ needs_agent_switch(&self.state.config, &task, "running");
if agent_switch {
if let Some(session_name) = &task.session_name {
let session_clone = session_name.clone();
@@ -4184,7 +4881,12 @@ impl App {
std::thread::spawn(move || {
let agent_ops = agent_registry.get(&running_agent_clone);
let new_cmd = agent_ops.build_interactive_command("");
- switch_agent_in_tmux(tmux_ops.as_ref(), &session_clone, &current_agent_clone, &new_cmd);
+ switch_agent_in_tmux(
+ tmux_ops.as_ref(),
+ &session_clone,
+ &current_agent_clone,
+ &new_cmd,
+ );
});
}
}
@@ -4210,13 +4912,25 @@ impl App {
task.cycle += 1;
// Switch agent if planning phase uses a different agent than review
- let (planning_agent, agent_switch) = needs_agent_switch(&self.state.config, &task, "planning");
+ let (planning_agent, agent_switch) =
+ needs_agent_switch(&self.state.config, &task, "planning");
let plugin = self.load_task_plugin(&task);
// Resolve skill command and prompt for the new planning phase
- let task_content = task.description.as_deref().unwrap_or(&task.title).to_string();
- let skill_cmd = resolve_skill_command(&plugin, "planning", &planning_agent, &task_content, task.cycle);
- let prompt = resolve_prompt(&plugin, "planning", &task_content, &task.id, task.cycle);
+ let task_content = task
+ .description
+ .as_deref()
+ .unwrap_or(&task.title)
+ .to_string();
+ let skill_cmd = resolve_skill_command(
+ &plugin,
+ "planning",
+ &planning_agent,
+ &task_content,
+ task.cycle,
+ );
+ let prompt =
+ resolve_prompt(&plugin, "planning", &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, "planning");
if let Some(session_name) = &task.session_name {
@@ -4226,15 +4940,31 @@ impl App {
let planning_agent_clone = planning_agent.clone();
let current_agent_clone = task.agent.clone();
let task_content_clone = task_content.clone();
- let auto_dismiss = plugin.as_ref().map_or_else(Vec::new, |p| p.auto_dismiss.clone());
+ let auto_dismiss = plugin
+ .as_ref()
+ .map_or_else(Vec::new, |p| p.auto_dismiss.clone());
std::thread::spawn(move || {
if agent_switch {
let agent_ops = agent_registry.get(&planning_agent_clone);
let new_cmd = agent_ops.build_interactive_command("");
- switch_agent_in_tmux(tmux_ops.as_ref(), &session_clone, &current_agent_clone, &new_cmd);
+ switch_agent_in_tmux(
+ tmux_ops.as_ref(),
+ &session_clone,
+ &current_agent_clone,
+ &new_cmd,
+ );
let _ = wait_for_agent_ready(&tmux_ops, &session_clone);
}
- send_skill_and_prompt(&tmux_ops, &session_clone, &skill_cmd, &prompt, &prompt_trigger, &task_content_clone, &planning_agent_clone, &auto_dismiss);
+ send_skill_and_prompt(
+ &tmux_ops,
+ &session_clone,
+ &skill_cmd,
+ &prompt,
+ &prompt_trigger,
+ &task_content_clone,
+ &planning_agent_clone,
+ &auto_dismiss,
+ );
});
}
@@ -4256,7 +4986,8 @@ impl App {
}
// Switch agent if planning phase uses a different agent than running
- let (planning_agent, agent_switch) = needs_agent_switch(&self.state.config, &task, "planning");
+ let (planning_agent, agent_switch) =
+ needs_agent_switch(&self.state.config, &task, "planning");
if agent_switch {
if let Some(session_name) = &task.session_name {
let session_clone = session_name.clone();
@@ -4267,7 +4998,12 @@ impl App {
std::thread::spawn(move || {
let agent_ops = agent_registry.get(&planning_agent_clone);
let new_cmd = agent_ops.build_interactive_command("");
- switch_agent_in_tmux(tmux_ops.as_ref(), &session_clone, &current_agent_clone, &new_cmd);
+ switch_agent_in_tmux(
+ tmux_ops.as_ref(),
+ &session_clone,
+ &current_agent_clone,
+ &new_cmd,
+ );
});
}
}
@@ -4286,7 +5022,9 @@ impl App {
/// Poll the transition_requests table for unprocessed requests and execute them.
fn process_transition_requests(&mut self) -> Result<()> {
- let Some(db) = &self.state.db else { return Ok(()) };
+ let Some(db) = &self.state.db else {
+ return Ok(());
+ };
let pending = db.get_pending_transition_requests()?;
if pending.is_empty() {
return Ok(());
@@ -4336,7 +5074,9 @@ impl App {
);
}
if task.session_name.is_some() {
- anyhow::bail!("Task already has an active session (research may already be running)");
+ anyhow::bail!(
+ "Task already has an active session (research may already be running)"
+ );
}
self.start_research(&req.task_id)?;
}
@@ -4399,7 +5139,10 @@ impl App {
task.status.as_str()
);
}
- task.escalation_note = req.reason.clone().or_else(|| Some("Needs attention".to_string()));
+ task.escalation_note = req
+ .reason
+ .clone()
+ .or_else(|| Some("Needs attention".to_string()));
task.updated_at = chrono::Utc::now();
if let Some(db) = &self.state.db {
db.update_task(&task)?;
@@ -4463,8 +5206,7 @@ impl App {
let task_content = task.content_text();
let skill_cmd =
resolve_skill_command(&plugin, "review", &review_agent, &task_content, task.cycle);
- let prompt =
- resolve_prompt(&plugin, "review", &task_content, &task.id, task.cycle);
+ let prompt = resolve_prompt(&plugin, "review", &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, "review");
let auto_dismiss = plugin
.as_ref()
@@ -4511,23 +5253,35 @@ impl App {
// If orchestrator is running, open the popup to view it
if let Some(ref orch_target) = self.state.orchestrator_session {
- if self.state.tmux_ops.window_exists(orch_target).unwrap_or(false) {
+ if self
+ .state
+ .tmux_ops
+ .window_exists(orch_target)
+ .unwrap_or(false)
+ {
let mut popup = ShellPopup::new("Orchestrator".to_string(), orch_target.clone());
if let Ok((_term_width, term_height)) = crossterm::terminal::size() {
let pane_width = SHELL_POPUP_CONTENT_WIDTH;
- let popup_height = (term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;
+ let popup_height =
+ (term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;
let pane_height = popup_height.saturating_sub(4);
- let _ = self.state.tmux_ops.resize_window(orch_target, pane_width, pane_height);
+ let _ = self
+ .state
+ .tmux_ops
+ .resize_window(orch_target, pane_width, pane_height);
popup.last_pane_size = Some((pane_width, pane_height));
std::thread::sleep(std::time::Duration::from_millis(200));
}
- popup.cached_content = capture_tmux_pane_with_history(orch_target, 500, self.state.tmux_ops.as_ref());
+ popup.cached_content =
+ capture_tmux_pane_with_history(orch_target, 500, self.state.tmux_ops.as_ref());
self.state.shell_popup = Some(popup);
return Ok(());
} else {
// Window gone, clear the session
self.state.orchestrator_session = None;
- self.state.orchestrator_ready.store(false, Ordering::Release);
+ self.state
+ .orchestrator_ready
+ .store(false, Ordering::Release);
}
}
@@ -4562,22 +5316,34 @@ impl App {
)?;
self.state.orchestrator_session = Some(orch_target.clone());
- self.state.orchestrator_ready.store(false, Ordering::Release);
+ self.state
+ .orchestrator_ready
+ .store(false, Ordering::Release);
// Open the popup immediately so the user can see the orchestrator starting
let mut popup = ShellPopup::new("Orchestrator".to_string(), orch_target.clone());
if let Ok((_term_width, term_height)) = crossterm::terminal::size() {
let pane_width = SHELL_POPUP_CONTENT_WIDTH;
- let popup_height = (term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;
+ let popup_height =
+ (term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;
let pane_height = popup_height.saturating_sub(4);
- let _ = self.state.tmux_ops.resize_window(&orch_target, pane_width, pane_height);
+ let _ = self
+ .state
+ .tmux_ops
+ .resize_window(&orch_target, pane_width, pane_height);
popup.last_pane_size = Some((pane_width, pane_height));
}
- popup.cached_content = capture_tmux_pane_with_history(&orch_target, 500, self.state.tmux_ops.as_ref());
+ popup.cached_content =
+ capture_tmux_pane_with_history(&orch_target, 500, self.state.tmux_ops.as_ref());
self.state.shell_popup = Some(popup);
// Deploy orchestrate skill to project root so the agent can discover it
- deploy_skill(&project_path, "agtx-orchestrate", skills::ORCHESTRATE_SKILL, &default_agent);
+ deploy_skill(
+ &project_path,
+ "agtx-orchestrate",
+ skills::ORCHESTRATE_SKILL,
+ &default_agent,
+ );
// Send the /agtx:orchestrate command once the agent is ready
let skill_cmd = skills::transform_plugin_command("/agtx:orchestrate", &default_agent)
@@ -4607,21 +5373,26 @@ impl App {
// Resize tmux window to match popup dimensions (uses same constants as draw_shell_popup)
if let Ok((_term_width, term_height)) = crossterm::terminal::size() {
let pane_width = SHELL_POPUP_CONTENT_WIDTH;
- let popup_height = (term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;
+ let popup_height =
+ (term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;
let pane_height = popup_height.saturating_sub(4); // -4 for borders + header/footer
let target = format!("{}:{}", self.state.project_name, window_name);
// 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 _ = self.state.tmux_ops.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));
// Give TUI apps (OpenCode, Gemini Ink) time to re-render after resize
std::thread::sleep(std::time::Duration::from_millis(200));
}
// Capture initial content
- popup.cached_content = capture_tmux_pane_with_history(window_name, 500, self.state.tmux_ops.as_ref());
+ popup.cached_content =
+ capture_tmux_pane_with_history(window_name, 500, self.state.tmux_ops.as_ref());
self.state.shell_popup = Some(popup);
}
@@ -4632,7 +5403,11 @@ impl App {
/// Load the plugin that a specific task was created with.
/// Falls back to bundled agtx plugin for tasks with no explicit plugin.
fn load_task_plugin(&self, task: &Task) -> Option<WorkflowPlugin> {
- load_task_plugin(task, self.state.project_path.as_deref(), &self.state.config.default_agent)
+ load_task_plugin(
+ task,
+ self.state.project_path.as_deref(),
+ &self.state.config.default_agent,
+ )
}
pub fn refresh_tasks(&mut self) -> Result<()> {
@@ -4662,7 +5437,12 @@ impl App {
// Find current project in list and select it
if let Some(project_path) = &self.state.project_path {
let current_path = project_path.to_string_lossy();
- if let Some(pos) = self.state.projects.iter().position(|p| p.path == current_path) {
+ if let Some(pos) = self
+ .state
+ .projects
+ .iter()
+ .position(|p| p.path == current_path)
+ {
self.state.selected_project = pos;
}
}
@@ -4690,12 +5470,19 @@ impl App {
}
// Check window still exists
- if !self.state.tmux_ops.window_exists(&orch_target).unwrap_or(false) {
+ if !self
+ .state
+ .tmux_ops
+ .window_exists(&orch_target)
+ .unwrap_or(false)
+ {
return;
}
// Capture current pane content (bottom portion for comparison)
- let current_content = self.state.tmux_ops
+ let current_content = self
+ .state
+ .tmux_ops
.capture_pane(&orch_target)
.unwrap_or_default();
@@ -4755,22 +5542,42 @@ impl App {
const CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(2);
// Collect tasks that need checking (cache expired or never checked)
- let tasks_to_check: Vec<_> = self.state.board.tasks.iter()
+ let tasks_to_check: Vec<_> = self
+ .state
+ .board
+ .tasks
+ .iter()
.filter(|t| {
- matches!(t.status, TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review)
- || (t.status == TaskStatus::Backlog && t.session_name.is_some())
+ matches!(
+ t.status,
+ TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review
+ ) || (t.status == TaskStatus::Backlog && t.session_name.is_some())
})
.filter(|t| t.worktree_path.is_some() || t.session_name.is_some())
.filter(|t| {
- self.state.phase_status_cache.get(&t.id)
+ self.state
+ .phase_status_cache
+ .get(&t.id)
.map_or(true, |(_, ts)| now.duration_since(*ts) >= CACHE_TTL)
})
.map(|t| {
// was_ready: true if previously Ready OR not in cache yet (first poll after startup).
// This avoids false "newly ready" notifications for tasks that were already done before restart.
- let was_ready = self.state.phase_status_cache.get(&t.id)
+ let was_ready = self
+ .state
+ .phase_status_cache
+ .get(&t.id)
.map_or(true, |(prev, _)| *prev == PhaseStatus::Ready);
- (t.id.clone(), t.status, t.worktree_path.clone(), t.plugin.clone(), t.session_name.clone(), t.cycle, was_ready, t.agent.clone())
+ (
+ t.id.clone(),
+ t.status,
+ t.worktree_path.clone(),
+ t.plugin.clone(),
+ t.session_name.clone(),
+ t.cycle,
+ was_ready,
+ t.agent.clone(),
+ )
})
.collect();
@@ -4789,22 +5596,34 @@ impl App {
let mut plugin_cache: HashMap<Option<String>, Option<WorkflowPlugin>> = HashMap::new();
let mut statuses = Vec::new();
- for (task_id, status, worktree_path, task_plugin, session_name, cycle, was_ready, agent) in tasks_to_check {
- let plugin = plugin_cache.entry(task_plugin.clone()).or_insert_with(|| {
- match &task_plugin {
- Some(name) => WorkflowPlugin::load(name, project_path.as_deref())
- .ok()
- .or_else(|| skills::load_bundled_plugin(name)),
- None => skills::load_bundled_plugin("agtx"),
- }
- });
+ for (
+ task_id,
+ status,
+ worktree_path,
+ task_plugin,
+ session_name,
+ cycle,
+ was_ready,
+ agent,
+ ) in tasks_to_check
+ {
+ let plugin =
+ plugin_cache
+ .entry(task_plugin.clone())
+ .or_insert_with(|| match &task_plugin {
+ Some(name) => WorkflowPlugin::load(name, project_path.as_deref())
+ .ok()
+ .or_else(|| skills::load_bundled_plugin(name)),
+ None => skills::load_bundled_plugin("agtx"),
+ });
let phase_status = if status == TaskStatus::Backlog {
// Preresearch copy-back
if let (Some(ref wt), Some(ref pp)) = (&worktree_path, &project_path) {
if let Some(ref p) = plugin {
if let Some(entries) = p.copy_back.get("preresearch") {
- let all_at_root = !entries.is_empty() && entries.iter().all(|e| pp.join(e).exists());
+ let all_at_root = !entries.is_empty()
+ && entries.iter().all(|e| pp.join(e).exists());
if !all_at_root && !p.artifacts.preresearch.is_empty() {
let any_artifact = p.artifacts.preresearch.iter().all(|a| {
let path = Path::new(wt).join(a);
@@ -4822,10 +5641,14 @@ impl App {
}
}
- let found = worktree_path.as_ref().map_or(false, |wt| {
- research_artifact_exists(wt, &task_id, plugin)
- });
- if found { PhaseStatus::Ready } else { PhaseStatus::Working }
+ let found = worktree_path
+ .as_ref()
+ .map_or(false, |wt| research_artifact_exists(wt, &task_id, plugin));
+ if found {
+ PhaseStatus::Ready
+ } else {
+ PhaseStatus::Working
+ }
} else if let Some(ref wt) = worktree_path {
if phase_artifact_exists(wt, status, plugin, cycle) {
PhaseStatus::Ready
@@ -4839,7 +5662,11 @@ impl App {
// Copy-back on Working β†’ Ready transition
if phase_status == PhaseStatus::Ready && !was_ready {
if let (Some(ref wt), Some(ref pp)) = (&worktree_path, &project_path) {
- let phase_name = if status == TaskStatus::Backlog { "research" } else { status.as_str() };
+ let phase_name = if status == TaskStatus::Backlog {
+ "research"
+ } else {
+ status.as_str()
+ };
if let Some(ref p) = plugin {
if let Some(entries) = p.copy_back.get(phase_name) {
copy_back_to_project(Path::new(wt), pp, entries);
@@ -4888,7 +5715,9 @@ impl App {
if phase == PhaseStatus::Working {
// Idle detection: check if content hash has been stable for 15s
if let Some(hash) = task_status.content_hash {
- let entry = self.state.pane_content_hashes
+ let entry = self
+ .state
+ .pane_content_hashes
.entry(task_status.task_id.clone())
.or_insert((hash, now));
if entry.0 != hash {
@@ -4902,18 +5731,32 @@ impl App {
}
let newly_ready = phase == PhaseStatus::Ready && !task_status.was_ready;
- self.state.phase_status_cache.insert(task_status.task_id.clone(), (phase, now));
+ self.state
+ .phase_status_cache
+ .insert(task_status.task_id.clone(), (phase, now));
// Notify orchestrator when a phase completes (newly Ready)
if newly_ready {
if self.state.orchestrator_session.is_some() {
if let Some(db) = &self.state.db {
- let task_title = self.state.board.tasks.iter()
+ let task_title = self
+ .state
+ .board
+ .tasks
+ .iter()
.find(|t| t.id == task_status.task_id)
.map(|t| t.title.as_str())
.unwrap_or("unknown");
- let phase_name = if task_status.status == TaskStatus::Backlog { "research" } else { task_status.status.as_str() };
- let short_id = if task_status.task_id.len() >= 8 { &task_status.task_id[..8] } else { &task_status.task_id };
+ let phase_name = if task_status.status == TaskStatus::Backlog {
+ "research"
+ } else {
+ task_status.status.as_str()
+ };
+ let short_id = if task_status.task_id.len() >= 8 {
+ &task_status.task_id[..8]
+ } else {
+ &task_status.task_id
+ };
let notif = crate::db::Notification::new(format!(
"Task \"{}\" ({}) completed phase: {}",
task_title, short_id, phase_name
@@ -4924,22 +5767,32 @@ impl App {
}
// Auto merge-conflict check for Review tasks
- if task_status.status == TaskStatus::Review && !self.state.merge_conflict_checked.contains(&task_status.task_id) {
+ if task_status.status == TaskStatus::Review
+ && !self
+ .state
+ .merge_conflict_checked
+ .contains(&task_status.task_id)
+ {
let should_check = match phase {
PhaseStatus::Ready => newly_ready,
- PhaseStatus::Idle => {
- self.state.pane_content_hashes.get(&task_status.task_id)
- .map_or(false, |(_, last_change)| {
- now.duration_since(*last_change) >= std::time::Duration::from_secs(30)
- })
- }
+ PhaseStatus::Idle => self
+ .state
+ .pane_content_hashes
+ .get(&task_status.task_id)
+ .map_or(false, |(_, last_change)| {
+ now.duration_since(*last_change) >= std::time::Duration::from_secs(30)
+ }),
_ => false,
};
if should_check {
- if let (Some(ref wt), Some(ref sn)) = (&task_status.worktree_path, &task_status.session_name) {
+ if let (Some(ref wt), Some(ref sn)) =
+ (&task_status.worktree_path, &task_status.session_name)
+ {
if self.state.tmux_ops.window_exists(sn).unwrap_or(false) {
- self.state.merge_conflict_checked.insert(task_status.task_id.clone());
+ self.state
+ .merge_conflict_checked
+ .insert(task_status.task_id.clone());
let git_ops = Arc::clone(&self.state.git_ops);
let tmux_ops = Arc::clone(&self.state.tmux_ops);
@@ -4975,18 +5828,26 @@ impl App {
// Stuck-task notification: fire once when Planning/Running task has been Idle for 1+ min
// Void plugin tasks are fully user-managed β€” no stuck notifications
- let task_plugin = self.state.board.tasks.iter()
+ let task_plugin = self
+ .state
+ .board
+ .tasks
+ .iter()
.find(|t| t.id == task_status.task_id)
.and_then(|t| t.plugin.as_deref());
- if matches!(task_status.status, TaskStatus::Planning | TaskStatus::Running)
- && phase == PhaseStatus::Idle
+ if matches!(
+ task_status.status,
+ TaskStatus::Planning | TaskStatus::Running
+ ) && phase == PhaseStatus::Idle
&& self.state.orchestrator_session.is_some()
&& should_send_stuck_notification(task_plugin)
{
let stuck_key = format!("{}:{}", task_status.task_id, task_status.status.as_str());
if !self.state.stuck_task_notified.contains(&stuck_key) {
// Track when this task first became Idle
- let idle_since = self.state.stuck_task_idle_since
+ let idle_since = self
+ .state
+ .stuck_task_idle_since
.entry(task_status.task_id.clone())
.or_insert(now);
@@ -4994,14 +5855,24 @@ impl App {
self.state.stuck_task_notified.insert(stuck_key);
if let Some(db) = &self.state.db {
- let task_title = self.state.board.tasks.iter()
+ let task_title = self
+ .state
+ .board
+ .tasks
+ .iter()
.find(|t| t.id == task_status.task_id)
.map(|t| t.title.as_str())
.unwrap_or("unknown");
- let short_id = if task_status.task_id.len() >= 8 { &task_status.task_id[..8] } else { &task_status.task_id };
+ let short_id = if task_status.task_id.len() >= 8 {
+ &task_status.task_id[..8]
+ } else {
+ &task_status.task_id
+ };
let notif = crate::db::Notification::new(format!(
"Task \"{}\" ({}) has been idle for 1m in phase: {}",
- task_title, short_id, task_status.status.as_str()
+ task_title,
+ short_id,
+ task_status.status.as_str()
));
let _ = db.create_notification(&notif);
}
@@ -5009,7 +5880,9 @@ impl App {
}
} else if phase != PhaseStatus::Idle {
// Task is no longer idle β€” reset the idle-since timer
- self.state.stuck_task_idle_since.remove(&task_status.task_id);
+ self.state
+ .stuck_task_idle_since
+ .remove(&task_status.task_id);
}
}
@@ -5121,7 +5994,10 @@ fn check_orchestrator_idle(
} else {
// Content unchanged β€” check stability timer
match stable_since {
- Some(t) if t.elapsed() >= std::time::Duration::from_secs(ORCHESTRATOR_IDLE_FALLBACK_SECS) => {
+ Some(t)
+ if t.elapsed()
+ >= std::time::Duration::from_secs(ORCHESTRATOR_IDLE_FALLBACK_SECS) =>
+ {
OrchestratorIdleResult::Idle
}
_ => OrchestratorIdleResult::Waiting,
@@ -5129,7 +6005,11 @@ fn check_orchestrator_idle(
}
}
-fn ensure_project_tmux_session(project_name: &str, project_path: &Path, tmux_ops: &dyn TmuxOperations) {
+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());
}
@@ -5160,7 +6040,13 @@ fn copy_back_to_project(worktree: &Path, project_root: &Path, entries: &[String]
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 { '-' })
+ .map(|c| {
+ if c.is_alphanumeric() || c == '-' || c == '_' {
+ c
+ } else {
+ '-'
+ }
+ })
.take(30)
.collect();
let title_slug = title_slug.trim_matches('-').to_string();
@@ -5182,7 +6068,9 @@ fn cleanup_task_for_done(
if let Some(worktree) = &task.worktree_path {
let artifacts_dir = Path::new(worktree).join(".agtx");
if artifacts_dir.exists() {
- let slug = task.branch_name.as_deref()
+ let slug = task
+ .branch_name
+ .as_deref()
.and_then(|b| b.strip_prefix("task/"))
.unwrap_or(&task.id);
let archive_dir = project_path.join(".agtx").join("archive").join(slug);
@@ -5227,7 +6115,8 @@ fn cleanup_task_resources(
if let Some(worktree) = worktree_path {
let artifacts_dir = Path::new(worktree).join(".agtx");
if artifacts_dir.exists() {
- let slug = branch_name.as_deref()
+ let slug = branch_name
+ .as_deref()
.and_then(|b| b.strip_prefix("task/"))
.unwrap_or(task_id);
let archive_dir = project_path.join(".agtx").join("archive").join(slug);
@@ -5265,6 +6154,7 @@ fn setup_task_worktree(
project_path: &Path,
project_name: &str,
prompt: &str,
+ base_branch: &str,
copy_files: Option<String>,
init_script: Option<String>,
plugin: &Option<WorkflowPlugin>,
@@ -5279,20 +6169,26 @@ fn setup_task_worktree(
let window_name = format!("task-{}", unique_slug);
let target = format!("{}:{}", project_name, window_name);
- // Create git worktree from main branch
- let worktree_path_str = match git_ops.create_worktree(project_path, &unique_slug) {
+ // Create git worktree from the configured base branch
+ let worktree_path_str = match git_ops.create_worktree(project_path, &unique_slug, base_branch) {
Ok(path) => path,
Err(e) => {
eprintln!("Failed to create worktree: {}", e);
- project_path.join(".agtx").join("worktrees").join(&unique_slug)
- .to_string_lossy().to_string()
+ project_path
+ .join(".agtx")
+ .join("worktrees")
+ .join(&unique_slug)
+ .to_string_lossy()
+ .to_string()
}
};
// Initialize worktree: copy files and run init script
// Merge plugin-level copy_files with project-level copy_files
let worktree_path = Path::new(&worktree_path_str);
- let copy_dirs = plugin.as_ref().map_or_else(Vec::new, |p| p.copy_dirs.clone());
+ let copy_dirs = plugin
+ .as_ref()
+ .map_or_else(Vec::new, |p| p.copy_dirs.clone());
let merged_copy_files = {
let mut parts: Vec<String> = Vec::new();
if let Some(ref cf) = copy_files {
@@ -5305,7 +6201,11 @@ fn setup_task_worktree(
parts.push(p.copy_files.join(","));
}
}
- if parts.is_empty() { None } else { Some(parts.join(",")) }
+ if parts.is_empty() {
+ None
+ } else {
+ Some(parts.join(","))
+ }
};
let init_warnings = git_ops.initialize_worktree(
project_path,
@@ -5365,7 +6265,8 @@ fn setup_task_worktree(
if let Some(ref script) = p.init_script {
let script = script.replace("{agent}", agent_name);
let output = std::process::Command::new("sh")
- .arg("-c").arg(&script)
+ .arg("-c")
+ .arg(&script)
.current_dir(&worktree_path_str)
.output();
match output {
@@ -5388,7 +6289,8 @@ fn setup_task_worktree(
// Build the interactive command. For agents with skill/command support,
// start with no prompt β€” the skill command and task content are sent via send_keys.
- let has_skill_support = resolve_skill_command(plugin, "planning", agent_name, "", task.cycle).is_some();
+ let has_skill_support =
+ resolve_skill_command(plugin, "planning", agent_name, "", task.cycle).is_some();
let agent_cmd = if has_skill_support {
agent_ops.build_interactive_command("")
} else {
@@ -5436,7 +6338,11 @@ fn delete_task_resources(
/// 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, exclude_prefixes: &[&str]) -> String {
+fn collect_task_diff(
+ worktree_path: &str,
+ git_ops: &dyn GitOperations,
+ exclude_prefixes: &[&str],
+) -> String {
let worktree = Path::new(worktree_path);
let mut sections = Vec::new();
@@ -5462,7 +6368,10 @@ fn collect_task_diff(worktree_path: &str, git_ops: &dyn GitOperations, exclude_p
continue;
}
// Skip files in copied directories (agent configs, plugin dirs)
- if exclude_prefixes.iter().any(|prefix| file.starts_with(&format!("{}/", prefix.trim_end_matches('/')))) {
+ if exclude_prefixes
+ .iter()
+ .any(|prefix| file.starts_with(&format!("{}/", prefix.trim_end_matches('/'))))
+ {
continue;
}
// Show diff for untracked file (as if adding new file)
@@ -5531,7 +6440,11 @@ fn centered_rect_fixed_width(fixed_width: u16, percent_y: u16, r: Rect) -> Rect
}
/// Capture content from a tmux pane with history (with ANSI escape sequences)
-fn capture_tmux_pane_with_history(window_name: &str, history_lines: i32, tmux_ops: &dyn TmuxOperations) -> Vec<u8> {
+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
@@ -5603,7 +6516,11 @@ fn create_pr_with_content(
// Commit if there are staged changes
if has_changes {
- let commit_msg = format!("{}\n\nCo-Authored-By: {}", pr_title, agent_ops.co_author_string());
+ let commit_msg = format!(
+ "{}\n\nCo-Authored-By: {}",
+ pr_title,
+ agent_ops.co_author_string()
+ );
git_ops.commit(worktree_path, &commit_msg)?;
}
@@ -5638,7 +6555,10 @@ fn push_changes_to_existing_pr(
// Commit if there are staged changes
if has_changes {
- let commit_msg = format!("Address review comments\n\nCo-Authored-By: {}", agent_ops.co_author_string());
+ let commit_msg = format!(
+ "Address review comments\n\nCo-Authored-By: {}",
+ agent_ops.co_author_string()
+ );
git_ops.commit(worktree_path, &commit_msg)?;
}
@@ -5648,7 +6568,10 @@ fn push_changes_to_existing_pr(
}
// Return the existing PR URL
- Ok(task.pr_url.clone().unwrap_or_else(|| "Changes pushed to existing PR".to_string()))
+ Ok(task
+ .pr_url
+ .clone()
+ .unwrap_or_else(|| "Changes pushed to existing PR".to_string()))
}
/// Send a key to a tmux pane
@@ -5739,10 +6662,7 @@ fn parse_sgr(seq: &str, mut style: Style) -> Style {
return Style::default();
}
- let codes: Vec<u8> = seq
- .split(';')
- .filter_map(|s| s.parse().ok())
- .collect();
+ let codes: Vec<u8> = seq.split(';').filter_map(|s| s.parse().ok()).collect();
let mut i = 0;
while i < codes.len() {
@@ -5899,7 +6819,12 @@ fn build_highlighted_text<'a>(
}
/// Fuzzy find files in a directory (respects .gitignore)
-fn fuzzy_find_files(project_path: &Path, pattern: &str, max_results: usize, git_ops: &dyn GitOperations) -> Vec<String> {
+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 files = git_ops.list_files(project_path);
@@ -5931,7 +6856,11 @@ fn fuzzy_find_files(project_path: &Path, pattern: &str, max_results: usize, git_
// Sort by score (higher is better)
matches.sort_by(|a, b| b.1.cmp(&a.1));
- matches.into_iter().take(max_results).map(|(path, _)| path).collect()
+ matches
+ .into_iter()
+ .take(max_results)
+ .map(|(path, _)| path)
+ .collect()
}
/// Calculate fuzzy match score (higher is better, 0 means no match)
@@ -5980,24 +6909,36 @@ fn fuzzy_score(haystack: &str, needle: &str) -> i32 {
/// Resolve the task prompt for a given phase transition, using plugin prompt template.
/// Substitutes {task}, {task_id}, and {phase} placeholders. Returns empty if no template is configured.
-fn resolve_prompt(plugin: &Option<WorkflowPlugin>, phase: &str, task_content: &str, task_id: &str, cycle: i32) -> String {
+fn resolve_prompt(
+ plugin: &Option<WorkflowPlugin>,
+ phase: &str,
+ task_content: &str,
+ task_id: &str,
+ cycle: i32,
+) -> String {
let template = match phase {
- "preresearch" | "research" => plugin.as_ref()
+ "preresearch" | "research" => plugin
+ .as_ref()
.and_then(|p| p.prompts.research.as_deref())
.unwrap_or(""),
- "planning" => plugin.as_ref()
+ "planning" => plugin
+ .as_ref()
.and_then(|p| p.prompts.planning.as_deref())
.unwrap_or(""),
- "planning_with_research" => plugin.as_ref()
+ "planning_with_research" => plugin
+ .as_ref()
.and_then(|p| p.prompts.planning_with_research.as_deref())
.unwrap_or(""),
- "running" => plugin.as_ref()
+ "running" => plugin
+ .as_ref()
.and_then(|p| p.prompts.running.as_deref())
.unwrap_or(""),
- "running_with_research_or_planning" => plugin.as_ref()
+ "running_with_research_or_planning" => plugin
+ .as_ref()
.and_then(|p| p.prompts.running_with_research_or_planning.as_deref())
.unwrap_or(""),
- "review" => plugin.as_ref()
+ "review" => plugin
+ .as_ref()
.and_then(|p| p.prompts.review.as_deref())
.unwrap_or(""),
_ => return task_content.to_string(),
@@ -6015,13 +6956,22 @@ fn resolve_prompt(plugin: &Option<WorkflowPlugin>, phase: &str, task_content: &s
/// Resolve the skill command to send via send_keys for a given phase.
/// Returns the plugin command transformed for the target agent, or None if no command is configured.
-fn resolve_skill_command(plugin: &Option<WorkflowPlugin>, phase: &str, agent_name: &str, task_content: &str, cycle: i32) -> Option<String> {
+fn resolve_skill_command(
+ plugin: &Option<WorkflowPlugin>,
+ phase: &str,
+ agent_name: &str,
+ task_content: &str,
+ cycle: i32,
+) -> Option<String> {
let p = plugin.as_ref()?;
// Commands are stored in canonical form (Claude/Gemini syntax) and transformed per agent
// Commands may contain {task} and {phase} placeholders
let cmd = match phase {
- "preresearch" => p.commands.preresearch.as_deref()
+ "preresearch" => p
+ .commands
+ .preresearch
+ .as_deref()
.or(p.commands.research.as_deref()),
"research" => p.commands.research.as_deref(),
"planning" | "planning_with_research" => p.commands.planning.as_deref(),
@@ -6036,13 +6986,19 @@ fn resolve_skill_command(plugin: &Option<WorkflowPlugin>, phase: &str, agent_nam
}
// When a prior phase was done, strip {task} β€” agent already has context
- let expanded = if phase == "planning_with_research" || phase == "running_with_research_or_planning" {
- cmd.replace("{task}", "").trim().to_string()
- } else {
- // Collapse task content to single line for commands (newlines β†’ spaces)
- let task_oneline = task_content.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" ");
- cmd.replace("{task}", &task_oneline)
- };
+ let expanded =
+ if phase == "planning_with_research" || phase == "running_with_research_or_planning" {
+ cmd.replace("{task}", "").trim().to_string()
+ } else {
+ // Collapse task content to single line for commands (newlines β†’ spaces)
+ let task_oneline = task_content
+ .lines()
+ .map(|l| l.trim())
+ .filter(|l| !l.is_empty())
+ .collect::<Vec<_>>()
+ .join(" ");
+ cmd.replace("{task}", &task_oneline)
+ };
let expanded = expanded.replace("{phase}", &cycle.to_string());
skills::transform_plugin_command(&expanded, agent_name)
}
@@ -6069,7 +7025,16 @@ fn spawn_send_to_agent(
switch_agent_in_tmux(tmux_ops.as_ref(), &target, &current_agent, &new_cmd);
let _ = wait_for_agent_ready(&tmux_ops, &target);
}
- send_skill_and_prompt(&tmux_ops, &target, &skill_cmd, &prompt, &prompt_trigger, &task_content, &target_agent, &auto_dismiss);
+ send_skill_and_prompt(
+ &tmux_ops,
+ &target,
+ &skill_cmd,
+ &prompt,
+ &prompt_trigger,
+ &task_content,
+ &target_agent,
+ &auto_dismiss,
+ );
});
}
@@ -6102,15 +7067,25 @@ fn send_skill_and_prompt(
} else if !prompt.is_empty() {
Some(prompt.to_string())
} else {
- let oneline = task_content.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" ");
- if !oneline.is_empty() { Some(oneline) } else { None }
+ let oneline = task_content
+ .lines()
+ .map(|l| l.trim())
+ .filter(|l| !l.is_empty())
+ .collect::<Vec<_>>()
+ .join(" ");
+ if !oneline.is_empty() {
+ Some(oneline)
+ } else {
+ None
+ }
};
if let Some(text) = text_to_send {
let _ = tmux_ops.send_keys_literal(target, &text);
// Wait for text to appear in pane before sending Enter (Ink TUIs need time to render)
let check_str = text.lines().next().unwrap_or(&text);
- for _ in 0..20 { // up to 4s
+ for _ in 0..20 {
+ // up to 4s
std::thread::sleep(std::time::Duration::from_millis(200));
if let Ok(content) = tmux_ops.capture_pane(target) {
if content.contains(check_str) {
@@ -6146,7 +7121,8 @@ fn send_skill_and_prompt(
let mut last_content = String::new();
let mut stable_ticks = 0u32;
let mut change_count = 0u32;
- for _ in 0..75 { // 15s max
+ for _ in 0..75 {
+ // 15s max
std::thread::sleep(std::time::Duration::from_millis(200));
if let Ok(content) = tmux_ops.capture_pane(target) {
if content != last_content {
@@ -6155,7 +7131,8 @@ fn send_skill_and_prompt(
last_content = content;
} else if change_count >= 1 {
stable_ticks += 1;
- if stable_ticks >= 10 { // 2s of no changes after agent responded
+ if stable_ticks >= 10 {
+ // 2s of no changes after agent responded
break;
}
}
@@ -6170,7 +7147,12 @@ fn send_skill_and_prompt(
let _ = tmux_ops.send_keys(target, prompt);
} else {
// No command and no prompt (e.g. void plugin): prefill task in input
- let oneline = task_content.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" ");
+ let oneline = task_content
+ .lines()
+ .map(|l| l.trim())
+ .filter(|l| !l.is_empty())
+ .collect::<Vec<_>>()
+ .join(" ");
if !oneline.is_empty() {
let _ = tmux_ops.send_keys_literal(target, &oneline);
}
@@ -6182,26 +7164,33 @@ fn send_skill_and_prompt(
/// Resolve the prompt trigger text for a given phase.
/// When set, the system polls the tmux pane for this text before sending the prompt.
fn resolve_prompt_trigger(plugin: &Option<WorkflowPlugin>, phase: &str) -> Option<String> {
- plugin.as_ref().and_then(|p| {
- match phase {
+ plugin
+ .as_ref()
+ .and_then(|p| match phase {
"preresearch" | "research" => p.prompt_triggers.research.clone(),
"planning" | "planning_with_research" => p.prompt_triggers.planning.clone(),
"running" | "running_with_research_or_planning" => p.prompt_triggers.running.clone(),
"review" => p.prompt_triggers.review.clone(),
_ => None,
- }
- }).filter(|s| !s.is_empty())
+ })
+ .filter(|s| !s.is_empty())
}
/// Wait for a specific text to appear in a tmux pane, then return.
/// Returns true if the trigger was found, false if timed out.
/// Auto-dismiss rules are checked while waiting: when all detect patterns match
/// and the pane is stable for ~2s, the response keystrokes are sent automatically.
-fn wait_for_prompt_trigger(tmux_ops: &Arc<dyn TmuxOperations>, target: &str, trigger: &str, auto_dismiss: &[crate::config::AutoDismiss]) -> bool {
+fn wait_for_prompt_trigger(
+ tmux_ops: &Arc<dyn TmuxOperations>,
+ target: &str,
+ trigger: &str,
+ auto_dismiss: &[crate::config::AutoDismiss],
+) -> bool {
let mut last_content = String::new();
let mut stable_ticks = 0u32;
- for _ in 0..600 { // ~5 minutes (600 * 500ms)
+ for _ in 0..600 {
+ // ~5 minutes (600 * 500ms)
std::thread::sleep(std::time::Duration::from_millis(500));
if let Ok(content) = tmux_ops.capture_pane(target) {
if content == last_content {
@@ -6225,7 +7214,9 @@ fn wait_for_prompt_trigger(tmux_ops: &Arc<dyn TmuxOperations>, target: &str, tri
break;
}
}
- if last_content.is_empty() { continue; }
+ if last_content.is_empty() {
+ continue;
+ }
}
// Trigger as soon as the text is present in the pane.
@@ -6245,7 +7236,12 @@ fn should_send_stuck_notification(plugin_name: Option<&str>) -> bool {
/// Check if the phase artifact exists for a task in its worktree.
/// Tries both zero-padded (e.g. "01") and non-padded (e.g. "1") {phase} substitution.
-fn phase_artifact_exists(worktree_path: &str, status: TaskStatus, plugin: &Option<WorkflowPlugin>, cycle: i32) -> bool {
+fn phase_artifact_exists(
+ worktree_path: &str,
+ status: TaskStatus,
+ plugin: &Option<WorkflowPlugin>,
+ cycle: i32,
+) -> bool {
let rel_template = plugin.as_ref().and_then(|p| match status {
TaskStatus::Planning => p.artifacts.planning.as_deref(),
TaskStatus::Running => p.artifacts.running.as_deref(),
@@ -6253,14 +7249,23 @@ fn phase_artifact_exists(worktree_path: &str, status: TaskStatus, plugin: &Optio
_ => None,
});
- let Some(rel_template) = rel_template else { return false; };
+ let Some(rel_template) = rel_template else {
+ return false;
+ };
artifact_path_exists(worktree_path, rel_template, cycle)
}
/// Check if the research artifact exists for a task.
/// Tries both zero-padded (e.g. "01") and non-padded (e.g. "1") {phase} substitution.
-fn research_artifact_exists(worktree_path: &str, task_id: &str, plugin: &Option<WorkflowPlugin>) -> bool {
- let Some(template) = plugin.as_ref().and_then(|p| p.artifacts.research.as_deref()) else {
+fn research_artifact_exists(
+ worktree_path: &str,
+ task_id: &str,
+ plugin: &Option<WorkflowPlugin>,
+) -> bool {
+ let Some(template) = plugin
+ .as_ref()
+ .and_then(|p| p.artifacts.research.as_deref())
+ else {
return false;
};
let rel_template = template.replace("{task_id}", task_id);
@@ -6279,17 +7284,24 @@ fn determine_phase_variant(
) -> &'static str {
match phase {
"planning" => {
- let has_research = worktree_path.map_or(false, |wt| {
- research_artifact_exists(wt, task_id, plugin)
- });
- if has_research { "planning_with_research" } else { "planning" }
+ let has_research =
+ worktree_path.map_or(false, |wt| research_artifact_exists(wt, task_id, plugin));
+ if has_research {
+ "planning_with_research"
+ } else {
+ "planning"
+ }
}
"running" => {
let has_prior = worktree_path.map_or(false, |wt| {
research_artifact_exists(wt, task_id, plugin)
|| phase_artifact_exists(wt, TaskStatus::Planning, plugin, cycle)
});
- if has_prior { "running_with_research_or_planning" } else { "running" }
+ if has_prior {
+ "running_with_research_or_planning"
+ } else {
+ "running"
+ }
}
_ => {
// Phases without variants leak the &str β€” use a known static
@@ -6393,18 +7405,20 @@ fn collect_phase_agents(config: &MergedConfig) -> Vec<String> {
/// can fire for them rather than Check 1 firing too early.
/// Note: on systems where agents are installed via asdf/nvm, all agents run as `node`
/// and Check 1 never fires β€” AGENT_ACTIVE_INDICATORS is the only reliable signal there.
-const AGENT_COMMANDS: &[&str] = &["claude", "codex", "gemini", "copilot", "opencode", "agent", "python3", "python"];
+const AGENT_COMMANDS: &[&str] = &[
+ "claude", "codex", "gemini", "copilot", "opencode", "agent", "python3", "python",
+];
/// Strings in pane content that indicate a Node/Ink agent TUI is active and ready.
/// Used by `is_agent_active` to detect agents like Gemini and Cursor that run
/// inside bash/node and don't change `pane_current_command` to their own name.
/// Also used by `wait_for_agent_ready` (Check 2) to detect readiness for these agents.
const AGENT_ACTIVE_INDICATORS: &[&str] = &[
- "Claude Code", // Claude
- "Type your message", // Gemini
- "Ask anything", // OpenCode
- "Cursor Agent", // Cursor
- "OpenAI Codex", // Codex
+ "Claude Code", // Claude
+ "Type your message", // Gemini
+ "Ask anything", // OpenCode
+ "Cursor Agent", // Cursor
+ "OpenAI Codex", // Codex
];
/// Check if the pane is running a shell (i.e. the agent has exited).
@@ -6434,7 +7448,10 @@ fn is_agent_active(tmux_ops: &dyn TmuxOperations, target: &str) -> bool {
let bottom = lines.len().saturating_sub(5);
let tail = &lines[bottom..];
let tail_text = tail.join("\n");
- if AGENT_ACTIVE_INDICATORS.iter().any(|s| tail_text.contains(s)) {
+ if AGENT_ACTIVE_INDICATORS
+ .iter()
+ .any(|s| tail_text.contains(s))
+ {
return true;
}
}
@@ -6461,9 +7478,9 @@ fn switch_agent_in_tmux(
) {
// 1. Send the graceful exit command for the current agent.
let exit_cmd = match current_agent {
- "codex" => None, // Codex has no exit command β€” Ctrl+C is the only way
+ "codex" => None, // Codex has no exit command β€” Ctrl+C is the only way
"gemini" => Some("/quit"),
- "cursor" => None, // Ink/Node TUI β€” Ctrl+C is the only reliable exit
+ "cursor" => None, // Ink/Node TUI β€” Ctrl+C is the only reliable exit
_ => Some("/exit"), // claude, opencode, and others
};
@@ -6476,7 +7493,8 @@ fn switch_agent_in_tmux(
// 2. Poll for shell (agent exited). If the agent was busy, the exit command
// may have been queued β€” so we wait up to 3s for it to take effect.
let mut found_shell = false;
- for _ in 0..30 { // 3s
+ for _ in 0..30 {
+ // 3s
std::thread::sleep(std::time::Duration::from_millis(100));
if is_pane_at_shell(tmux_ops, target) {
found_shell = true;
@@ -6494,7 +7512,8 @@ fn switch_agent_in_tmux(
}
// Wait for shell after retry
- for _ in 0..50 { // 5s
+ for _ in 0..50 {
+ // 5s
std::thread::sleep(std::time::Duration::from_millis(100));
if is_pane_at_shell(tmux_ops, target) {
found_shell = true;
@@ -6506,7 +7525,8 @@ fn switch_agent_in_tmux(
// 4. Last resort: Ctrl+D to force exit
if !found_shell {
let _ = tmux_ops.send_keys_literal(target, "C-d");
- for _ in 0..20 { // 2s
+ for _ in 0..20 {
+ // 2s
std::thread::sleep(std::time::Duration::from_millis(100));
if is_pane_at_shell(tmux_ops, target) {
break;
@@ -6524,10 +7544,12 @@ fn switch_agent_in_tmux(
// Without this, wait_for_agent_ready may see stale ">" from old pane content
// and return before the new agent has even launched.
// Includes `node` here so Gemini/Cursor (Node/Ink TUIs) are detected immediately.
- for _ in 0..10 { // 10s max
+ for _ in 0..10 {
+ // 10s max
std::thread::sleep(std::time::Duration::from_secs(1));
if let Some(cmd) = tmux_ops.pane_current_command(target) {
- let process_started = AGENT_COMMANDS.iter().any(|a| cmd.contains(a)) || cmd.contains("node");
+ let process_started =
+ AGENT_COMMANDS.iter().any(|a| cmd.contains(a)) || cmd.contains("node");
if process_started {
break;
}
@@ -6552,7 +7574,8 @@ fn wait_for_agent_ready(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> Opt
let mut stable_ticks: u32 = 0;
let mut change_count: u32 = 0;
- for _ in 0..30 { // 30s (30 * 1s)
+ for _ in 0..30 {
+ // 30s (30 * 1s)
std::thread::sleep(std::time::Duration::from_secs(1));
// Check 1: agent process detected via pane_current_command
@@ -6598,7 +7621,8 @@ fn wait_for_agent_ready(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> Opt
// TUI has finished rendering. Avoids sending the prompt into a half-drawn screen.
let mut last_content = String::new();
let mut stable_ticks: u32 = 0;
- for _ in 0..30 { // 30s hard timeout
+ for _ in 0..30 {
+ // 30s hard timeout
std::thread::sleep(std::time::Duration::from_secs(1));
if let Ok(content) = tmux_ops.capture_pane(target) {
if content != last_content {
@@ -6618,7 +7642,11 @@ fn wait_for_agent_ready(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> Opt
/// Load the workflow plugin for a task, checking agent compatibility.
/// Tries disk first (project-local β†’ global), then falls back to bundled plugins.
-fn load_task_plugin(task: &Task, project_path: Option<&Path>, default_agent: &str) -> Option<WorkflowPlugin> {
+fn load_task_plugin(
+ task: &Task,
+ project_path: Option<&Path>,
+ default_agent: &str,
+) -> Option<WorkflowPlugin> {
let plugin = match &task.plugin {
Some(name) => WorkflowPlugin::load(name, project_path)
.ok()
@@ -6634,7 +7662,10 @@ fn load_task_plugin(task: &Task, project_path: Option<&Path>, default_agent: &st
}
/// Load workflow plugin if configured
-fn load_plugin_if_configured(config: &MergedConfig, project_path: Option<&Path>) -> Option<WorkflowPlugin> {
+fn load_plugin_if_configured(
+ config: &MergedConfig,
+ project_path: Option<&Path>,
+) -> Option<WorkflowPlugin> {
// For bundled plugins, always write the latest version to disk so updates ship with new releases
if let (Some(name), Some(pp)) = (config.workflow_plugin.as_ref(), project_path) {
if let Some((_name, _desc, content)) = skills::BUNDLED_PLUGINS
@@ -6646,7 +7677,9 @@ fn load_plugin_if_configured(config: &MergedConfig, project_path: Option<&Path>)
let _ = std::fs::write(plugin_dir.join("plugin.toml"), content);
}
}
- config.workflow_plugin.as_ref()
+ config
+ .workflow_plugin
+ .as_ref()
.and_then(|name| WorkflowPlugin::load(name, project_path).ok())
.or_else(|| skills::load_bundled_plugin("agtx"))
}
@@ -6654,7 +7687,12 @@ fn load_plugin_if_configured(config: &MergedConfig, project_path: Option<&Path>)
/// Write skill files to a worktree's .agtx/skills/ directory and agent-native discovery paths.
/// `agent_names` determines which native paths to use (e.g. `.claude/commands/agtx/` for Claude).
/// When multiple agents are configured for different phases, skills are deployed for all of them.
-fn write_skills_to_worktree(worktree_path: &str, project_path: &Path, plugin: &Option<WorkflowPlugin>, agent_names: &[&str]) {
+fn write_skills_to_worktree(
+ worktree_path: &str,
+ project_path: &Path,
+ plugin: &Option<WorkflowPlugin>,
+ agent_names: &[&str],
+) {
let agtx_dir = Path::new(worktree_path).join(".agtx");
let _ = std::fs::create_dir_all(&agtx_dir);
@@ -6702,7 +7740,8 @@ fn write_skills_to_worktree(worktree_path: &str, project_path: &Path, plugin: &O
let _ = std::fs::create_dir_all(&native_dir);
for (skill_dir_name, default_content) in skills::BUILTIN_SKILLS {
- let content = resolve_skill_content(plugin, skill_dir_name, project_path, default_content);
+ let content =
+ resolve_skill_content(plugin, skill_dir_name, project_path, default_content);
match *agent_name {
"gemini" => {
@@ -6804,14 +7843,19 @@ fn transform_skill_frontmatter(content: &str) -> String {
/// OpenCode uses flat command files and hyphen-separated names (no colon namespace)
fn transform_skill_for_opencode(content: &str) -> String {
// OpenCode commands use description frontmatter + prompt body
- let description = skills::extract_description(content)
- .unwrap_or_else(|| "agtx skill".to_string());
+ let description =
+ skills::extract_description(content).unwrap_or_else(|| "agtx skill".to_string());
let body = skills::strip_frontmatter(content);
format!("---\ndescription: \"{}\"\n---\n{}", description, body)
}
/// Resolve skill content: check plugin override, then fall back to default
-fn resolve_skill_content(plugin: &Option<WorkflowPlugin>, skill_name: &str, project_path: &Path, default: &str) -> String {
+fn resolve_skill_content(
+ plugin: &Option<WorkflowPlugin>,
+ skill_name: &str,
+ project_path: &Path,
+ default: &str,
+) -> String {
if let Some(ref p) = plugin {
if let Some(plugin_dir) = WorkflowPlugin::plugin_dir(&p.name, Some(project_path)) {
let src = plugin_dir.join(skill_name).join("SKILL.md");
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index 97f3b82..2309c96 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -230,7 +230,9 @@ fn test_create_pr_with_content_success() {
mock_git
.expect_commit()
.withf(|path: &Path, msg: &str| {
- path == Path::new("/tmp/worktree") && msg.contains("Test PR") && msg.contains("Co-Authored-By")
+ path == Path::new("/tmp/worktree")
+ && msg.contains("Test PR")
+ && msg.contains("Co-Authored-By")
})
.times(1)
.returning(|_, _| Ok(()));
@@ -253,7 +255,10 @@ fn test_create_pr_with_content_success() {
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"
+ 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())));
@@ -302,20 +307,14 @@ fn test_create_pr_with_content_no_changes() {
updated_at: chrono::Utc::now(),
};
- mock_git
- .expect_add_all()
- .returning(|_| Ok(()));
+ mock_git.expect_add_all().returning(|_| Ok(()));
// No changes to commit
- mock_git
- .expect_has_changes()
- .returning(|_| false);
+ mock_git.expect_has_changes().returning(|_| false);
// commit should NOT be called (no expectation set)
- mock_git
- .expect_push()
- .returning(|_, _, _| Ok(()));
+ mock_git.expect_push().returning(|_, _, _| Ok(()));
mock_git_provider
.expect_create_pr()
@@ -385,7 +384,10 @@ fn test_create_pr_with_content_push_failure() {
);
assert!(result.is_err());
- assert!(result.unwrap_err().to_string().contains("Permission denied"));
+ assert!(result
+ .unwrap_err()
+ .to_string()
+ .contains("Permission denied"));
}
// =============================================================================
@@ -530,15 +532,15 @@ fn test_push_changes_to_existing_pr_no_url() {
fn test_fuzzy_find_files_basic() {
let mut mock_git = MockGitOperations::new();
- mock_git
- .expect_list_files()
- .returning(|_| vec![
+ 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);
@@ -552,15 +554,15 @@ fn test_fuzzy_find_files_basic() {
fn test_fuzzy_find_files_empty_pattern() {
let mut mock_git = MockGitOperations::new();
- mock_git
- .expect_list_files()
- .returning(|_| vec![
+ 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);
@@ -604,15 +606,15 @@ fn test_fuzzy_find_files_empty_list() {
fn test_fuzzy_find_files_max_results() {
let mut mock_git = MockGitOperations::new();
- mock_git
- .expect_list_files()
- .returning(|_| vec![
+ 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);
@@ -718,7 +720,10 @@ fn test_send_key_to_tmux_special_keys() {
// Test Escape
mock_tmux
.expect_send_keys_literal()
- .with(mockall::predicate::eq("win"), mockall::predicate::eq("Escape"))
+ .with(
+ mockall::predicate::eq("win"),
+ mockall::predicate::eq("Escape"),
+ )
.returning(|_, _| Ok(()));
send_key_to_tmux("win", KeyCode::Esc, &mock_tmux);
@@ -727,7 +732,10 @@ fn test_send_key_to_tmux_special_keys() {
let mut mock_tmux2 = MockTmuxOperations::new();
mock_tmux2
.expect_send_keys_literal()
- .with(mockall::predicate::eq("win"), mockall::predicate::eq("BSpace"))
+ .with(
+ mockall::predicate::eq("win"),
+ mockall::predicate::eq("BSpace"),
+ )
.returning(|_, _| Ok(()));
send_key_to_tmux("win", KeyCode::Backspace, &mock_tmux2);
@@ -759,7 +767,10 @@ fn test_capture_tmux_pane_with_history() {
mock_tmux
.expect_capture_pane_with_history()
- .with(mockall::predicate::eq("test-window"), mockall::predicate::eq(500))
+ .with(
+ mockall::predicate::eq("test-window"),
+ mockall::predicate::eq(500),
+ )
.returning(|_, _| b"Line 1\nLine 2\nLine 3\n".to_vec());
mock_tmux
@@ -902,12 +913,7 @@ fn test_cleanup_task_for_done_with_resources() {
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,
- );
+ 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());
@@ -927,12 +933,7 @@ fn test_cleanup_task_for_done_no_resources() {
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,
- );
+ cleanup_task_for_done(&mut task, Path::new("/project"), &mock_tmux, &mock_git);
assert_eq!(task.status, TaskStatus::Done);
}
@@ -975,12 +976,7 @@ fn test_delete_task_resources_full_cleanup() {
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,
- );
+ delete_task_resources(&task, Path::new("/project"), &mock_tmux, &mock_git);
}
/// Test delete_task_resources handles task without resources
@@ -996,12 +992,7 @@ fn test_delete_task_resources_no_resources() {
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,
- );
+ delete_task_resources(&task, Path::new("/project"), &mock_tmux, &mock_git);
}
// =============================================================================
@@ -1045,7 +1036,9 @@ fn test_collect_task_diff_no_changes() {
mock_git.expect_diff().returning(|_| String::new());
mock_git.expect_diff_cached().returning(|_| String::new());
- mock_git.expect_list_untracked_files().returning(|_| String::new());
+ mock_git
+ .expect_list_untracked_files()
+ .returning(|_| String::new());
let result = collect_task_diff("/tmp/worktree", &mock_git, &[]);
@@ -1064,7 +1057,9 @@ fn test_collect_task_diff_only_unstaged() {
.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());
+ mock_git
+ .expect_list_untracked_files()
+ .returning(|_| String::new());
let result = collect_task_diff("/tmp/worktree", &mock_git, &[]);
@@ -1106,7 +1101,10 @@ fn test_build_highlighted_text_single_path() {
assert_eq!(lines[0].spans[1].content, "src/main.rs");
assert_eq!(lines[0].spans[2].content, " for me");
// The highlighted span should be bold
- assert!(lines[0].spans[1].style.add_modifier.contains(Modifier::BOLD));
+ assert!(lines[0].spans[1]
+ .style
+ .add_modifier
+ .contains(Modifier::BOLD));
}
/// Test build_highlighted_text with multiple file paths on one line
@@ -1129,7 +1127,12 @@ fn test_build_highlighted_text_multiple_paths() {
fn test_build_highlighted_text_multiline() {
let mut paths = HashSet::new();
paths.insert("app.rs".to_string());
- let text = build_highlighted_text("line1\nfix app.rs\nline3", &paths, Color::White, Color::Cyan);
+ let text = build_highlighted_text(
+ "line1\nfix app.rs\nline3",
+ &paths,
+ Color::White,
+ Color::Cyan,
+ );
let lines: Vec<&Line> = text.lines.iter().collect();
assert_eq!(lines.len(), 3);
// First line: no highlight
@@ -1167,7 +1170,10 @@ fn test_build_highlighted_text_path_is_entire_line() {
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].spans.len(), 1);
assert_eq!(lines[0].spans[0].content, "Cargo.toml");
- assert!(lines[0].spans[0].style.add_modifier.contains(Modifier::BOLD));
+ assert!(lines[0].spans[0]
+ .style
+ .add_modifier
+ .contains(Modifier::BOLD));
}
// =============================================================================
@@ -1362,7 +1368,7 @@ fn test_setup_task_worktree_success() {
// Expect worktree creation
mock_git
.expect_create_worktree()
- .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+ .returning(|_, slug, _| Ok(format!("/project/.agtx/worktrees/{}", slug)));
// Expect worktree initialization
mock_git
@@ -1375,9 +1381,7 @@ fn test_setup_task_worktree_success() {
.returning(|prompt| format!("claude --dangerously-skip-permissions '{}'", prompt));
// Expect tmux session check and window creation
- mock_tmux
- .expect_has_session()
- .returning(|_| true);
+ mock_tmux.expect_has_session().returning(|_| true);
mock_tmux
.expect_create_window()
@@ -1391,6 +1395,7 @@ fn test_setup_task_worktree_success() {
Path::new("/project"),
"my-project",
"implement this",
+ "main",
None,
None,
&None,
@@ -1423,7 +1428,7 @@ fn test_setup_task_worktree_sets_task_fields() {
mock_git
.expect_create_worktree()
- .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+ .returning(|_, slug, _| Ok(format!("/project/.agtx/worktrees/{}", slug)));
mock_git
.expect_initialize_worktree()
.returning(|_, _, _, _, _| vec![]);
@@ -1431,7 +1436,9 @@ fn test_setup_task_worktree_sets_task_fields() {
.expect_build_interactive_command()
.returning(|prompt| format!("claude '{}'", prompt));
mock_tmux.expect_has_session().returning(|_| true);
- mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+ mock_tmux
+ .expect_create_window()
+ .returning(|_, _, _, _| Ok(()));
let mut task = Task::new("Fix bug", "claude", "project-1");
@@ -1440,6 +1447,7 @@ fn test_setup_task_worktree_sets_task_fields() {
Path::new("/project"),
"my-project",
"fix the bug",
+ "main",
Some("CLAUDE.md".to_string()),
Some("./init.sh".to_string()),
&None,
@@ -1449,12 +1457,17 @@ fn test_setup_task_worktree_sets_task_fields() {
&mock_git,
&mock_agent,
&[],
- ).unwrap();
+ )
+ .unwrap();
// session_name should be the returned target
assert_eq!(task.session_name.as_ref().unwrap(), &target);
// worktree_path should contain the slug
- assert!(task.worktree_path.as_ref().unwrap().contains(".agtx/worktrees/"));
+ assert!(task
+ .worktree_path
+ .as_ref()
+ .unwrap()
+ .contains(".agtx/worktrees/"));
// branch_name should be task/{slug}
let slug = &task.branch_name.as_ref().unwrap()["task/".len()..];
assert!(task.worktree_path.as_ref().unwrap().ends_with(slug));
@@ -1473,7 +1486,7 @@ fn test_setup_task_worktree_worktree_creation_fails() {
// Worktree creation fails
mock_git
.expect_create_worktree()
- .returning(|_, _| Err(anyhow::anyhow!("worktree already exists")));
+ .returning(|_, _, _| Err(anyhow::anyhow!("worktree already exists")));
// Should still initialize and create window with fallback path
mock_git
@@ -1483,7 +1496,9 @@ fn test_setup_task_worktree_worktree_creation_fails() {
.expect_build_interactive_command()
.returning(|prompt| format!("claude '{}'", prompt));
mock_tmux.expect_has_session().returning(|_| true);
- mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+ mock_tmux
+ .expect_create_window()
+ .returning(|_, _, _, _| Ok(()));
let mut task = Task::new("Test task", "claude", "project-1");
@@ -1492,6 +1507,7 @@ fn test_setup_task_worktree_worktree_creation_fails() {
Path::new("/project"),
"my-project",
"do something",
+ "main",
None,
None,
&None,
@@ -1506,7 +1522,11 @@ fn test_setup_task_worktree_worktree_creation_fails() {
// Should succeed despite worktree creation failure (uses fallback path)
assert!(result.is_ok());
assert!(task.worktree_path.is_some());
- assert!(task.worktree_path.as_ref().unwrap().contains(".agtx/worktrees/"));
+ assert!(task
+ .worktree_path
+ .as_ref()
+ .unwrap()
+ .contains(".agtx/worktrees/"));
}
/// Test setup_task_worktree fails when tmux window creation fails
@@ -1521,7 +1541,7 @@ fn test_setup_task_worktree_tmux_window_fails() {
mock_git
.expect_create_worktree()
- .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+ .returning(|_, slug, _| Ok(format!("/project/.agtx/worktrees/{}", slug)));
mock_git
.expect_initialize_worktree()
.returning(|_, _, _, _, _| vec![]);
@@ -1542,6 +1562,7 @@ fn test_setup_task_worktree_tmux_window_fails() {
Path::new("/project"),
"my-project",
"do something",
+ "main",
None,
None,
&None,
@@ -1570,7 +1591,7 @@ fn test_setup_task_worktree_creates_session_when_missing() {
mock_git
.expect_create_worktree()
- .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+ .returning(|_, slug, _| Ok(format!("/project/.agtx/worktrees/{}", slug)));
mock_git
.expect_initialize_worktree()
.returning(|_, _, _, _, _| vec![]);
@@ -1579,12 +1600,8 @@ fn test_setup_task_worktree_creates_session_when_missing() {
.returning(|prompt| format!("claude '{}'", prompt));
// Session doesn't exist yet
- mock_tmux
- .expect_has_session()
- .returning(|_| false);
- mock_tmux
- .expect_create_session()
- .returning(|_, _| Ok(()));
+ mock_tmux.expect_has_session().returning(|_| false);
+ mock_tmux.expect_create_session().returning(|_, _| Ok(()));
mock_tmux
.expect_create_window()
.returning(|_, _, _, _| Ok(()));
@@ -1596,6 +1613,7 @@ fn test_setup_task_worktree_creates_session_when_missing() {
Path::new("/project"),
"my-project",
"do work",
+ "main",
None,
None,
&None,
@@ -1622,7 +1640,8 @@ fn test_setup_task_worktree_passes_init_config() {
mock_git
.expect_create_worktree()
- .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+ .withf(|_, _, base_branch| base_branch == "development")
+ .returning(|_, slug, _| Ok(format!("/project/.agtx/worktrees/{}", slug)));
// Verify copy_files and init_script are passed through
mock_git
@@ -1637,7 +1656,9 @@ fn test_setup_task_worktree_passes_init_config() {
.expect_build_interactive_command()
.returning(|prompt| format!("claude '{}'", prompt));
mock_tmux.expect_has_session().returning(|_| true);
- mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+ mock_tmux
+ .expect_create_window()
+ .returning(|_, _, _, _| Ok(()));
let mut task = Task::new("Task with config", "claude", "project-1");
@@ -1646,6 +1667,7 @@ fn test_setup_task_worktree_passes_init_config() {
Path::new("/project"),
"my-project",
"implement feature",
+ "development",
Some("CLAUDE.md,.env".to_string()),
Some("./setup.sh".to_string()),
&None,
@@ -1665,57 +1687,138 @@ fn test_setup_task_worktree_passes_init_config() {
#[test]
fn test_skill_name_to_command() {
assert_eq!(skills::skill_name_to_command("agtx-plan"), "agtx:plan");
- assert_eq!(skills::skill_name_to_command("agtx-execute"), "agtx:execute");
+ assert_eq!(
+ skills::skill_name_to_command("agtx-execute"),
+ "agtx:execute"
+ );
assert_eq!(skills::skill_name_to_command("agtx-review"), "agtx:review");
- assert_eq!(skills::skill_name_to_command("agtx-research"), "agtx:research");
+ assert_eq!(
+ skills::skill_name_to_command("agtx-research"),
+ "agtx:research"
+ );
assert_eq!(skills::skill_name_to_command("simple"), "simple");
}
#[test]
fn test_skill_dir_to_filename() {
// Claude/default: .md files with prefix stripped
- assert_eq!(skills::skill_dir_to_filename("agtx-plan", "claude"), "plan.md");
- assert_eq!(skills::skill_dir_to_filename("agtx-execute", "claude"), "execute.md");
- assert_eq!(skills::skill_dir_to_filename("agtx-review", "claude"), "review.md");
- assert_eq!(skills::skill_dir_to_filename("custom", "claude"), "custom.md");
+ assert_eq!(
+ skills::skill_dir_to_filename("agtx-plan", "claude"),
+ "plan.md"
+ );
+ assert_eq!(
+ skills::skill_dir_to_filename("agtx-execute", "claude"),
+ "execute.md"
+ );
+ assert_eq!(
+ skills::skill_dir_to_filename("agtx-review", "claude"),
+ "review.md"
+ );
+ assert_eq!(
+ skills::skill_dir_to_filename("custom", "claude"),
+ "custom.md"
+ );
// Gemini: .toml files with prefix stripped
- assert_eq!(skills::skill_dir_to_filename("agtx-plan", "gemini"), "plan.toml");
- assert_eq!(skills::skill_dir_to_filename("agtx-execute", "gemini"), "execute.toml");
+ assert_eq!(
+ skills::skill_dir_to_filename("agtx-plan", "gemini"),
+ "plan.toml"
+ );
+ assert_eq!(
+ skills::skill_dir_to_filename("agtx-execute", "gemini"),
+ "execute.toml"
+ );
// OpenCode: .md files with full name (flat directory, no namespace)
- assert_eq!(skills::skill_dir_to_filename("agtx-plan", "opencode"), "agtx-plan.md");
- assert_eq!(skills::skill_dir_to_filename("agtx-execute", "opencode"), "agtx-execute.md");
+ assert_eq!(
+ skills::skill_dir_to_filename("agtx-plan", "opencode"),
+ "agtx-plan.md"
+ );
+ assert_eq!(
+ skills::skill_dir_to_filename("agtx-execute", "opencode"),
+ "agtx-execute.md"
+ );
// Copilot: .md files with prefix stripped (same as Claude default)
- assert_eq!(skills::skill_dir_to_filename("agtx-plan", "copilot"), "plan.md");
- assert_eq!(skills::skill_dir_to_filename("agtx-execute", "copilot"), "execute.md");
+ assert_eq!(
+ skills::skill_dir_to_filename("agtx-plan", "copilot"),
+ "plan.md"
+ );
+ assert_eq!(
+ skills::skill_dir_to_filename("agtx-execute", "copilot"),
+ "execute.md"
+ );
}
#[test]
fn test_agent_native_skill_dir() {
- assert_eq!(skills::agent_native_skill_dir("claude"), Some((".claude/commands", "agtx")));
- assert_eq!(skills::agent_native_skill_dir("gemini"), Some((".gemini/commands", "agtx")));
- assert_eq!(skills::agent_native_skill_dir("opencode"), Some((".opencode/commands", "")));
- assert_eq!(skills::agent_native_skill_dir("codex"), Some((".codex/skills", "")));
- assert_eq!(skills::agent_native_skill_dir("copilot"), Some((".github/agents", "agtx")));
+ assert_eq!(
+ skills::agent_native_skill_dir("claude"),
+ Some((".claude/commands", "agtx"))
+ );
+ assert_eq!(
+ skills::agent_native_skill_dir("gemini"),
+ Some((".gemini/commands", "agtx"))
+ );
+ assert_eq!(
+ skills::agent_native_skill_dir("opencode"),
+ Some((".opencode/commands", ""))
+ );
+ assert_eq!(
+ skills::agent_native_skill_dir("codex"),
+ Some((".codex/skills", ""))
+ );
+ assert_eq!(
+ skills::agent_native_skill_dir("copilot"),
+ Some((".github/agents", "agtx"))
+ );
assert_eq!(skills::agent_native_skill_dir("unknown"), None);
}
#[test]
fn test_transform_plugin_command() {
// Claude/Gemini: canonical form unchanged
- assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "claude"), Some("/gsd:plan-phase 1".to_string()));
- assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "gemini"), Some("/gsd:plan-phase 1".to_string()));
+ assert_eq!(
+ skills::transform_plugin_command("/gsd:plan-phase 1", "claude"),
+ Some("/gsd:plan-phase 1".to_string())
+ );
+ assert_eq!(
+ skills::transform_plugin_command("/gsd:plan-phase 1", "gemini"),
+ Some("/gsd:plan-phase 1".to_string())
+ );
// OpenCode: colon β†’ hyphen
- assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "opencode"), Some("/gsd-plan-phase 1".to_string()));
- assert_eq!(skills::transform_plugin_command("/gsd:discuss-phase 1", "opencode"), Some("/gsd-discuss-phase 1".to_string()));
+ assert_eq!(
+ skills::transform_plugin_command("/gsd:plan-phase 1", "opencode"),
+ Some("/gsd-plan-phase 1".to_string())
+ );
+ assert_eq!(
+ skills::transform_plugin_command("/gsd:discuss-phase 1", "opencode"),
+ Some("/gsd-discuss-phase 1".to_string())
+ );
// Codex: slash β†’ dollar, colon β†’ hyphen
- assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "codex"), Some("$gsd-plan-phase 1".to_string()));
- assert_eq!(skills::transform_plugin_command("/gsd:execute-phase 1", "codex"), Some("$gsd-execute-phase 1".to_string()));
+ assert_eq!(
+ skills::transform_plugin_command("/gsd:plan-phase 1", "codex"),
+ Some("$gsd-plan-phase 1".to_string())
+ );
+ assert_eq!(
+ skills::transform_plugin_command("/gsd:execute-phase 1", "codex"),
+ Some("$gsd-execute-phase 1".to_string())
+ );
// Spec-kit style (dot separator, no colon): transform only affects colon
- assert_eq!(skills::transform_plugin_command("/speckit.plan", "opencode"), Some("/speckit.plan".to_string()));
- assert_eq!(skills::transform_plugin_command("/speckit.plan", "codex"), Some("$speckit.plan".to_string()));
+ assert_eq!(
+ skills::transform_plugin_command("/speckit.plan", "opencode"),
+ Some("/speckit.plan".to_string())
+ );
+ assert_eq!(
+ skills::transform_plugin_command("/speckit.plan", "codex"),
+ Some("$speckit.plan".to_string())
+ );
// Unsupported agents
- assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "copilot"), None);
- assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "unknown"), None);
+ assert_eq!(
+ skills::transform_plugin_command("/gsd:plan-phase 1", "copilot"),
+ None
+ );
+ assert_eq!(
+ skills::transform_plugin_command("/gsd:plan-phase 1", "unknown"),
+ None
+ );
}
#[test]
@@ -1729,7 +1832,10 @@ fn test_strip_frontmatter() {
#[test]
fn test_skill_to_gemini_toml() {
- let toml = skills::skill_to_gemini_toml("Plan a task", "---\nname: agtx-plan\n---\n# Planning\nDo stuff");
+ let toml = skills::skill_to_gemini_toml(
+ "Plan a task",
+ "---\nname: agtx-plan\n---\n# Planning\nDo stuff",
+ );
assert!(toml.contains("description = \"Plan a task\""));
assert!(toml.contains("prompt = \"\"\""));
assert!(toml.contains("# Planning"));
@@ -1741,7 +1847,10 @@ fn test_skill_to_gemini_toml() {
#[test]
fn test_extract_description() {
let content = "---\nname: agtx-plan\ndescription: Plan a task implementation.\n---\n# Content";
- assert_eq!(skills::extract_description(content), Some("Plan a task implementation.".to_string()));
+ assert_eq!(
+ skills::extract_description(content),
+ Some("Plan a task implementation.".to_string())
+ );
let no_desc = "---\nname: agtx-plan\n---\n# Content";
assert_eq!(skills::extract_description(no_desc), None);
@@ -1777,7 +1886,13 @@ fn test_resolve_prompt_agtx_no_prompts() {
assert!(prompt.is_empty());
let prompt = resolve_prompt(&plugin, "running", "my task", "task-123", 1);
assert!(prompt.is_empty());
- let prompt = resolve_prompt(&plugin, "running_with_research_or_planning", "my task", "task-123", 1);
+ let prompt = resolve_prompt(
+ &plugin,
+ "running_with_research_or_planning",
+ "my task",
+ "task-123",
+ 1,
+ );
assert!(prompt.is_empty());
}
@@ -1807,18 +1922,33 @@ fn test_resolve_prompt_no_plugin_returns_empty() {
#[test]
fn test_agtx_plugin_artifacts() {
let plugin = skills::load_bundled_plugin("agtx").expect("agtx plugin should load");
- assert_eq!(plugin.artifacts.research.as_deref(), Some(".agtx/research.md"));
+ assert_eq!(
+ plugin.artifacts.research.as_deref(),
+ Some(".agtx/research.md")
+ );
assert_eq!(plugin.artifacts.planning.as_deref(), Some(".agtx/plan.md"));
- assert_eq!(plugin.artifacts.running.as_deref(), Some(".agtx/execute.md"));
+ assert_eq!(
+ plugin.artifacts.running.as_deref(),
+ Some(".agtx/execute.md")
+ );
assert_eq!(plugin.artifacts.review.as_deref(), Some(".agtx/review.md"));
}
#[test]
fn test_agtx_plugin_has_commands() {
let plugin = skills::load_bundled_plugin("agtx").expect("agtx plugin should load");
- assert_eq!(plugin.commands.research.as_deref(), Some("/agtx:research {task}"));
- assert_eq!(plugin.commands.planning.as_deref(), Some("/agtx:plan {task}"));
- assert_eq!(plugin.commands.running.as_deref(), Some("/agtx:execute {task}"));
+ assert_eq!(
+ plugin.commands.research.as_deref(),
+ Some("/agtx:research {task}")
+ );
+ assert_eq!(
+ plugin.commands.planning.as_deref(),
+ Some("/agtx:plan {task}")
+ );
+ assert_eq!(
+ plugin.commands.running.as_deref(),
+ Some("/agtx:execute {task}")
+ );
assert_eq!(plugin.commands.review.as_deref(), Some("/agtx:review"));
}
@@ -1858,16 +1988,33 @@ fn test_enumerate_available_skills_opencode() {
#[test]
fn test_resolve_skill_command_no_plugin() {
// No plugin: no commands, returns None for all agents/phases
- assert_eq!(resolve_skill_command(&None, "planning", "claude", "", 1), None);
- assert_eq!(resolve_skill_command(&None, "running", "codex", "", 1), None);
- assert_eq!(resolve_skill_command(&None, "review", "gemini", "", 1), None);
- assert_eq!(resolve_skill_command(&None, "planning", "opencode", "", 1), None);
- assert_eq!(resolve_skill_command(&None, "planning", "copilot", "", 1), None);
+ assert_eq!(
+ resolve_skill_command(&None, "planning", "claude", "", 1),
+ None
+ );
+ assert_eq!(
+ resolve_skill_command(&None, "running", "codex", "", 1),
+ None
+ );
+ assert_eq!(
+ resolve_skill_command(&None, "review", "gemini", "", 1),
+ None
+ );
+ assert_eq!(
+ resolve_skill_command(&None, "planning", "opencode", "", 1),
+ None
+ );
+ assert_eq!(
+ resolve_skill_command(&None, "planning", "copilot", "", 1),
+ None
+ );
}
#[test]
fn test_resolve_skill_command_with_plugin() {
- use crate::config::{WorkflowPlugin, PluginArtifacts, PluginCommands, PluginPrompts, PluginPromptTriggers};
+ use crate::config::{
+ PluginArtifacts, PluginCommands, PluginPromptTriggers, PluginPrompts, WorkflowPlugin,
+ };
let plugin = Some(WorkflowPlugin {
name: "gsd".to_string(),
description: None,
@@ -1890,18 +2037,45 @@ fn test_resolve_skill_command_with_plugin() {
auto_dismiss: vec![],
});
// Claude/Gemini: canonical form unchanged
- assert_eq!(resolve_skill_command(&plugin, "planning", "claude", "", 1), Some("/gsd:plan-phase 1".to_string()));
- assert_eq!(resolve_skill_command(&plugin, "running", "claude", "", 1), Some("/gsd:execute-phase 1".to_string()));
- assert_eq!(resolve_skill_command(&plugin, "review", "gemini", "", 1), Some("/gsd:verify-work 1".to_string()));
- assert_eq!(resolve_skill_command(&plugin, "research", "claude", "", 1), Some("/gsd:discuss-phase 1".to_string()));
+ assert_eq!(
+ resolve_skill_command(&plugin, "planning", "claude", "", 1),
+ Some("/gsd:plan-phase 1".to_string())
+ );
+ assert_eq!(
+ resolve_skill_command(&plugin, "running", "claude", "", 1),
+ Some("/gsd:execute-phase 1".to_string())
+ );
+ assert_eq!(
+ resolve_skill_command(&plugin, "review", "gemini", "", 1),
+ Some("/gsd:verify-work 1".to_string())
+ );
+ assert_eq!(
+ resolve_skill_command(&plugin, "research", "claude", "", 1),
+ Some("/gsd:discuss-phase 1".to_string())
+ );
// OpenCode: colon β†’ hyphen
- assert_eq!(resolve_skill_command(&plugin, "planning", "opencode", "", 1), Some("/gsd-plan-phase 1".to_string()));
- assert_eq!(resolve_skill_command(&plugin, "research", "opencode", "", 1), Some("/gsd-discuss-phase 1".to_string()));
+ assert_eq!(
+ resolve_skill_command(&plugin, "planning", "opencode", "", 1),
+ Some("/gsd-plan-phase 1".to_string())
+ );
+ assert_eq!(
+ resolve_skill_command(&plugin, "research", "opencode", "", 1),
+ Some("/gsd-discuss-phase 1".to_string())
+ );
// Codex: slash β†’ dollar, colon β†’ hyphen
- assert_eq!(resolve_skill_command(&plugin, "planning", "codex", "", 1), Some("$gsd-plan-phase 1".to_string()));
- assert_eq!(resolve_skill_command(&plugin, "running", "codex", "", 1), Some("$gsd-execute-phase 1".to_string()));
+ assert_eq!(
+ resolve_skill_command(&plugin, "planning", "codex", "", 1),
+ Some("$gsd-plan-phase 1".to_string())
+ );
+ assert_eq!(
+ resolve_skill_command(&plugin, "running", "codex", "", 1),
+ Some("$gsd-execute-phase 1".to_string())
+ );
// Unsupported agents: None (will use file-path fallback in prompt)
- assert_eq!(resolve_skill_command(&plugin, "planning", "copilot", "", 1), None);
+ assert_eq!(
+ resolve_skill_command(&plugin, "planning", "copilot", "", 1),
+ None
+ );
}
#[test]
@@ -1933,7 +2107,12 @@ fn test_plugin_supports_agent() {
name: "gsd".to_string(),
description: None,
init_script: None,
- supported_agents: vec!["claude".into(), "codex".into(), "gemini".into(), "opencode".into()],
+ supported_agents: vec![
+ "claude".into(),
+ "codex".into(),
+ "gemini".into(),
+ "opencode".into(),
+ ],
artifacts: Default::default(),
commands: Default::default(),
prompts: Default::default(),
@@ -1986,7 +2165,7 @@ fn test_glob_path_exists() {
#[test]
fn test_phase_artifact_exists_with_glob() {
- use crate::config::{WorkflowPlugin, PluginArtifacts, PluginCommands, PluginPrompts};
+ use crate::config::{PluginArtifacts, PluginCommands, PluginPrompts, WorkflowPlugin};
let tmp = std::env::temp_dir().join("agtx_test_artifact_glob");
let _ = std::fs::remove_dir_all(&tmp);
@@ -2019,14 +2198,34 @@ fn test_phase_artifact_exists_with_glob() {
let worktree = tmp.to_string_lossy().to_string();
// Planning artifact exists (glob matches)
- assert!(phase_artifact_exists(&worktree, TaskStatus::Planning, &plugin, 1));
+ assert!(phase_artifact_exists(
+ &worktree,
+ TaskStatus::Planning,
+ &plugin,
+ 1
+ ));
// Research artifact doesn't exist yet (no spec.md)
- assert!(!phase_artifact_exists(&worktree, TaskStatus::Backlog, &plugin, 1));
+ assert!(!phase_artifact_exists(
+ &worktree,
+ TaskStatus::Backlog,
+ &plugin,
+ 1
+ ));
// Running/Review fall back to agtx defaults (don't exist)
- assert!(!phase_artifact_exists(&worktree, TaskStatus::Running, &plugin, 1));
- assert!(!phase_artifact_exists(&worktree, TaskStatus::Review, &plugin, 1));
+ assert!(!phase_artifact_exists(
+ &worktree,
+ TaskStatus::Running,
+ &plugin,
+ 1
+ ));
+ assert!(!phase_artifact_exists(
+ &worktree,
+ TaskStatus::Review,
+ &plugin,
+ 1
+ ));
let _ = std::fs::remove_dir_all(&tmp);
}
@@ -2066,7 +2265,9 @@ fn test_plugin_select_popup_construction_no_active() {
active: current.is_empty(),
}];
for (name, desc, _) in skills::BUNDLED_PLUGINS {
- if *name == "agtx" { continue; }
+ if *name == "agtx" {
+ continue;
+ }
options.push(PluginOption {
name: name.to_string(),
label: name.to_string(),
@@ -2091,7 +2292,9 @@ fn test_plugin_select_popup_construction_gsd_active() {
active: current.is_empty(),
}];
for (name, desc, _) in skills::BUNDLED_PLUGINS {
- if *name == "agtx" { continue; }
+ if *name == "agtx" {
+ continue;
+ }
options.push(PluginOption {
name: name.to_string(),
label: name.to_string(),
@@ -2131,7 +2334,11 @@ fn test_install_plugin_writes_files() {
project_config.save(&tmp).unwrap();
// Verify plugin.toml was written
- let plugin_toml = tmp.join(".agtx").join("plugins").join("gsd").join("plugin.toml");
+ let plugin_toml = tmp
+ .join(".agtx")
+ .join("plugins")
+ .join("gsd")
+ .join("plugin.toml");
assert!(plugin_toml.exists());
let content = std::fs::read_to_string(&plugin_toml).unwrap();
assert!(content.contains("name = \"gsd\""));
@@ -2269,15 +2476,24 @@ fn test_gsd_plugin_toml_has_research_command() {
.find(|(n, _, _)| *n == "gsd")
.expect("gsd plugin should be bundled");
let plugin: WorkflowPlugin = toml::from_str(content).unwrap();
- assert_eq!(plugin.commands.preresearch, Some("/gsd:new-project".to_string()));
- assert_eq!(plugin.commands.research, Some("/gsd:discuss-phase {phase}".to_string()));
- assert_eq!(plugin.commands.planning, Some("/gsd:plan-phase {phase}".to_string()));
+ assert_eq!(
+ plugin.commands.preresearch,
+ Some("/gsd:new-project".to_string())
+ );
+ assert_eq!(
+ plugin.commands.research,
+ Some("/gsd:discuss-phase {phase}".to_string())
+ );
+ assert_eq!(
+ plugin.commands.planning,
+ Some("/gsd:plan-phase {phase}".to_string())
+ );
assert!(plugin.cyclic);
}
#[test]
fn test_resolve_prompt_trigger_with_gsd() {
- use crate::config::{WorkflowPlugin, PluginPromptTriggers};
+ use crate::config::{PluginPromptTriggers, WorkflowPlugin};
let plugin = Some(WorkflowPlugin {
name: "gsd".to_string(),
description: None,
@@ -2315,7 +2531,7 @@ fn test_resolve_prompt_trigger_no_plugin() {
#[test]
fn test_resolve_prompt_trigger_empty_string_filtered() {
- use crate::config::{WorkflowPlugin, PluginPromptTriggers};
+ use crate::config::{PluginPromptTriggers, WorkflowPlugin};
let plugin = Some(WorkflowPlugin {
name: "test".to_string(),
description: None,
@@ -2350,11 +2566,13 @@ fn test_scan_agent_skills_claude() {
std::fs::write(
cmd_dir.join("plan.md"),
"---\nname: agtx-plan\ndescription: Plan a task implementation\n---\nBody here\n",
- ).unwrap();
+ )
+ .unwrap();
std::fs::write(
cmd_dir.join("execute.md"),
"---\nname: agtx-execute\ndescription: Execute the plan\n---\nBody\n",
- ).unwrap();
+ )
+ .unwrap();
let results = crate::skills::scan_agent_skills("claude", base);
assert_eq!(results.len(), 2);
@@ -2374,7 +2592,8 @@ fn test_scan_agent_skills_codex() {
std::fs::write(
skill_dir.join("SKILL.md"),
"---\nname: agtx-plan\ndescription: Plan implementation\n---\nContent\n",
- ).unwrap();
+ )
+ .unwrap();
let results = crate::skills::scan_agent_skills("codex", base);
assert_eq!(results.len(), 1);
@@ -2391,7 +2610,8 @@ fn test_scan_agent_skills_gemini() {
std::fs::write(
cmd_dir.join("plan.toml"),
"description = \"Plan a task\"\n\nprompt = \"\"\"Do the planning\"\"\"\n",
- ).unwrap();
+ )
+ .unwrap();
let results = crate::skills::scan_agent_skills("gemini", base);
assert_eq!(results.len(), 1);
@@ -2445,7 +2665,7 @@ fn test_skill_fuzzy_matching() {
#[test]
fn test_needs_agent_switch_no_config_keeps_current() {
- use crate::config::{GlobalConfig, ProjectConfig, MergedConfig};
+ use crate::config::{GlobalConfig, MergedConfig, ProjectConfig};
use crate::db::Task;
// No [agents] section β€” should keep whatever agent is running
@@ -2459,7 +2679,7 @@ fn test_needs_agent_switch_no_config_keeps_current() {
#[test]
fn test_needs_agent_switch_no_config_falls_back_to_default() {
- use crate::config::{GlobalConfig, ProjectConfig, MergedConfig};
+ use crate::config::{GlobalConfig, MergedConfig, ProjectConfig};
use crate::db::Task;
// No review agent configured, task is running codex (set by explicit running override).
@@ -2477,7 +2697,7 @@ fn test_needs_agent_switch_no_config_falls_back_to_default() {
#[test]
fn test_needs_agent_switch_explicit_override() {
- use crate::config::{GlobalConfig, ProjectConfig, MergedConfig};
+ use crate::config::{GlobalConfig, MergedConfig, ProjectConfig};
use crate::db::Task;
let mut global = GlobalConfig::default();
@@ -2492,7 +2712,7 @@ fn test_needs_agent_switch_explicit_override() {
#[test]
fn test_needs_agent_switch_explicit_same_as_current() {
- use crate::config::{GlobalConfig, ProjectConfig, MergedConfig};
+ use crate::config::{GlobalConfig, MergedConfig, ProjectConfig};
use crate::db::Task;
// Explicit override exists but matches current agent β€” no switch needed
@@ -2509,7 +2729,7 @@ fn test_needs_agent_switch_explicit_same_as_current() {
#[test]
fn test_collect_phase_agents_all_same() {
- use crate::config::{GlobalConfig, ProjectConfig, MergedConfig};
+ use crate::config::{GlobalConfig, MergedConfig, ProjectConfig};
let config = MergedConfig::merge(&GlobalConfig::default(), &ProjectConfig::default());
let agents = collect_phase_agents(&config);
@@ -2518,14 +2738,21 @@ fn test_collect_phase_agents_all_same() {
#[test]
fn test_collect_phase_agents_mixed() {
- use crate::config::{GlobalConfig, ProjectConfig, MergedConfig};
+ use crate::config::{GlobalConfig, MergedConfig, ProjectConfig};
let mut global = GlobalConfig::default();
global.agents.running = Some("codex".to_string());
global.agents.review = Some("gemini".to_string());
let config = MergedConfig::merge(&global, &ProjectConfig::default());
let agents = collect_phase_agents(&config);
- assert_eq!(agents, vec!["claude".to_string(), "codex".to_string(), "gemini".to_string()]);
+ assert_eq!(
+ agents,
+ vec![
+ "claude".to_string(),
+ "codex".to_string(),
+ "gemini".to_string()
+ ]
+ );
}
// === is_pane_at_shell tests ===
@@ -2629,22 +2856,30 @@ fn test_switch_agent_claude_sends_exit() {
let new_agent_sent_c = new_agent_sent.clone();
// Claude uses /exit
- mock.expect_send_keys()
- .returning(move |_, k| {
- if k == "/exit" { exit_sent_c.store(true, Ordering::SeqCst); }
- if k == "codex" { new_agent_sent_c.store(true, Ordering::SeqCst); }
- Ok(())
- });
+ mock.expect_send_keys().returning(move |_, k| {
+ if k == "/exit" {
+ exit_sent_c.store(true, Ordering::SeqCst);
+ }
+ if k == "codex" {
+ new_agent_sent_c.store(true, Ordering::SeqCst);
+ }
+ Ok(())
+ });
mock.expect_send_keys_literal().returning(|_, _| Ok(()));
// Return shell immediately so polling exits fast
mock.expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
- mock.expect_capture_pane()
- .returning(|_| Ok(String::new()));
+ mock.expect_capture_pane().returning(|_| Ok(String::new()));
switch_agent_in_tmux(&mock, "sess:win", "claude", "codex");
- assert!(exit_sent.load(Ordering::SeqCst), "/exit should be sent for claude");
- assert!(new_agent_sent.load(Ordering::SeqCst), "new agent command should be sent");
+ assert!(
+ exit_sent.load(Ordering::SeqCst),
+ "/exit should be sent for claude"
+ );
+ assert!(
+ new_agent_sent.load(Ordering::SeqCst),
+ "new agent command should be sent"
+ );
}
#[test]
@@ -2657,19 +2892,22 @@ fn test_switch_agent_gemini_sends_quit() {
let quit_sent = Arc::new(AtomicBool::new(false));
let quit_sent_c = quit_sent.clone();
- mock.expect_send_keys()
- .returning(move |_, k| {
- if k == "/quit" { quit_sent_c.store(true, Ordering::SeqCst); }
- Ok(())
- });
+ mock.expect_send_keys().returning(move |_, k| {
+ if k == "/quit" {
+ quit_sent_c.store(true, Ordering::SeqCst);
+ }
+ Ok(())
+ });
mock.expect_send_keys_literal().returning(|_, _| Ok(()));
mock.expect_pane_current_command()
.returning(|_| Some("zsh".to_string()));
- mock.expect_capture_pane()
- .returning(|_| Ok(String::new()));
+ mock.expect_capture_pane().returning(|_| Ok(String::new()));
switch_agent_in_tmux(&mock, "sess:win", "gemini", "claude");
- assert!(quit_sent.load(Ordering::SeqCst), "/quit should be sent for gemini");
+ assert!(
+ quit_sent.load(Ordering::SeqCst),
+ "/quit should be sent for gemini"
+ );
}
#[test]
@@ -2683,18 +2921,21 @@ fn test_switch_agent_codex_sends_ctrl_c() {
let ctrl_c_sent_c = ctrl_c_sent.clone();
mock.expect_send_keys().returning(|_, _| Ok(()));
- mock.expect_send_keys_literal()
- .returning(move |_, k| {
- if k == "C-c" { ctrl_c_sent_c.store(true, Ordering::SeqCst); }
- Ok(())
- });
+ mock.expect_send_keys_literal().returning(move |_, k| {
+ if k == "C-c" {
+ ctrl_c_sent_c.store(true, Ordering::SeqCst);
+ }
+ Ok(())
+ });
mock.expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
- mock.expect_capture_pane()
- .returning(|_| Ok(String::new()));
+ mock.expect_capture_pane().returning(|_| Ok(String::new()));
switch_agent_in_tmux(&mock, "sess:win", "codex", "claude");
- assert!(ctrl_c_sent.load(Ordering::SeqCst), "Ctrl+C should be sent for codex");
+ assert!(
+ ctrl_c_sent.load(Ordering::SeqCst),
+ "Ctrl+C should be sent for codex"
+ );
}
// =============================================================================
@@ -2703,7 +2944,7 @@ fn test_switch_agent_codex_sends_ctrl_c() {
#[test]
fn test_resolve_skill_command_phase_substitution() {
- use crate::config::{WorkflowPlugin, PluginCommands};
+ use crate::config::{PluginCommands, WorkflowPlugin};
let plugin_toml = r#"
name = "gsd"
init_script = "echo test"
@@ -2720,22 +2961,43 @@ fn test_resolve_skill_command_phase_substitution() {
let p = Some(plugin);
// Cycle 1: {phase} β†’ "1"
- assert_eq!(resolve_skill_command(&p, "planning", "claude", "", 1), Some("/gsd:plan-phase 1".to_string()));
- assert_eq!(resolve_skill_command(&p, "running", "claude", "", 1), Some("/gsd:execute-phase 1".to_string()));
- assert_eq!(resolve_skill_command(&p, "review", "claude", "", 1), Some("/gsd:verify-work 1".to_string()));
+ assert_eq!(
+ resolve_skill_command(&p, "planning", "claude", "", 1),
+ Some("/gsd:plan-phase 1".to_string())
+ );
+ assert_eq!(
+ resolve_skill_command(&p, "running", "claude", "", 1),
+ Some("/gsd:execute-phase 1".to_string())
+ );
+ assert_eq!(
+ resolve_skill_command(&p, "review", "claude", "", 1),
+ Some("/gsd:verify-work 1".to_string())
+ );
// Cycle 2: {phase} β†’ "2"
- assert_eq!(resolve_skill_command(&p, "planning", "claude", "", 2), Some("/gsd:plan-phase 2".to_string()));
- assert_eq!(resolve_skill_command(&p, "running", "claude", "", 2), Some("/gsd:execute-phase 2".to_string()));
- assert_eq!(resolve_skill_command(&p, "review", "claude", "", 2), Some("/gsd:verify-work 2".to_string()));
+ assert_eq!(
+ resolve_skill_command(&p, "planning", "claude", "", 2),
+ Some("/gsd:plan-phase 2".to_string())
+ );
+ assert_eq!(
+ resolve_skill_command(&p, "running", "claude", "", 2),
+ Some("/gsd:execute-phase 2".to_string())
+ );
+ assert_eq!(
+ resolve_skill_command(&p, "review", "claude", "", 2),
+ Some("/gsd:verify-work 2".to_string())
+ );
// preresearch also gets {phase} substitution (falls back to research command)
- assert_eq!(resolve_skill_command(&p, "preresearch", "claude", "", 1), Some("/gsd:new-project".to_string()));
+ assert_eq!(
+ resolve_skill_command(&p, "preresearch", "claude", "", 1),
+ Some("/gsd:new-project".to_string())
+ );
}
#[test]
fn test_phase_artifact_exists_with_phase_substitution() {
- use crate::config::{WorkflowPlugin, PluginArtifacts};
+ use crate::config::{PluginArtifacts, WorkflowPlugin};
let tmp = std::env::temp_dir().join("agtx_test_phase_artifact");
let _ = std::fs::remove_dir_all(&tmp);
@@ -2836,7 +3098,10 @@ fn test_determine_phase_variant_running_with_planning() {
#[test]
fn test_determine_phase_variant_review_passthrough() {
- assert_eq!(determine_phase_variant("review", None, "t", &None, 1), "review");
+ assert_eq!(
+ determine_phase_variant("review", None, "t", &None, 1),
+ "review"
+ );
}
#[test]
@@ -2860,7 +3125,10 @@ fn test_resolve_skill_command_preresearch_fallback() {
use crate::config::WorkflowPlugin;
let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();
let p = Some(plugin);
- assert_eq!(resolve_skill_command(&p, "preresearch", "claude", "", 1), Some("/test:discuss".to_string()));
+ assert_eq!(
+ resolve_skill_command(&p, "preresearch", "claude", "", 1),
+ Some("/test:discuss".to_string())
+ );
}
#[test]
@@ -2923,22 +3191,28 @@ fn test_send_skill_and_prompt_gemini_combined() {
let literal_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let literal_c = literal_calls.clone();
- mock.expect_send_keys_literal()
- .returning(move |_, text| {
- literal_c.lock().unwrap().push(text.to_string());
- Ok(())
- });
+ mock.expect_send_keys_literal().returning(move |_, text| {
+ literal_c.lock().unwrap().push(text.to_string());
+ Ok(())
+ });
mock.expect_capture_pane()
.returning(|_| Ok("/agtx:plan\n\nmy task".to_string()));
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
send_skill_and_prompt(
- &tmux, "sess:win",
- &Some("/agtx:plan".to_string()), "my task",
- &None, "my task", "gemini", &[],
+ &tmux,
+ "sess:win",
+ &Some("/agtx:plan".to_string()),
+ "my task",
+ &None,
+ "my task",
+ "gemini",
+ &[],
);
let calls = literal_calls.lock().unwrap();
- assert!(calls.iter().any(|c| c.contains("/agtx:plan") && c.contains("my task")));
+ assert!(calls
+ .iter()
+ .any(|c| c.contains("/agtx:plan") && c.contains("my task")));
assert!(calls.iter().any(|c| c == "Enter"));
}
@@ -2949,22 +3223,28 @@ fn test_send_skill_and_prompt_codex_combined() {
let literal_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let literal_c = literal_calls.clone();
- mock.expect_send_keys_literal()
- .returning(move |_, text| {
- literal_c.lock().unwrap().push(text.to_string());
- Ok(())
- });
+ mock.expect_send_keys_literal().returning(move |_, text| {
+ literal_c.lock().unwrap().push(text.to_string());
+ Ok(())
+ });
mock.expect_capture_pane()
.returning(|_| Ok("$agtx-plan\n\ndo the thing".to_string()));
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
send_skill_and_prompt(
- &tmux, "sess:win",
- &Some("$agtx-plan".to_string()), "do the thing",
- &None, "do the thing", "codex", &[],
+ &tmux,
+ "sess:win",
+ &Some("$agtx-plan".to_string()),
+ "do the thing",
+ &None,
+ "do the thing",
+ "codex",
+ &[],
);
let calls = literal_calls.lock().unwrap();
- assert!(calls.iter().any(|c| c.contains("$agtx-plan") && c.contains("do the thing")));
+ assert!(calls
+ .iter()
+ .any(|c| c.contains("$agtx-plan") && c.contains("do the thing")));
assert!(calls.iter().any(|c| c == "Enter"));
}
@@ -2975,11 +3255,10 @@ fn test_send_skill_and_prompt_claude_with_trigger() {
let keys_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let keys_c = keys_calls.clone();
- mock.expect_send_keys()
- .returning(move |_, k| {
- keys_c.lock().unwrap().push(k.to_string());
- Ok(())
- });
+ mock.expect_send_keys().returning(move |_, k| {
+ keys_c.lock().unwrap().push(k.to_string());
+ Ok(())
+ });
mock.expect_send_keys_literal().returning(|_, _| Ok(()));
// Return trigger text immediately
mock.expect_capture_pane()
@@ -2987,13 +3266,24 @@ fn test_send_skill_and_prompt_claude_with_trigger() {
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
send_skill_and_prompt(
- &tmux, "sess:win",
- &Some("/agtx:plan".to_string()), "implement this",
- &Some("Ready for input".to_string()), "implement this", "claude", &[],
+ &tmux,
+ "sess:win",
+ &Some("/agtx:plan".to_string()),
+ "implement this",
+ &Some("Ready for input".to_string()),
+ "implement this",
+ "claude",
+ &[],
);
let calls = keys_calls.lock().unwrap();
- assert!(calls.iter().any(|c| c == "/agtx:plan"), "skill should be sent");
- assert!(calls.iter().any(|c| c == "implement this"), "prompt should be sent after trigger");
+ assert!(
+ calls.iter().any(|c| c == "/agtx:plan"),
+ "skill should be sent"
+ );
+ assert!(
+ calls.iter().any(|c| c == "implement this"),
+ "prompt should be sent after trigger"
+ );
}
#[test]
@@ -3003,17 +3293,21 @@ fn test_send_skill_and_prompt_prompt_only() {
let keys_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let keys_c = keys_calls.clone();
- mock.expect_send_keys()
- .returning(move |_, k| {
- keys_c.lock().unwrap().push(k.to_string());
- Ok(())
- });
+ mock.expect_send_keys().returning(move |_, k| {
+ keys_c.lock().unwrap().push(k.to_string());
+ Ok(())
+ });
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
send_skill_and_prompt(
- &tmux, "sess:win",
- &None, "just a prompt",
- &None, "just a prompt", "claude", &[],
+ &tmux,
+ "sess:win",
+ &None,
+ "just a prompt",
+ &None,
+ "just a prompt",
+ "claude",
+ &[],
);
let calls = keys_calls.lock().unwrap();
assert_eq!(calls.len(), 1);
@@ -3027,17 +3321,21 @@ fn test_send_skill_and_prompt_void_prefill() {
let literal_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let literal_c = literal_calls.clone();
- mock.expect_send_keys_literal()
- .returning(move |_, text| {
- literal_c.lock().unwrap().push(text.to_string());
- Ok(())
- });
+ mock.expect_send_keys_literal().returning(move |_, text| {
+ literal_c.lock().unwrap().push(text.to_string());
+ Ok(())
+ });
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
send_skill_and_prompt(
- &tmux, "sess:win",
- &None, "",
- &None, "fix the login bug", "claude", &[],
+ &tmux,
+ "sess:win",
+ &None,
+ "",
+ &None,
+ "fix the login bug",
+ "claude",
+ &[],
);
let calls = literal_calls.lock().unwrap();
assert_eq!(calls.len(), 1);
@@ -3070,20 +3368,20 @@ fn test_wait_for_prompt_trigger_auto_dismiss_then_trigger() {
let dismiss_sent = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let dismiss_c = dismiss_sent.clone();
- mock.expect_capture_pane()
- .returning(move |_| {
- let n = call_c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- if n < 8 {
- Ok("Do you accept? [y/n]".to_string())
- } else {
- Ok("Ready for input >".to_string())
- }
- });
- mock.expect_send_keys_literal()
- .returning(move |_, k| {
- if k == "y" { dismiss_c.store(true, std::sync::atomic::Ordering::SeqCst); }
- Ok(())
- });
+ mock.expect_capture_pane().returning(move |_| {
+ let n = call_c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if n < 8 {
+ Ok("Do you accept? [y/n]".to_string())
+ } else {
+ Ok("Ready for input >".to_string())
+ }
+ });
+ mock.expect_send_keys_literal().returning(move |_, k| {
+ if k == "y" {
+ dismiss_c.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+ Ok(())
+ });
let auto_dismiss = vec![AutoDismiss {
detect: vec!["Do you accept?".to_string()],
@@ -3138,17 +3436,19 @@ fn test_wait_for_agent_ready_claude_bypass_accept() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("Do you trust this? Yes, I accept the terms".to_string()));
- mock.expect_send_keys_literal()
- .returning(move |_, k| {
- literal_c.lock().unwrap().push(k.to_string());
- Ok(())
- });
+ mock.expect_send_keys_literal().returning(move |_, k| {
+ literal_c.lock().unwrap().push(k.to_string());
+ Ok(())
+ });
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
let result = wait_for_agent_ready(&tmux, "sess:win");
assert_eq!(result, Some("sess:win".to_string()));
let calls = literal_calls.lock().unwrap();
- assert!(calls.contains(&"2".to_string()), "should send '2' to accept");
+ assert!(
+ calls.contains(&"2".to_string()),
+ "should send '2' to accept"
+ );
assert!(calls.contains(&"Enter".to_string()), "should send Enter");
}
@@ -3165,15 +3465,27 @@ fn test_write_skills_to_worktree_claude() {
// Canonical skills
assert!(dir.path().join(".agtx/skills/agtx-plan/SKILL.md").exists());
- assert!(dir.path().join(".agtx/skills/agtx-execute/SKILL.md").exists());
- assert!(dir.path().join(".agtx/skills/agtx-review/SKILL.md").exists());
- assert!(dir.path().join(".agtx/skills/agtx-research/SKILL.md").exists());
+ assert!(dir
+ .path()
+ .join(".agtx/skills/agtx-execute/SKILL.md")
+ .exists());
+ assert!(dir
+ .path()
+ .join(".agtx/skills/agtx-review/SKILL.md")
+ .exists());
+ assert!(dir
+ .path()
+ .join(".agtx/skills/agtx-research/SKILL.md")
+ .exists());
// Claude-native paths
assert!(dir.path().join(".claude/commands/agtx/plan.md").exists());
assert!(dir.path().join(".claude/commands/agtx/execute.md").exists());
assert!(dir.path().join(".claude/commands/agtx/review.md").exists());
- assert!(dir.path().join(".claude/commands/agtx/research.md").exists());
+ assert!(dir
+ .path()
+ .join(".claude/commands/agtx/research.md")
+ .exists());
}
#[test]
@@ -3186,8 +3498,14 @@ fn test_write_skills_to_worktree_gemini_toml() {
let toml_path = dir.path().join(".gemini/commands/agtx/plan.toml");
assert!(toml_path.exists());
let content = std::fs::read_to_string(&toml_path).unwrap();
- assert!(content.contains("description"), "Gemini TOML should have description field");
- assert!(content.contains("prompt"), "Gemini TOML should have prompt field");
+ assert!(
+ content.contains("description"),
+ "Gemini TOML should have description field"
+ );
+ assert!(
+ content.contains("prompt"),
+ "Gemini TOML should have prompt field"
+ );
}
#[test]
@@ -3199,7 +3517,10 @@ fn test_write_skills_to_worktree_codex() {
// Codex uses subdirectories with SKILL.md
assert!(dir.path().join(".codex/skills/agtx-plan/SKILL.md").exists());
- assert!(dir.path().join(".codex/skills/agtx-execute/SKILL.md").exists());
+ assert!(dir
+ .path()
+ .join(".codex/skills/agtx-execute/SKILL.md")
+ .exists());
}
#[test]
@@ -3212,7 +3533,10 @@ fn test_write_skills_to_worktree_opencode() {
let md_path = dir.path().join(".opencode/commands/agtx-plan.md");
assert!(md_path.exists());
let content = std::fs::read_to_string(&md_path).unwrap();
- assert!(content.starts_with("---\ndescription:"), "OpenCode should have description frontmatter");
+ assert!(
+ content.starts_with("---\ndescription:"),
+ "OpenCode should have description frontmatter"
+ );
}
// =============================================================================
@@ -3233,12 +3557,16 @@ fn test_load_task_plugin_from_disk() {
let dir = tempfile::tempdir().unwrap();
let plugin_dir = dir.path().join(".agtx").join("plugins").join("test-plug");
std::fs::create_dir_all(&plugin_dir).unwrap();
- std::fs::write(plugin_dir.join("plugin.toml"), r#"
+ std::fs::write(
+ plugin_dir.join("plugin.toml"),
+ r#"
name = "test-plug"
[commands]
[prompts]
[artifacts]
- "#).unwrap();
+ "#,
+ )
+ .unwrap();
let mut task = crate::db::Task::new("Test", "claude", "proj");
task.plugin = Some("test-plug".to_string());
@@ -3253,13 +3581,17 @@ fn test_load_task_plugin_unsupported_agent_returns_none() {
let dir = tempfile::tempdir().unwrap();
let plugin_dir = dir.path().join(".agtx").join("plugins").join("claude-only");
std::fs::create_dir_all(&plugin_dir).unwrap();
- std::fs::write(plugin_dir.join("plugin.toml"), r#"
+ std::fs::write(
+ plugin_dir.join("plugin.toml"),
+ r#"
name = "claude-only"
supported_agents = ["claude"]
[commands]
[prompts]
[artifacts]
- "#).unwrap();
+ "#,
+ )
+ .unwrap();
let mut task = crate::db::Task::new("Test", "gemini", "proj");
task.plugin = Some("claude-only".to_string());
@@ -3290,54 +3622,81 @@ fn test_load_task_plugin_bundled_fallback() {
#[test]
fn test_phase_accepts_task_with_task_placeholder() {
use crate::config::WorkflowPlugin;
- let plugin: WorkflowPlugin = toml::from_str(r#"
+ let plugin: WorkflowPlugin = toml::from_str(
+ r#"
name = "test"
[commands]
planning = "/test:plan {task}"
[prompts]
[artifacts]
- "#).unwrap();
- assert!(plugin.phase_accepts_task("planning"), "command with {{task}} should be accepted");
+ "#,
+ )
+ .unwrap();
+ assert!(
+ plugin.phase_accepts_task("planning"),
+ "command with {{task}} should be accepted"
+ );
}
#[test]
fn test_phase_accepts_task_without_task_placeholder() {
use crate::config::WorkflowPlugin;
- let plugin: WorkflowPlugin = toml::from_str(r#"
+ let plugin: WorkflowPlugin = toml::from_str(
+ r#"
name = "test"
[commands]
planning = "/test:plan {phase}"
[prompts]
[artifacts]
- "#).unwrap();
- assert!(!plugin.phase_accepts_task("planning"), "command without {{task}} should be blocked");
+ "#,
+ )
+ .unwrap();
+ assert!(
+ !plugin.phase_accepts_task("planning"),
+ "command without {{task}} should be blocked"
+ );
}
#[test]
fn test_phase_accepts_task_void_plugin_ungated() {
use crate::config::WorkflowPlugin;
// Void plugin: no commands, no prompts β€” should be ungated
- let plugin: WorkflowPlugin = toml::from_str(r#"
+ let plugin: WorkflowPlugin = toml::from_str(
+ r#"
name = "void"
[commands]
[prompts]
[artifacts]
- "#).unwrap();
- assert!(plugin.phase_accepts_task("planning"), "void plugin should be ungated for planning");
- assert!(plugin.phase_accepts_task("running"), "void plugin should be ungated for running");
+ "#,
+ )
+ .unwrap();
+ assert!(
+ plugin.phase_accepts_task("planning"),
+ "void plugin should be ungated for planning"
+ );
+ assert!(
+ plugin.phase_accepts_task("running"),
+ "void plugin should be ungated for running"
+ );
}
#[test]
fn test_phase_accepts_task_prompt_with_task() {
use crate::config::WorkflowPlugin;
- let plugin: WorkflowPlugin = toml::from_str(r#"
+ let plugin: WorkflowPlugin = toml::from_str(
+ r#"
name = "test"
[commands]
[prompts]
planning = "Task: {task}"
[artifacts]
- "#).unwrap();
- assert!(plugin.phase_accepts_task("planning"), "prompt with {{task}} should be accepted");
+ "#,
+ )
+ .unwrap();
+ assert!(
+ plugin.phase_accepts_task("planning"),
+ "prompt with {{task}} should be accepted"
+ );
}
// === App Integration Tests ===
@@ -3359,7 +3718,8 @@ fn make_test_app() -> App {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap()
+ )
+ .unwrap()
}
/// Helper: simulate a key press on the App.
@@ -3368,7 +3728,8 @@ fn press_key(app: &mut App, code: KeyCode) {
app.handle_key(crossterm::event::KeyEvent::new(
code,
crossterm::event::KeyModifiers::NONE,
- )).unwrap();
+ ))
+ .unwrap();
}
/// Helper: simulate typing a string into the App (character by character).
@@ -3399,7 +3760,8 @@ fn test_app_new_for_test_dashboard_mode() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
assert_eq!(app.state.project_name, "Dashboard");
assert!(app.state.db.is_none());
}
@@ -3447,7 +3809,10 @@ fn test_create_task_full_flow() {
assert_eq!(app.state.board.tasks.len(), 1);
let task = &app.state.board.tasks[0];
assert_eq!(task.title, "Fix login bug");
- assert_eq!(task.description.as_deref(), Some("Users report 500 error on the login page"));
+ assert_eq!(
+ task.description.as_deref(),
+ Some("Users report 500 error on the login page")
+ );
assert_eq!(task.status, TaskStatus::Backlog);
}
@@ -3489,8 +3854,10 @@ fn test_board_navigation_with_tasks() {
// Create two tasks
let db = app.state.db.as_ref().unwrap();
- db.create_task(&Task::new("Task 1", "claude", "test-project")).unwrap();
- db.create_task(&Task::new("Task 2", "claude", "test-project")).unwrap();
+ db.create_task(&Task::new("Task 1", "claude", "test-project"))
+ .unwrap();
+ db.create_task(&Task::new("Task 2", "claude", "test-project"))
+ .unwrap();
app.refresh_tasks().unwrap();
assert_eq!(app.state.board.tasks.len(), 2);
@@ -3524,7 +3891,8 @@ fn test_delete_task_confirm() {
// Create a task
let db = app.state.db.as_ref().unwrap();
- db.create_task(&Task::new("Delete me", "claude", "test-project")).unwrap();
+ db.create_task(&Task::new("Delete me", "claude", "test-project"))
+ .unwrap();
app.refresh_tasks().unwrap();
assert_eq!(app.state.board.tasks.len(), 1);
@@ -3544,7 +3912,8 @@ fn test_delete_task_cancel() {
let mut app = make_test_app();
let db = app.state.db.as_ref().unwrap();
- db.create_task(&Task::new("Keep me", "claude", "test-project")).unwrap();
+ db.create_task(&Task::new("Keep me", "claude", "test-project"))
+ .unwrap();
app.refresh_tasks().unwrap();
press_key(&mut app, KeyCode::Char('x'));
@@ -3569,7 +3938,10 @@ fn test_quit_sets_should_quit() {
#[test]
fn test_merge_conflicts_skill_name_to_command() {
- assert_eq!(skills::skill_name_to_command("agtx-merge-conflicts"), "agtx:merge-conflicts");
+ assert_eq!(
+ skills::skill_name_to_command("agtx-merge-conflicts"),
+ "agtx:merge-conflicts"
+ );
}
#[test]
@@ -3600,7 +3972,9 @@ fn test_merge_conflicts_transform_plugin_command() {
fn test_merge_conflicts_skill_registered() {
// Verify the merge-conflicts skill is in BUILTIN_SKILLS
assert!(
- skills::BUILTIN_SKILLS.iter().any(|(name, _)| *name == "agtx-merge-conflicts"),
+ skills::BUILTIN_SKILLS
+ .iter()
+ .any(|(name, _)| *name == "agtx-merge-conflicts"),
"agtx-merge-conflicts should be registered in BUILTIN_SKILLS"
);
}
@@ -3620,12 +3994,23 @@ fn make_test_app_with_agents() -> App {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
// Inject 2 agents so wizard doesn't auto-skip
app.state.available_agents = vec![
- crate::agent::Agent::new("claude", "claude", "Anthropic Claude", "Claude <[email protected]>"),
- crate::agent::Agent::new("codex", "codex", "OpenAI Codex", "Codex <[email protected]>"),
+ crate::agent::Agent::new(
+ "claude",
+ "claude",
+ "Anthropic Claude",
+ "Claude <[email protected]>",
+ ),
+ crate::agent::Agent::new(
+ "codex",
+ "codex",
+ "OpenAI Codex",
+ "Codex <[email protected]>",
+ ),
];
app
}
@@ -3715,7 +4100,9 @@ fn test_wizard_saves_with_selected_plugin() {
// Move to a non-default plugin (index 1 should be gsd or similar)
press_key(&mut app, KeyCode::Char('j'));
- let selected_plugin = app.state.wizard_plugin_options[app.state.wizard_selected_plugin].name.clone();
+ let selected_plugin = app.state.wizard_plugin_options[app.state.wizard_selected_plugin]
+ .name
+ .clone();
press_key(&mut app, KeyCode::Enter);
assert_eq!(app.state.input_mode, InputMode::InputDescription);
press_key(&mut app, KeyCode::Enter); // save with no description
@@ -3825,7 +4212,8 @@ fn test_task_ref_search_exclamation_trigger() {
let mut app = make_test_app();
// Add a task to the board so search has results
let db = app.state.db.as_ref().unwrap();
- db.create_task(&Task::new("Setup auth", "claude", "test-project")).unwrap();
+ db.create_task(&Task::new("Setup auth", "claude", "test-project"))
+ .unwrap();
app.refresh_tasks().unwrap();
assert_eq!(app.state.board.tasks.len(), 1);
@@ -3848,7 +4236,8 @@ fn test_task_ref_inserts_reference() {
let mut app = make_test_app();
// Add a task to the board
let db = app.state.db.as_ref().unwrap();
- db.create_task(&Task::new("Setup auth", "claude", "test-project")).unwrap();
+ db.create_task(&Task::new("Setup auth", "claude", "test-project"))
+ .unwrap();
app.refresh_tasks().unwrap();
press_key(&mut app, KeyCode::Char('o'));
@@ -3865,7 +4254,11 @@ fn test_task_ref_inserts_reference() {
assert!(app.state.task_ref_search.is_none()); // search closed
// Buffer should contain ![Setup auth]
- assert!(app.state.input_buffer.contains("![Setup auth]"), "Buffer: {}", app.state.input_buffer);
+ assert!(
+ app.state.input_buffer.contains("![Setup auth]"),
+ "Buffer: {}",
+ app.state.input_buffer
+ );
// Referenced task ID should be tracked
assert!(!app.state.wizard_referenced_task_ids.is_empty());
// Highlighted references should contain the reference text
@@ -3877,7 +4270,8 @@ fn test_task_ref_inserts_reference() {
fn test_task_ref_after_space() {
let mut app = make_test_app();
let db = app.state.db.as_ref().unwrap();
- db.create_task(&Task::new("Other task", "claude", "test-project")).unwrap();
+ db.create_task(&Task::new("Other task", "claude", "test-project"))
+ .unwrap();
app.refresh_tasks().unwrap();
press_key(&mut app, KeyCode::Char('o'));
@@ -3907,9 +4301,21 @@ fn test_footer_text_select_plugin() {
#[cfg(feature = "test-mocks")]
fn test_footer_text_description_shows_all_triggers() {
let text = build_footer_text(InputMode::InputDescription, false, 0, false);
- assert!(text.contains("[#] files"), "Missing files trigger: {}", text);
- assert!(text.contains("[/] skills"), "Missing skills trigger: {}", text);
- assert!(text.contains("[!] tasks"), "Missing tasks trigger: {}", text);
+ assert!(
+ text.contains("[#] files"),
+ "Missing files trigger: {}",
+ text
+ );
+ assert!(
+ text.contains("[/] skills"),
+ "Missing skills trigger: {}",
+ text
+ );
+ assert!(
+ text.contains("[!] tasks"),
+ "Missing tasks trigger: {}",
+ text
+ );
}
// =============================================================================
@@ -3919,33 +4325,22 @@ fn test_footer_text_description_shows_all_triggers() {
#[test]
fn test_orchestrator_idle_signal_in_new_content() {
// Content changed AND contains [agtx:idle] β†’ Idle
- let result = check_orchestrator_idle(
- "some output\n[agtx:idle]\n",
- "previous content",
- None,
- );
+ let result = check_orchestrator_idle("some output\n[agtx:idle]\n", "previous content", None);
assert_eq!(result, OrchestratorIdleResult::Idle);
}
#[test]
fn test_orchestrator_busy_when_content_changed_no_signal() {
// Content changed but no idle signal β†’ Busy
- let result = check_orchestrator_idle(
- "agent is working on something...",
- "previous content",
- None,
- );
+ let result =
+ check_orchestrator_idle("agent is working on something...", "previous content", None);
assert_eq!(result, OrchestratorIdleResult::Busy);
}
#[test]
fn test_orchestrator_waiting_when_unchanged_no_stable_since() {
// Content unchanged, no stable_since yet β†’ Waiting (start tracking)
- let result = check_orchestrator_idle(
- "same content",
- "same content",
- None,
- );
+ let result = check_orchestrator_idle("same content", "same content", None);
assert_eq!(result, OrchestratorIdleResult::Waiting);
}
@@ -3974,11 +4369,8 @@ fn test_orchestrator_idle_fallback_after_threshold() {
#[test]
fn test_orchestrator_idle_signal_takes_priority_over_content_change() {
// Even if content just changed, the idle signal means we're ready
- let result = check_orchestrator_idle(
- "new output with [agtx:idle] at the end",
- "old output",
- None,
- );
+ let result =
+ check_orchestrator_idle("new output with [agtx:idle] at the end", "old output", None);
assert_eq!(result, OrchestratorIdleResult::Idle);
}
@@ -4029,7 +4421,8 @@ fn test_check_phase_incomplete_skip_move_confirm() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
app.state.skip_move_confirm = true;
let task = make_test_task("t1", "My task", TaskStatus::Planning);
@@ -4049,7 +4442,8 @@ fn test_check_phase_incomplete_backlog_returns_false() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let task = make_test_task("t1", "My task", TaskStatus::Backlog);
let result = app.check_phase_incomplete(&task, TaskStatus::Backlog, TaskStatus::Planning);
@@ -4068,7 +4462,8 @@ fn test_check_phase_incomplete_no_worktree_returns_false() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Planning);
task.worktree_path = None;
@@ -4095,7 +4490,8 @@ fn test_check_phase_incomplete_artifact_exists_returns_false() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Planning);
task.worktree_path = Some(tmp.to_string_lossy().to_string());
@@ -4114,9 +4510,7 @@ fn test_check_phase_incomplete_no_tmux_window_returns_false() {
std::fs::create_dir_all(&tmp).unwrap();
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux
- .expect_window_exists()
- .returning(|_| Ok(false));
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -4124,7 +4518,8 @@ fn test_check_phase_incomplete_no_tmux_window_returns_false() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Planning);
task.worktree_path = Some(tmp.to_string_lossy().to_string());
@@ -4145,9 +4540,7 @@ fn test_check_phase_incomplete_agent_running_sets_popup() {
std::fs::create_dir_all(&tmp).unwrap();
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux
- .expect_window_exists()
- .returning(|_| Ok(true));
+ mock_tmux.expect_window_exists().returning(|_| Ok(true));
// is_agent_active checks pane_current_command first
mock_tmux
.expect_pane_current_command()
@@ -4159,7 +4552,8 @@ fn test_check_phase_incomplete_agent_running_sets_popup() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Planning);
task.worktree_path = Some(tmp.to_string_lossy().to_string());
@@ -4191,7 +4585,8 @@ fn test_transition_to_planning_stamps_plugin() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
// Set the project workflow plugin
app.state.config.workflow_plugin = Some("agtx".to_string());
@@ -4216,7 +4611,8 @@ fn test_transition_to_planning_warning_when_research_required() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Backlog);
// Use gsd plugin β€” planning phase requires prior research artifact
@@ -4235,13 +4631,15 @@ fn test_transition_to_planning_warning_when_research_required() {
fn test_transition_to_planning_reuses_live_session() {
// Task has a live session β†’ reuses it (returns Ok(false) to continue with db update)
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux
- .expect_window_exists()
- .returning(|_| Ok(true));
+ mock_tmux.expect_window_exists().returning(|_| Ok(true));
// spawn_send_to_agent may call these; allow any number of calls
mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
- mock_tmux.expect_send_keys_literal().returning(|_, _| Ok(()));
- mock_tmux.expect_capture_pane().returning(|_| Ok(String::new()));
+ mock_tmux
+ .expect_send_keys_literal()
+ .returning(|_, _| Ok(()));
+ mock_tmux
+ .expect_capture_pane()
+ .returning(|_| Ok(String::new()));
let mut mock_registry = MockAgentRegistry::new();
mock_registry
@@ -4254,7 +4652,8 @@ fn test_transition_to_planning_reuses_live_session() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Backlog);
task.session_name = Some("test-project:task-t1--test-project--my-task".to_string());
@@ -4276,7 +4675,8 @@ fn test_transition_to_planning_returns_true_when_setup_in_progress() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
// Pre-set a setup_rx to simulate in-progress setup
let (_tx, rx) = std::sync::mpsc::channel::<SetupResult>();
@@ -4311,7 +4711,8 @@ fn test_transition_to_planning_spawns_background_setup() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Backlog);
task.plugin = Some("agtx".to_string());
@@ -4337,7 +4738,8 @@ fn test_transition_to_running_no_session_returns_false() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Planning);
task.session_name = None;
@@ -4354,8 +4756,12 @@ fn test_transition_to_running_with_session_returns_false() {
// Task has a session β†’ spawns send_to_agent (background), still returns Ok(false)
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
- mock_tmux.expect_send_keys_literal().returning(|_, _| Ok(()));
- mock_tmux.expect_capture_pane().returning(|_| Ok(String::new()));
+ mock_tmux
+ .expect_send_keys_literal()
+ .returning(|_, _| Ok(()));
+ mock_tmux
+ .expect_capture_pane()
+ .returning(|_| Ok(String::new()));
let mut mock_registry = MockAgentRegistry::new();
mock_registry
@@ -4368,7 +4774,8 @@ fn test_transition_to_running_with_session_returns_false() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Planning);
task.session_name = Some("test-project:task-t1".to_string());
@@ -4390,8 +4797,12 @@ fn test_transition_to_review_no_pr_sets_review_confirm_popup() {
// No existing PR β†’ shows review confirm popup (to ask if user wants to create PR)
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
- mock_tmux.expect_send_keys_literal().returning(|_, _| Ok(()));
- mock_tmux.expect_capture_pane().returning(|_| Ok(String::new()));
+ mock_tmux
+ .expect_send_keys_literal()
+ .returning(|_, _| Ok(()));
+ mock_tmux
+ .expect_capture_pane()
+ .returning(|_| Ok(String::new()));
let mut mock_registry = MockAgentRegistry::new();
mock_registry
@@ -4404,7 +4815,8 @@ fn test_transition_to_review_no_pr_sets_review_confirm_popup() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "Implement feature", TaskStatus::Running);
task.pr_number = None;
@@ -4425,8 +4837,12 @@ fn test_transition_to_review_existing_pr_spawns_push() {
// PR already exists β†’ sets pr_status_popup (Pushing) and spawns push thread
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
- mock_tmux.expect_send_keys_literal().returning(|_, _| Ok(()));
- mock_tmux.expect_capture_pane().returning(|_| Ok(String::new()));
+ mock_tmux
+ .expect_send_keys_literal()
+ .returning(|_, _| Ok(()));
+ mock_tmux
+ .expect_capture_pane()
+ .returning(|_| Ok(String::new()));
let mut mock_git = MockGitOperations::new();
// push_changes_to_existing_pr calls add_all, has_changes, push
@@ -4436,7 +4852,9 @@ fn test_transition_to_review_existing_pr_spawns_push() {
let mut mock_registry = MockAgentRegistry::new();
let mut mock_agent_ops = MockAgentOperations::new();
- mock_agent_ops.expect_co_author_string().return_const("Test <[email protected]>".to_string());
+ mock_agent_ops
+ .expect_co_author_string()
+ .return_const("Test <[email protected]>".to_string());
let mock_agent_arc: Arc<dyn AgentOperations> = Arc::new(mock_agent_ops);
mock_registry
.expect_get()
@@ -4448,7 +4866,8 @@ fn test_transition_to_review_existing_pr_spawns_push() {
Arc::new(mock_git),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "Implement feature", TaskStatus::Running);
task.pr_number = Some(42);
@@ -4484,7 +4903,8 @@ fn test_transition_to_done_merged_pr_shows_popup() {
Arc::new(MockGitOperations::new()),
Arc::new(mock_git_provider),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Review);
task.pr_number = Some(5);
@@ -4506,9 +4926,7 @@ fn test_transition_to_done_uncommitted_changes_shows_popup() {
let mock_tmux = MockTmuxOperations::new();
let mut mock_git = MockGitOperations::new();
- mock_git
- .expect_has_changes()
- .returning(|_| true);
+ mock_git.expect_has_changes().returning(|_| true);
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -4516,7 +4934,8 @@ fn test_transition_to_done_uncommitted_changes_shows_popup() {
Arc::new(mock_git),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Review);
task.pr_number = None;
@@ -4528,7 +4947,10 @@ fn test_transition_to_done_uncommitted_changes_shows_popup() {
assert_eq!(result.unwrap(), true);
assert!(app.state.done_confirm_popup.is_some());
let popup = app.state.done_confirm_popup.as_ref().unwrap();
- assert!(matches!(popup.pr_state, DoneConfirmPrState::UncommittedChanges));
+ assert!(matches!(
+ popup.pr_state,
+ DoneConfirmPrState::UncommittedChanges
+ ));
}
#[test]
@@ -4540,9 +4962,7 @@ fn test_transition_to_done_clean_clears_session_and_worktree() {
mock_tmux.expect_kill_window().returning(|_| Ok(()));
let mut mock_git = MockGitOperations::new();
- mock_git
- .expect_has_changes()
- .returning(|_| false);
+ mock_git.expect_has_changes().returning(|_| false);
// cleanup_task_resources may call remove_worktree
mock_git.expect_remove_worktree().returning(|_, _| Ok(()));
@@ -4552,7 +4972,8 @@ fn test_transition_to_done_clean_clears_session_and_worktree() {
Arc::new(mock_git),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let mut task = make_test_task("t1", "My task", TaskStatus::Review);
task.pr_number = None;
@@ -4563,7 +4984,7 @@ fn test_transition_to_done_clean_clears_session_and_worktree() {
assert!(result.is_ok());
assert_eq!(result.unwrap(), false); // Ok(false) β†’ continue with db update
- // Task fields cleared synchronously before background thread
+ // Task fields cleared synchronously before background thread
assert!(task.session_name.is_none());
assert!(task.worktree_path.is_none());
// No popup shown
@@ -4600,7 +5021,12 @@ fn test_apply_session_refresh_working_inserts_cache() {
// Working status β†’ stored in phase_status_cache as Working
let mut app = make_test_app();
let result = SessionRefreshResult {
- statuses: vec![make_session_task_status("t1", TaskStatus::Planning, PhaseStatus::Working, false)],
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Planning,
+ PhaseStatus::Working,
+ false,
+ )],
};
app.apply_session_refresh(result);
let (phase, _) = app.state.phase_status_cache["t1"];
@@ -4613,10 +5039,17 @@ fn test_apply_session_refresh_ready_inserts_cache() {
// Ready status β†’ stored as Ready, clears idle hash
let mut app = make_test_app();
// Pre-populate a content hash so we can verify it gets removed
- app.state.pane_content_hashes.insert("t1".to_string(), (42, std::time::Instant::now()));
+ app.state
+ .pane_content_hashes
+ .insert("t1".to_string(), (42, std::time::Instant::now()));
let result = SessionRefreshResult {
- statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Ready, false)],
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Running,
+ PhaseStatus::Ready,
+ false,
+ )],
};
app.apply_session_refresh(result);
let (phase, _) = app.state.phase_status_cache["t1"];
@@ -4631,7 +5064,9 @@ fn test_apply_session_refresh_working_becomes_idle_after_15s() {
// Working with same content hash stable for β‰₯15s β†’ promoted to Idle
let mut app = make_test_app();
let old_instant = std::time::Instant::now() - std::time::Duration::from_secs(20);
- app.state.pane_content_hashes.insert("t1".to_string(), (99, old_instant));
+ app.state
+ .pane_content_hashes
+ .insert("t1".to_string(), (99, old_instant));
let result = SessionRefreshResult {
statuses: vec![SessionTaskStatus {
@@ -4656,7 +5091,9 @@ fn test_apply_session_refresh_working_stays_working_hash_changed() {
// Working with changed content hash β†’ still Working (timer resets)
let mut app = make_test_app();
let old_instant = std::time::Instant::now() - std::time::Duration::from_secs(20);
- app.state.pane_content_hashes.insert("t1".to_string(), (99, old_instant));
+ app.state
+ .pane_content_hashes
+ .insert("t1".to_string(), (99, old_instant));
let result = SessionRefreshResult {
statuses: vec![SessionTaskStatus {
@@ -4687,7 +5124,8 @@ fn test_apply_session_refresh_newly_ready_notifies_orchestrator() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
// Add a task so the notification message can include its title
let db = app.state.db.as_ref().unwrap();
@@ -4701,14 +5139,22 @@ fn test_apply_session_refresh_newly_ready_notifies_orchestrator() {
app.state.orchestrator_session = Some("orch-session".to_string());
let result = SessionRefreshResult {
- statuses: vec![make_session_task_status("t1", TaskStatus::Planning, PhaseStatus::Ready, false)],
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Planning,
+ PhaseStatus::Ready,
+ false,
+ )],
};
app.apply_session_refresh(result);
// Notification should have been written to the DB
let db = app.state.db.as_ref().unwrap();
let notifs = db.peek_notifications().unwrap();
- assert!(!notifs.is_empty(), "should have created an orchestrator notification");
+ assert!(
+ !notifs.is_empty(),
+ "should have created an orchestrator notification"
+ );
assert!(notifs[0].message.contains("My feature"));
assert!(notifs[0].message.contains("planning"));
}
@@ -4725,11 +5171,17 @@ fn test_apply_session_refresh_already_ready_no_notification() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
app.state.orchestrator_session = Some("orch-session".to_string());
let result = SessionRefreshResult {
- statuses: vec![make_session_task_status("t1", TaskStatus::Planning, PhaseStatus::Ready, true)],
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Planning,
+ PhaseStatus::Ready,
+ true,
+ )],
};
app.apply_session_refresh(result);
@@ -4776,7 +5228,8 @@ fn test_handle_done_confirm_y_force_moves_to_done() {
Arc::new(mock_git),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
// Create a task in the DB so force_move_to_done can find it
let db = app.state.db.as_ref().unwrap();
@@ -4792,12 +5245,20 @@ fn test_handle_done_confirm_y_force_moves_to_done() {
pr_state: DoneConfirmPrState::UncommittedChanges,
});
- let key = crossterm::event::KeyEvent::new(KeyCode::Char('y'), crossterm::event::KeyModifiers::NONE);
+ let key =
+ crossterm::event::KeyEvent::new(KeyCode::Char('y'), crossterm::event::KeyModifiers::NONE);
app.handle_done_confirm_key(key).unwrap();
assert!(app.state.done_confirm_popup.is_none());
// Task should be Done in DB
- let updated = app.state.db.as_ref().unwrap().get_task("t1").unwrap().unwrap();
+ let updated = app
+ .state
+ .db
+ .as_ref()
+ .unwrap()
+ .get_task("t1")
+ .unwrap()
+ .unwrap();
assert_eq!(updated.status, TaskStatus::Done);
}
@@ -4811,7 +5272,8 @@ fn test_handle_done_confirm_n_cancels() {
pr_state: DoneConfirmPrState::UncommittedChanges,
});
- let key = crossterm::event::KeyEvent::new(KeyCode::Char('n'), crossterm::event::KeyModifiers::NONE);
+ let key =
+ crossterm::event::KeyEvent::new(KeyCode::Char('n'), crossterm::event::KeyModifiers::NONE);
app.handle_done_confirm_key(key).unwrap();
assert!(app.state.done_confirm_popup.is_none()); // popup dismissed
@@ -4843,7 +5305,9 @@ fn test_handle_move_confirm_y_clears_popup_and_moves() {
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_window_exists().returning(|_| Ok(false));
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -4851,7 +5315,8 @@ fn test_handle_move_confirm_y_clears_popup_and_moves() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("My task", "claude", "test-project");
@@ -4865,7 +5330,8 @@ fn test_handle_move_confirm_y_clears_popup_and_moves() {
to_status: TaskStatus::Planning,
});
- let key = crossterm::event::KeyEvent::new(KeyCode::Char('y'), crossterm::event::KeyModifiers::NONE);
+ let key =
+ crossterm::event::KeyEvent::new(KeyCode::Char('y'), crossterm::event::KeyModifiers::NONE);
app.handle_move_confirm_key(key).unwrap();
assert!(app.state.move_confirm_popup.is_none());
@@ -4883,7 +5349,8 @@ fn test_handle_move_confirm_n_only_clears_popup() {
to_status: TaskStatus::Running,
});
- let key = crossterm::event::KeyEvent::new(KeyCode::Char('n'), crossterm::event::KeyModifiers::NONE);
+ let key =
+ crossterm::event::KeyEvent::new(KeyCode::Char('n'), crossterm::event::KeyModifiers::NONE);
app.handle_move_confirm_key(key).unwrap();
assert!(app.state.move_confirm_popup.is_none());
@@ -4913,13 +5380,19 @@ fn test_handle_move_confirm_esc_clears_popup() {
fn test_handle_review_confirm_y_starts_pr_generation() {
// y β†’ calls move_running_to_review_with_pr β†’ opens pr_confirm_popup (generating=true)
let mut mock_git = MockGitOperations::new();
- mock_git.expect_diff_stat_from_main().returning(|_| String::new());
+ mock_git
+ .expect_diff_stat_from_main()
+ .returning(|_| String::new());
let mut mock_registry = MockAgentRegistry::new();
let mut mock_agent_ops = MockAgentOperations::new();
- mock_agent_ops.expect_generate_text().returning(|_, _| Ok(String::new()));
+ mock_agent_ops
+ .expect_generate_text()
+ .returning(|_, _| Ok(String::new()));
let ops_arc: Arc<dyn AgentOperations> = Arc::new(mock_agent_ops);
- mock_registry.expect_get().returning(move |_| Arc::clone(&ops_arc));
+ mock_registry
+ .expect_get()
+ .returning(move |_| Arc::clone(&ops_arc));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -4927,7 +5400,8 @@ fn test_handle_review_confirm_y_starts_pr_generation() {
Arc::new(mock_git),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
// Create a Running task in the DB
let db = app.state.db.as_ref().unwrap();
@@ -4942,7 +5416,8 @@ fn test_handle_review_confirm_y_starts_pr_generation() {
task_title: "My feature".to_string(),
});
- let key = crossterm::event::KeyEvent::new(KeyCode::Char('y'), crossterm::event::KeyModifiers::NONE);
+ let key =
+ crossterm::event::KeyEvent::new(KeyCode::Char('y'), crossterm::event::KeyModifiers::NONE);
app.handle_review_confirm_key(key).unwrap();
assert!(app.state.review_confirm_popup.is_none());
@@ -4963,7 +5438,8 @@ fn test_handle_review_confirm_n_moves_without_pr() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("My feature", "claude", "test-project");
@@ -4977,13 +5453,21 @@ fn test_handle_review_confirm_n_moves_without_pr() {
task_title: "My feature".to_string(),
});
- let key = crossterm::event::KeyEvent::new(KeyCode::Char('n'), crossterm::event::KeyModifiers::NONE);
+ let key =
+ crossterm::event::KeyEvent::new(KeyCode::Char('n'), crossterm::event::KeyModifiers::NONE);
app.handle_review_confirm_key(key).unwrap();
assert!(app.state.review_confirm_popup.is_none());
assert!(app.state.pr_confirm_popup.is_none()); // no PR popup
- // Task should be in Review now
- let updated = app.state.db.as_ref().unwrap().get_task("t1").unwrap().unwrap();
+ // Task should be in Review now
+ let updated = app
+ .state
+ .db
+ .as_ref()
+ .unwrap()
+ .get_task("t1")
+ .unwrap()
+ .unwrap();
assert_eq!(updated.status, TaskStatus::Review);
}
@@ -5037,7 +5521,8 @@ fn test_handle_pr_confirm_char_appends_to_active_field() {
generating: false,
});
- let key = crossterm::event::KeyEvent::new(KeyCode::Char('X'), crossterm::event::KeyModifiers::NONE);
+ let key =
+ crossterm::event::KeyEvent::new(KeyCode::Char('X'), crossterm::event::KeyModifiers::NONE);
app.handle_pr_confirm_key(key).unwrap();
assert_eq!(app.state.pr_confirm_popup.as_ref().unwrap().pr_title, "TiX");
@@ -5045,7 +5530,8 @@ fn test_handle_pr_confirm_char_appends_to_active_field() {
let tab = crossterm::event::KeyEvent::new(KeyCode::Tab, crossterm::event::KeyModifiers::NONE);
app.handle_pr_confirm_key(tab).unwrap();
- let key2 = crossterm::event::KeyEvent::new(KeyCode::Char('Z'), crossterm::event::KeyModifiers::NONE);
+ let key2 =
+ crossterm::event::KeyEvent::new(KeyCode::Char('Z'), crossterm::event::KeyModifiers::NONE);
app.handle_pr_confirm_key(key2).unwrap();
assert_eq!(app.state.pr_confirm_popup.as_ref().unwrap().pr_body, "Z");
}
@@ -5062,7 +5548,8 @@ fn test_handle_pr_confirm_backspace_removes_char() {
generating: false,
});
- let key = crossterm::event::KeyEvent::new(KeyCode::Backspace, crossterm::event::KeyModifiers::NONE);
+ let key =
+ crossterm::event::KeyEvent::new(KeyCode::Backspace, crossterm::event::KeyModifiers::NONE);
app.handle_pr_confirm_key(key).unwrap();
assert_eq!(app.state.pr_confirm_popup.as_ref().unwrap().pr_title, "AB");
}
@@ -5098,7 +5585,10 @@ fn test_handle_pr_confirm_enter_in_body_adds_newline() {
let key = crossterm::event::KeyEvent::new(KeyCode::Enter, crossterm::event::KeyModifiers::NONE);
app.handle_pr_confirm_key(key).unwrap();
- assert_eq!(app.state.pr_confirm_popup.as_ref().unwrap().pr_body, "Line1\n");
+ assert_eq!(
+ app.state.pr_confirm_popup.as_ref().unwrap().pr_body,
+ "Line1\n"
+ );
}
#[test]
@@ -5128,13 +5618,19 @@ fn test_handle_pr_confirm_ctrl_s_submits_pr() {
mock_git.expect_push().returning(|_, _, _| Ok(()));
let mut mock_git_provider = MockGitProviderOperations::new();
- mock_git_provider.expect_create_pr().returning(|_, _, _, _| Ok((1, "https://github.com/pr/1".to_string())));
+ mock_git_provider
+ .expect_create_pr()
+ .returning(|_, _, _, _| Ok((1, "https://github.com/pr/1".to_string())));
let mut mock_registry = MockAgentRegistry::new();
let mut mock_agent_ops = MockAgentOperations::new();
- mock_agent_ops.expect_co_author_string().return_const("Test <[email protected]>".to_string());
+ mock_agent_ops
+ .expect_co_author_string()
+ .return_const("Test <[email protected]>".to_string());
let ops_arc: Arc<dyn AgentOperations> = Arc::new(mock_agent_ops);
- mock_registry.expect_get().returning(move |_| Arc::clone(&ops_arc));
+ mock_registry
+ .expect_get()
+ .returning(move |_| Arc::clone(&ops_arc));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -5142,7 +5638,8 @@ fn test_handle_pr_confirm_ctrl_s_submits_pr() {
Arc::new(mock_git),
Arc::new(mock_git_provider),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
// Create task in DB
let db = app.state.db.as_ref().unwrap();
@@ -5210,7 +5707,9 @@ fn test_execute_transition_request_move_forward_backlog_to_planning() {
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_window_exists().returning(|_| Ok(false));
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -5218,7 +5717,8 @@ fn test_execute_transition_request_move_forward_backlog_to_planning() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("Plan this", "claude", "test-project");
@@ -5249,7 +5749,10 @@ fn test_execute_transition_request_move_to_running_from_wrong_status_errors() {
let req = crate::db::TransitionRequest::new("t1", "move_to_running");
let result = app.execute_transition_request(&req);
assert!(result.is_err());
- assert!(result.unwrap_err().to_string().contains("Backlog or Planning"));
+ assert!(result
+ .unwrap_err()
+ .to_string()
+ .contains("Backlog or Planning"));
}
#[test]
@@ -5266,7 +5769,10 @@ fn test_execute_transition_request_move_to_done_from_wrong_status_errors() {
let req = crate::db::TransitionRequest::new("t1", "move_to_done");
let result = app.execute_transition_request(&req);
assert!(result.is_err());
- assert!(result.unwrap_err().to_string().contains("Review to move to Done"));
+ assert!(result
+ .unwrap_err()
+ .to_string()
+ .contains("Review to move to Done"));
}
#[test]
@@ -5296,7 +5802,8 @@ fn test_execute_transition_request_resume_moves_review_to_running() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("Resume me", "claude", "test-project");
@@ -5308,7 +5815,14 @@ fn test_execute_transition_request_resume_moves_review_to_running() {
let req = crate::db::TransitionRequest::new("t1", "resume");
app.execute_transition_request(&req).unwrap();
- let updated = app.state.db.as_ref().unwrap().get_task("t1").unwrap().unwrap();
+ let updated = app
+ .state
+ .db
+ .as_ref()
+ .unwrap()
+ .get_task("t1")
+ .unwrap()
+ .unwrap();
assert_eq!(updated.status, TaskStatus::Running);
}
@@ -5327,7 +5841,8 @@ fn test_execute_transition_request_move_to_done_calls_force_move() {
Arc::new(mock_git),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("Done task", "claude", "test-project");
@@ -5339,7 +5854,14 @@ fn test_execute_transition_request_move_to_done_calls_force_move() {
let req = crate::db::TransitionRequest::new("t1", "move_to_done");
app.execute_transition_request(&req).unwrap();
- let updated = app.state.db.as_ref().unwrap().get_task("t1").unwrap().unwrap();
+ let updated = app
+ .state
+ .db
+ .as_ref()
+ .unwrap()
+ .get_task("t1")
+ .unwrap()
+ .unwrap();
assert_eq!(updated.status, TaskStatus::Done);
}
@@ -5358,7 +5880,8 @@ fn test_process_transition_requests_marks_processed() {
Arc::new(mock_git),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
{
let db = app.state.db.as_ref().unwrap();
@@ -5379,7 +5902,16 @@ fn test_process_transition_requests_marks_processed() {
app.process_transition_requests().unwrap();
// Should have 0 pending (request was processed)
- assert_eq!(app.state.db.as_ref().unwrap().get_pending_transition_requests().unwrap().len(), 0);
+ assert_eq!(
+ app.state
+ .db
+ .as_ref()
+ .unwrap()
+ .get_pending_transition_requests()
+ .unwrap()
+ .len(),
+ 0
+ );
}
// =============================================================================
@@ -5440,7 +5972,10 @@ fn test_parse_ansi_bold() {
let lines = parse_ansi_to_lines(input);
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].spans[0].content, "bold text");
- assert!(lines[0].spans[0].style.add_modifier.contains(ratatui::style::Modifier::BOLD));
+ assert!(lines[0].spans[0]
+ .style
+ .add_modifier
+ .contains(ratatui::style::Modifier::BOLD));
}
#[test]
@@ -5456,7 +5991,12 @@ fn test_parse_ansi_foreground_colors() {
];
for (input, expected_color) in cases {
let lines = parse_ansi_to_lines(input);
- assert_eq!(lines[0].spans[0].style.fg, Some(*expected_color), "input: {:?}", input);
+ assert_eq!(
+ lines[0].spans[0].style.fg,
+ Some(*expected_color),
+ "input: {:?}",
+ input
+ );
}
}
@@ -5518,8 +6058,12 @@ fn test_parse_sgr_rgb_bg() {
fn test_parse_sgr_dim_italic_underline() {
let style = parse_sgr("2;3;4", ratatui::style::Style::default());
assert!(style.add_modifier.contains(ratatui::style::Modifier::DIM));
- assert!(style.add_modifier.contains(ratatui::style::Modifier::ITALIC));
- assert!(style.add_modifier.contains(ratatui::style::Modifier::UNDERLINED));
+ assert!(style
+ .add_modifier
+ .contains(ratatui::style::Modifier::ITALIC));
+ assert!(style
+ .add_modifier
+ .contains(ratatui::style::Modifier::UNDERLINED));
}
#[test]
@@ -5554,9 +6098,15 @@ fn test_parse_ansi_mixed_text_and_colors() {
/// Build a test App with a task already in the DB and board, plus configurable mocks.
#[cfg(feature = "test-mocks")]
-fn make_app_with_task(task: &Task, mock_tmux: MockTmuxOperations, mock_git: MockGitOperations) -> App {
+fn make_app_with_task(
+ task: &Task,
+ mock_tmux: MockTmuxOperations,
+ mock_git: MockGitOperations,
+) -> App {
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -5564,7 +6114,8 @@ fn make_app_with_task(task: &Task, mock_tmux: MockTmuxOperations, mock_git: Mock
Arc::new(mock_git),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
app.state.db.as_ref().unwrap().create_task(task).unwrap();
app.refresh_tasks().unwrap();
@@ -5780,7 +6331,9 @@ fn test_toggle_orchestrator_warns_in_dashboard_mode() {
mock_tmux.expect_has_session().returning(|_| false);
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
None, // dashboard mode β€” no project path
@@ -5788,7 +6341,8 @@ fn test_toggle_orchestrator_warns_in_dashboard_mode() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
app.toggle_orchestrator().unwrap();
@@ -5804,15 +6358,20 @@ fn test_toggle_orchestrator_spawns_new_session() {
mock_tmux.expect_window_exists().returning(|_| Ok(false));
mock_tmux.expect_has_session().returning(|_| false);
mock_tmux.expect_create_session().returning(|_, _| Ok(()));
- mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+ mock_tmux
+ .expect_create_window()
+ .returning(|_, _, _, _| Ok(()));
mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));
- mock_tmux.expect_capture_pane_with_history().returning(|_, _| vec![]);
+ mock_tmux
+ .expect_capture_pane_with_history()
+ .returning(|_, _| vec![]);
mock_tmux.expect_get_cursor_info().returning(|_| None);
let mut mock_registry = MockAgentRegistry::new();
mock_registry.expect_get().returning(|_| {
let mut ops = MockAgentOperations::new();
- ops.expect_build_orchestrator_command().returning(|_, _| "claude".to_string());
+ ops.expect_build_orchestrator_command()
+ .returning(|_, _| "claude".to_string());
Arc::new(ops)
});
@@ -5822,7 +6381,8 @@ fn test_toggle_orchestrator_spawns_new_session() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
app.toggle_orchestrator().unwrap();
@@ -5839,11 +6399,15 @@ fn test_toggle_orchestrator_opens_popup_when_already_running() {
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_window_exists().returning(|_| Ok(true));
mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));
- mock_tmux.expect_capture_pane_with_history().returning(|_, _| vec![]);
+ mock_tmux
+ .expect_capture_pane_with_history()
+ .returning(|_, _| vec![]);
mock_tmux.expect_get_cursor_info().returning(|_| None);
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -5851,7 +6415,8 @@ fn test_toggle_orchestrator_opens_popup_when_already_running() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
// Simulate already-running orchestrator
app.state.orchestrator_session = Some("test-project:orchestrator".to_string());
@@ -5877,15 +6442,20 @@ fn test_toggle_orchestrator_clears_stale_session_and_respawns() {
mock_tmux.expect_window_exists().returning(|_| Ok(false));
mock_tmux.expect_has_session().returning(|_| false);
mock_tmux.expect_create_session().returning(|_, _| Ok(()));
- mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+ mock_tmux
+ .expect_create_window()
+ .returning(|_, _, _, _| Ok(()));
mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));
- mock_tmux.expect_capture_pane_with_history().returning(|_, _| vec![]);
+ mock_tmux
+ .expect_capture_pane_with_history()
+ .returning(|_, _| vec![]);
mock_tmux.expect_get_cursor_info().returning(|_| None);
let mut mock_registry = MockAgentRegistry::new();
mock_registry.expect_get().returning(|_| {
let mut ops = MockAgentOperations::new();
- ops.expect_build_orchestrator_command().returning(|_, _| "claude".to_string());
+ ops.expect_build_orchestrator_command()
+ .returning(|_, _| "claude".to_string());
Arc::new(ops)
});
@@ -5895,7 +6465,8 @@ fn test_toggle_orchestrator_clears_stale_session_and_respawns() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
// Stale session β€” window no longer exists
app.state.orchestrator_session = Some("test-project:orchestrator".to_string());
@@ -5918,10 +6489,14 @@ fn test_deliver_orchestrator_notifications_throttled() {
let mut mock_tmux = MockTmuxOperations::new();
// send_keys must NOT be called β€” any call would panic with mockall
mock_tmux.expect_window_exists().returning(|_| Ok(true));
- mock_tmux.expect_capture_pane().returning(|_| Ok("[agtx:idle]".to_string()));
+ mock_tmux
+ .expect_capture_pane()
+ .returning(|_| Ok("[agtx:idle]".to_string()));
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -5929,7 +6504,8 @@ fn test_deliver_orchestrator_notifications_throttled() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
app.state.orchestrator_session = Some("proj:orchestrator".to_string());
app.state.orchestrator_ready.store(true, Ordering::Release);
@@ -5949,7 +6525,9 @@ fn test_deliver_orchestrator_notifications_returns_early_no_session() {
// window_exists must NOT be called
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -5957,7 +6535,8 @@ fn test_deliver_orchestrator_notifications_returns_early_no_session() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
// Expire the throttle
app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
@@ -5976,7 +6555,9 @@ fn test_deliver_orchestrator_notifications_returns_early_not_ready() {
// window_exists must NOT be called
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -5984,7 +6565,8 @@ fn test_deliver_orchestrator_notifications_returns_early_not_ready() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
app.state.orchestrator_session = Some("proj:orchestrator".to_string());
@@ -6000,11 +6582,15 @@ fn test_deliver_orchestrator_notifications_busy_when_content_changed() {
// Content changed, no idle signal β†’ state updated to Busy (stable_since set), nothing sent
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_window_exists().returning(|_| Ok(true));
- mock_tmux.expect_capture_pane().returning(|_| Ok("new content here".to_string()));
+ mock_tmux
+ .expect_capture_pane()
+ .returning(|_| Ok("new content here".to_string()));
// send_keys must NOT be called
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -6012,7 +6598,8 @@ fn test_deliver_orchestrator_notifications_busy_when_content_changed() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
app.state.orchestrator_session = Some("proj:orchestrator".to_string());
@@ -6031,14 +6618,19 @@ fn test_deliver_orchestrator_notifications_delivers_when_idle_signal() {
// Content changed AND has [agtx:idle] β†’ sends combined notification
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_window_exists().returning(|_| Ok(true));
- mock_tmux.expect_capture_pane().returning(|_| Ok("stuff [agtx:idle]".to_string()));
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_capture_pane()
+ .returning(|_| Ok("stuff [agtx:idle]".to_string()));
+ mock_tmux
+ .expect_send_keys()
.withf(|_target, msg| msg.starts_with("[agtx]"))
.times(1)
.returning(|_, _| Ok(()));
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -6046,7 +6638,8 @@ fn test_deliver_orchestrator_notifications_delivers_when_idle_signal() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
app.state.orchestrator_session = Some("proj:orchestrator".to_string());
@@ -6056,7 +6649,8 @@ fn test_deliver_orchestrator_notifications_delivers_when_idle_signal() {
// Insert a notification into the DB
{
let db = app.state.db.as_ref().unwrap();
- db.create_notification(&crate::db::Notification::new("task X completed planning")).unwrap();
+ db.create_notification(&crate::db::Notification::new("task X completed planning"))
+ .unwrap();
}
app.deliver_orchestrator_notifications();
@@ -6075,14 +6669,19 @@ fn test_deliver_orchestrator_notifications_delivers_via_stability_fallback() {
// Content unchanged, timer β‰₯15s β†’ Idle via fallback, delivers notification
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_window_exists().returning(|_| Ok(true));
- mock_tmux.expect_capture_pane().returning(|_| Ok("same content".to_string()));
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_capture_pane()
+ .returning(|_| Ok("same content".to_string()));
+ mock_tmux
+ .expect_send_keys()
.withf(|_target, msg| msg.starts_with("[agtx]"))
.times(1)
.returning(|_, _| Ok(()));
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -6090,7 +6689,8 @@ fn test_deliver_orchestrator_notifications_delivers_via_stability_fallback() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
app.state.orchestrator_session = Some("proj:orchestrator".to_string());
@@ -6102,7 +6702,8 @@ fn test_deliver_orchestrator_notifications_delivers_via_stability_fallback() {
{
let db = app.state.db.as_ref().unwrap();
- db.create_notification(&crate::db::Notification::new("task Y completed running")).unwrap();
+ db.create_notification(&crate::db::Notification::new("task Y completed running"))
+ .unwrap();
}
app.deliver_orchestrator_notifications();
@@ -6117,11 +6718,15 @@ fn test_deliver_orchestrator_notifications_noop_when_no_notifications() {
// Idle orchestrator but DB has no notifications β†’ send_keys NOT called
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_window_exists().returning(|_| Ok(true));
- mock_tmux.expect_capture_pane().returning(|_| Ok("stuff [agtx:idle]".to_string()));
+ mock_tmux
+ .expect_capture_pane()
+ .returning(|_| Ok("stuff [agtx:idle]".to_string()));
// send_keys must NOT be called β€” mockall will panic if it is
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get().returning(|_| Arc::new(MockAgentOperations::new()));
+ mock_registry
+ .expect_get()
+ .returning(|_| Arc::new(MockAgentOperations::new()));
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -6129,7 +6734,8 @@ fn test_deliver_orchestrator_notifications_noop_when_no_notifications() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(mock_registry),
- ).unwrap();
+ )
+ .unwrap();
app.state.orchestrator_last_check = Instant::now() - std::time::Duration::from_secs(10);
app.state.orchestrator_session = Some("proj:orchestrator".to_string());
@@ -6157,7 +6763,8 @@ fn test_stuck_task_notification_fires_after_1_min_idle() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("stuck task", "claude", "test-project");
@@ -6174,12 +6781,20 @@ fn test_stuck_task_notification_fires_after_1_min_idle() {
);
let result = SessionRefreshResult {
- statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Idle, false)],
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Running,
+ PhaseStatus::Idle,
+ false,
+ )],
};
app.apply_session_refresh(result);
let notifs = app.state.db.as_ref().unwrap().peek_notifications().unwrap();
- assert!(!notifs.is_empty(), "should have created a stuck-task notification");
+ assert!(
+ !notifs.is_empty(),
+ "should have created a stuck-task notification"
+ );
assert!(notifs[0].message.contains("stuck task"));
assert!(notifs[0].message.contains("running"));
assert!(notifs[0].message.contains("idle"));
@@ -6197,7 +6812,8 @@ fn test_stuck_task_notification_does_not_fire_before_1_min() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("pending task", "claude", "test-project");
@@ -6213,12 +6829,20 @@ fn test_stuck_task_notification_does_not_fire_before_1_min() {
);
let result = SessionRefreshResult {
- statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Idle, false)],
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Running,
+ PhaseStatus::Idle,
+ false,
+ )],
};
app.apply_session_refresh(result);
let notifs = app.state.db.as_ref().unwrap().peek_notifications().unwrap();
- assert!(notifs.is_empty(), "should not have fired notification before 1 minute");
+ assert!(
+ notifs.is_empty(),
+ "should not have fired notification before 1 minute"
+ );
}
#[test]
@@ -6233,7 +6857,8 @@ fn test_stuck_task_notification_fires_once_per_phase() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("my task", "claude", "test-project");
@@ -6249,7 +6874,12 @@ fn test_stuck_task_notification_fires_once_per_phase() {
);
let make_result = || SessionRefreshResult {
- statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Idle, false)],
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Running,
+ PhaseStatus::Idle,
+ false,
+ )],
};
app.apply_session_refresh(make_result());
@@ -6272,7 +6902,8 @@ fn test_stuck_task_notification_not_fired_without_orchestrator() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("my task", "claude", "test-project");
@@ -6289,7 +6920,12 @@ fn test_stuck_task_notification_not_fired_without_orchestrator() {
);
let result = SessionRefreshResult {
- statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Idle, false)],
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Running,
+ PhaseStatus::Idle,
+ false,
+ )],
};
app.apply_session_refresh(result);
@@ -6309,7 +6945,8 @@ fn test_stuck_task_idle_since_cleared_when_not_idle() {
Arc::new(MockGitOperations::new()),
Arc::new(MockGitProviderOperations::new()),
Arc::new(MockAgentRegistry::new()),
- ).unwrap();
+ )
+ .unwrap();
let db = app.state.db.as_ref().unwrap();
let mut task = Task::new("my task", "claude", "test-project");
@@ -6326,7 +6963,12 @@ fn test_stuck_task_idle_since_cleared_when_not_idle() {
// Task is now Working (no longer Idle)
let result = SessionRefreshResult {
- statuses: vec![make_session_task_status("t1", TaskStatus::Running, PhaseStatus::Working, false)],
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Running,
+ PhaseStatus::Working,
+ false,
+ )],
};
app.apply_session_refresh(result);
@@ -6336,7 +6978,6 @@ fn test_stuck_task_idle_since_cleared_when_not_idle() {
);
}
-
// =============================================================================
// Tests for pure functions: fuzzy_score, word_boundary_left/right,
// generate_task_slug, centered_rect, centered_rect_fixed_width,
@@ -6426,7 +7067,11 @@ fn test_word_boundary_right_empty_string() {
fn test_generate_task_slug_basic() {
let slug = generate_task_slug("abcdefgh-1234-5678", "My Task");
assert!(slug.starts_with("abcdefgh-"), "slug={}", slug);
- assert!(slug.contains("My-Task") || slug.contains("my-task") || slug.contains("My"), "slug={}", slug);
+ assert!(
+ slug.contains("My-Task") || slug.contains("my-task") || slug.contains("My"),
+ "slug={}",
+ slug
+ );
}
#[test]
@@ -6435,7 +7080,11 @@ fn test_generate_task_slug_truncates_long_title() {
let slug = generate_task_slug("id12345678", &long_title);
// slug part should be <= 30 chars for the title portion
let after_prefix = slug.trim_start_matches("id123456-");
- assert!(after_prefix.len() <= 30, "slug title part too long: {}", after_prefix);
+ assert!(
+ after_prefix.len() <= 30,
+ "slug title part too long: {}",
+ after_prefix
+ );
}
#[test]
@@ -6460,7 +7109,12 @@ fn test_generate_task_slug_id_prefix_is_8_chars() {
#[test]
fn test_centered_rect_basic() {
use ratatui::layout::Rect;
- let area = Rect { x: 0, y: 0, width: 100, height: 50 };
+ let area = Rect {
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 50,
+ };
let popup = centered_rect(60, 40, area);
// x should be centered
assert_eq!(popup.x, 20); // (100 - 60) / 2
@@ -6471,7 +7125,12 @@ fn test_centered_rect_basic() {
#[test]
fn test_centered_rect_full_size() {
use ratatui::layout::Rect;
- let area = Rect { x: 0, y: 0, width: 80, height: 24 };
+ let area = Rect {
+ x: 0,
+ y: 0,
+ width: 80,
+ height: 24,
+ };
let popup = centered_rect(100, 100, area);
assert_eq!(popup.width, 80);
assert_eq!(popup.height, 24);
@@ -6482,7 +7141,12 @@ fn test_centered_rect_full_size() {
#[test]
fn test_centered_rect_fixed_width_basic() {
use ratatui::layout::Rect;
- let area = Rect { x: 0, y: 0, width: 100, height: 50 };
+ let area = Rect {
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 50,
+ };
let popup = centered_rect_fixed_width(60, 50, area);
assert_eq!(popup.width, 60);
// should be centered horizontally
@@ -6493,7 +7157,12 @@ fn test_centered_rect_fixed_width_basic() {
fn test_centered_rect_fixed_width_capped_to_terminal() {
use ratatui::layout::Rect;
// fixed_width wider than terminal β†’ capped at width - 4
- let area = Rect { x: 0, y: 0, width: 40, height: 24 };
+ let area = Rect {
+ x: 0,
+ y: 0,
+ width: 40,
+ height: 24,
+ };
let popup = centered_rect_fixed_width(100, 50, area);
assert_eq!(popup.width, 36); // 40 - 4
}
@@ -6532,7 +7201,11 @@ fn test_transform_skill_for_opencode_strips_frontmatter() {
let result = transform_skill_for_opencode(content);
// Should produce OpenCode format: description frontmatter + body
assert!(result.contains("description:"), "result={}", result);
- assert!(result.contains("Do the planning work."), "result={}", result);
+ assert!(
+ result.contains("Do the planning work."),
+ "result={}",
+ result
+ );
// Original name: field should not appear
assert!(!result.contains("name: agtx-plan"), "result={}", result);
}
@@ -6556,7 +7229,8 @@ fn test_transform_skill_for_opencode_uses_description_from_frontmatter() {
#[cfg(feature = "test-mocks")]
fn test_is_pane_at_shell_returns_true_for_shell_command() {
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
assert!(is_pane_at_shell(&mock_tmux, "proj:task"));
}
@@ -6565,8 +7239,7 @@ fn test_is_pane_at_shell_returns_true_for_shell_command() {
#[cfg(feature = "test-mocks")]
fn test_is_pane_at_shell_returns_false_when_no_command() {
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
- .returning(|_| None);
+ mock_tmux.expect_pane_current_command().returning(|_| None);
assert!(!is_pane_at_shell(&mock_tmux, "proj:task"));
}
@@ -6576,7 +7249,8 @@ fn test_is_pane_at_shell_returns_false_when_no_command() {
#[cfg(feature = "test-mocks")]
fn test_is_agent_active_true_when_agent_process_running() {
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("claude".to_string()));
assert!(is_agent_active(&mock_tmux, "proj:task"));
}
@@ -6586,9 +7260,11 @@ fn test_is_agent_active_true_when_agent_process_running() {
fn test_is_agent_active_true_when_gemini_indicator_in_pane() {
// Gemini runs inside bash β€” detected via pane content indicator
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
- mock_tmux.expect_capture_pane()
+ mock_tmux
+ .expect_capture_pane()
.returning(|_| Ok("some output\nType your message\n".to_string()));
assert!(is_agent_active(&mock_tmux, "proj:task"));
}
@@ -6597,9 +7273,11 @@ fn test_is_agent_active_true_when_gemini_indicator_in_pane() {
#[cfg(feature = "test-mocks")]
fn test_is_agent_active_false_when_at_shell_no_indicator() {
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
- mock_tmux.expect_capture_pane()
+ mock_tmux
+ .expect_capture_pane()
.returning(|_| Ok("$ ".to_string()));
assert!(!is_agent_active(&mock_tmux, "proj:task"));
}
@@ -6610,9 +7288,13 @@ fn test_is_agent_active_false_when_at_shell_no_indicator() {
#[cfg(feature = "test-mocks")]
fn test_collect_task_diff_shows_unstaged_changes() {
let mut mock_git = MockGitOperations::new();
- mock_git.expect_diff().returning(|_| "diff --git a/foo.rs\n-old\n+new\n".to_string());
+ mock_git
+ .expect_diff()
+ .returning(|_| "diff --git a/foo.rs\n-old\n+new\n".to_string());
mock_git.expect_diff_cached().returning(|_| String::new());
- mock_git.expect_list_untracked_files().returning(|_| String::new());
+ mock_git
+ .expect_list_untracked_files()
+ .returning(|_| String::new());
let result = collect_task_diff("/tmp/wt", &mock_git, &[]);
assert!(result.contains("Unstaged Changes"), "result={}", result);
@@ -6624,8 +7306,12 @@ fn test_collect_task_diff_shows_unstaged_changes() {
fn test_collect_task_diff_shows_staged_changes() {
let mut mock_git = MockGitOperations::new();
mock_git.expect_diff().returning(|_| String::new());
- mock_git.expect_diff_cached().returning(|_| "diff --git a/bar.rs\n+added\n".to_string());
- mock_git.expect_list_untracked_files().returning(|_| String::new());
+ mock_git
+ .expect_diff_cached()
+ .returning(|_| "diff --git a/bar.rs\n+added\n".to_string());
+ mock_git
+ .expect_list_untracked_files()
+ .returning(|_| String::new());
let result = collect_task_diff("/tmp/wt", &mock_git, &[]);
assert!(result.contains("Staged Changes"), "result={}", result);
@@ -6637,16 +7323,26 @@ fn test_collect_task_diff_untracked_excluded_by_prefix() {
let mut mock_git = MockGitOperations::new();
mock_git.expect_diff().returning(|_| String::new());
mock_git.expect_diff_cached().returning(|_| String::new());
- mock_git.expect_list_untracked_files()
+ mock_git
+ .expect_list_untracked_files()
.returning(|_| ".claude/settings.json\nsrc/new_file.rs\n".to_string());
// diff_untracked_file only called for non-excluded files
- mock_git.expect_diff_untracked_file()
+ mock_git
+ .expect_diff_untracked_file()
.withf(|_, file: &str| file == "src/new_file.rs")
.returning(|_, _| "+new content\n".to_string());
let result = collect_task_diff("/tmp/wt", &mock_git, &[".claude"]);
- assert!(!result.contains("settings.json"), "excluded file appeared: {}", result);
- assert!(result.contains("new_file.rs") || result.contains("Untracked"), "result={}", result);
+ assert!(
+ !result.contains("settings.json"),
+ "excluded file appeared: {}",
+ result
+ );
+ assert!(
+ result.contains("new_file.rs") || result.contains("Untracked"),
+ "result={}",
+ result
+ );
}
// --- cleanup_task_for_done ---
@@ -6655,13 +7351,15 @@ fn test_collect_task_diff_untracked_excluded_by_prefix() {
#[cfg(feature = "test-mocks")]
fn test_cleanup_task_for_done_clears_session_and_worktree() {
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_kill_window()
+ mock_tmux
+ .expect_kill_window()
.withf(|name: &str| name == "proj:task-1")
.times(1)
.returning(|_| Ok(()));
let mut mock_git = MockGitOperations::new();
- mock_git.expect_remove_worktree()
+ mock_git
+ .expect_remove_worktree()
.times(1)
.returning(|_, _| Ok(()));
@@ -6718,7 +7416,12 @@ fn test_cleanup_task_for_done_archives_md_files() {
cleanup_task_for_done(&mut task, project_dir.path(), &mock_tmux, &mock_git);
// Archived file should exist under .agtx/archive/my-slug/plan.md
- let archive = project_dir.path().join(".agtx").join("archive").join("my-slug").join("plan.md");
+ let archive = project_dir
+ .path()
+ .join(".agtx")
+ .join("archive")
+ .join("my-slug")
+ .join("plan.md");
assert!(archive.exists(), "archive not created at {:?}", archive);
}
@@ -6728,12 +7431,14 @@ fn test_cleanup_task_for_done_archives_md_files() {
#[cfg(feature = "test-mocks")]
fn test_cleanup_task_resources_kills_window_and_removes_worktree() {
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_kill_window()
+ mock_tmux
+ .expect_kill_window()
.times(1)
.returning(|_| Ok(()));
let mut mock_git = MockGitOperations::new();
- mock_git.expect_remove_worktree()
+ mock_git
+ .expect_remove_worktree()
.times(1)
.returning(|_, _| Ok(()));
@@ -6772,15 +7477,18 @@ fn test_cleanup_task_resources_noop_when_no_session_or_worktree() {
#[cfg(feature = "test-mocks")]
fn test_delete_task_resources_kills_window_removes_worktree_and_deletes_branch() {
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_kill_window()
+ mock_tmux
+ .expect_kill_window()
.times(1)
.returning(|_| Ok(()));
let mut mock_git = MockGitOperations::new();
- mock_git.expect_remove_worktree()
+ mock_git
+ .expect_remove_worktree()
.times(1)
.returning(|_, _| Ok(()));
- mock_git.expect_delete_branch()
+ mock_git
+ .expect_delete_branch()
.times(1)
.returning(|_, _| Ok(()));
@@ -6814,14 +7522,12 @@ fn test_save_task_creates_new_task_in_db() {
app.state.pending_task_title = "New Task Title".to_string();
app.state.input_buffer = "Task description here".to_string();
app.state.editing_task_id = None;
- app.state.wizard_plugin_options = vec![
- crate::tui::app::PluginOption {
- name: "agtx".to_string(),
- label: "agtx".to_string(),
- description: "".to_string(),
- active: true,
- }
- ];
+ app.state.wizard_plugin_options = vec![crate::tui::app::PluginOption {
+ name: "agtx".to_string(),
+ label: "agtx".to_string(),
+ description: "".to_string(),
+ active: true,
+ }];
app.state.wizard_selected_plugin = 0;
app.save_task().unwrap();
@@ -6842,26 +7548,36 @@ fn test_save_task_updates_existing_task() {
// Create a task in the DB first
let original = make_test_task("edit-me", "Original Title", TaskStatus::Backlog);
- app.state.db.as_ref().unwrap().create_task(&original).unwrap();
+ app.state
+ .db
+ .as_ref()
+ .unwrap()
+ .create_task(&original)
+ .unwrap();
app.refresh_tasks().unwrap();
// Set up wizard state for editing
app.state.pending_task_title = "Updated Title".to_string();
app.state.input_buffer = "Updated description".to_string();
app.state.editing_task_id = Some("edit-me".to_string());
- app.state.wizard_plugin_options = vec![
- crate::tui::app::PluginOption {
- name: "gsd".to_string(),
- label: "gsd".to_string(),
- description: "".to_string(),
- active: true,
- }
- ];
+ app.state.wizard_plugin_options = vec![crate::tui::app::PluginOption {
+ name: "gsd".to_string(),
+ label: "gsd".to_string(),
+ description: "".to_string(),
+ active: true,
+ }];
app.state.wizard_selected_plugin = 0;
app.save_task().unwrap();
- let updated = app.state.db.as_ref().unwrap().get_task("edit-me").unwrap().unwrap();
+ let updated = app
+ .state
+ .db
+ .as_ref()
+ .unwrap()
+ .get_task("edit-me")
+ .unwrap()
+ .unwrap();
assert_eq!(updated.title, "Updated Title");
assert_eq!(updated.description.as_deref(), Some("Updated description"));
assert_eq!(updated.plugin.as_deref(), Some("gsd"));
@@ -6877,14 +7593,12 @@ fn test_save_task_empty_description_stored_as_none() {
app.state.pending_task_title = "Title only".to_string();
app.state.input_buffer = String::new(); // empty
app.state.editing_task_id = None;
- app.state.wizard_plugin_options = vec![
- crate::tui::app::PluginOption {
- name: "agtx".to_string(),
- label: "agtx".to_string(),
- description: "".to_string(),
- active: true,
- }
- ];
+ app.state.wizard_plugin_options = vec![crate::tui::app::PluginOption {
+ name: "agtx".to_string(),
+ label: "agtx".to_string(),
+ description: "".to_string(),
+ active: true,
+ }];
app.state.wizard_selected_plugin = 0;
app.save_task().unwrap();
@@ -6900,7 +7614,12 @@ fn test_save_task_empty_description_stored_as_none() {
fn test_init_plugin_selection_includes_agtx() {
let mut app = make_test_app();
app.init_plugin_selection();
- let names: Vec<&str> = app.state.wizard_plugin_options.iter().map(|o| o.name.as_str()).collect();
+ let names: Vec<&str> = app
+ .state
+ .wizard_plugin_options
+ .iter()
+ .map(|o| o.name.as_str())
+ .collect();
assert!(names.contains(&"agtx"), "options={:?}", names);
}
@@ -6924,7 +7643,11 @@ fn test_init_plugin_selection_selected_index_matches_active() {
app.init_plugin_selection();
let idx = app.state.wizard_selected_plugin;
- assert!(app.state.wizard_plugin_options[idx].active, "selected idx {} not active", idx);
+ assert!(
+ app.state.wizard_plugin_options[idx].active,
+ "selected idx {} not active",
+ idx
+ );
}
// =============================================================================
@@ -6939,20 +7662,28 @@ fn test_switch_agent_claude_sends_exit_then_new_cmd() {
// Claude: sends /exit, shell found immediately, then sends new agent cmd
let mut mock_tmux = MockTmuxOperations::new();
// /exit sent to current agent
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "/exit")
.times(1)
.returning(|_, _| Ok(()));
// pane_current_command returns "bash" on first poll β†’ shell found
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
// new agent command sent after shell found
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "claude --dangerously-skip-permissions")
.times(1)
.returning(|_, _| Ok(()));
- switch_agent_in_tmux(&mock_tmux, "proj:task", "claude", "claude --dangerously-skip-permissions");
+ switch_agent_in_tmux(
+ &mock_tmux,
+ "proj:task",
+ "claude",
+ "claude --dangerously-skip-permissions",
+ );
}
#[test]
@@ -6961,13 +7692,16 @@ fn test_switch_agent_codex_sends_ctrl_c_not_exit() {
// Codex has no exit command β€” sends C-c instead
let mut mock_tmux = MockTmuxOperations::new();
// C-c via send_keys_literal (not send_keys)
- mock_tmux.expect_send_keys_literal()
+ mock_tmux
+ .expect_send_keys_literal()
.withf(|_, key: &str| key == "C-c")
.times(1)
.returning(|_, _| Ok(()));
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "codex --full-auto")
.times(1)
.returning(|_, _| Ok(()));
@@ -6984,24 +7718,30 @@ fn test_switch_agent_retries_with_ctrl_c_when_shell_not_found() {
let mut mock_tmux = MockTmuxOperations::new();
// Initial /exit
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "/exit")
.returning(|_, _| Ok(()));
// pane_current_command: returns "claude" for first 30 polls (shell not found),
// then "bash" for the retry polls
- mock_tmux.expect_pane_current_command()
- .returning(move |_| {
- let mut n = seq2.lock().unwrap();
- *n += 1;
- if *n <= 30 { Some("claude".to_string()) } else { Some("bash".to_string()) }
- });
+ mock_tmux.expect_pane_current_command().returning(move |_| {
+ let mut n = seq2.lock().unwrap();
+ *n += 1;
+ if *n <= 30 {
+ Some("claude".to_string())
+ } else {
+ Some("bash".to_string())
+ }
+ });
// C-c sent on retry
- mock_tmux.expect_send_keys_literal()
+ mock_tmux
+ .expect_send_keys_literal()
.withf(|_, key: &str| key == "C-c")
.times(1)
.returning(|_, _| Ok(()));
// new agent cmd always sent at end
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "newagent")
.times(1)
.returning(|_, _| Ok(()));
@@ -7014,24 +7754,29 @@ fn test_switch_agent_retries_with_ctrl_c_when_shell_not_found() {
fn test_switch_agent_sends_ctrl_d_as_last_resort() {
// Shell never found β†’ C-d last resort, but new agent cmd still sent
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "/exit")
.returning(|_, _| Ok(()));
// Always returns agent process β€” shell never found
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("claude".to_string()));
// C-c on retry
- mock_tmux.expect_send_keys_literal()
+ mock_tmux
+ .expect_send_keys_literal()
.withf(|_, key: &str| key == "C-c")
.times(1)
.returning(|_, _| Ok(()));
// C-d as last resort
- mock_tmux.expect_send_keys_literal()
+ mock_tmux
+ .expect_send_keys_literal()
.withf(|_, key: &str| key == "C-d")
.times(1)
.returning(|_, _| Ok(()));
// new agent still sent
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "newagent")
.times(1)
.returning(|_, _| Ok(()));
@@ -7044,15 +7789,19 @@ fn test_switch_agent_sends_ctrl_d_as_last_resort() {
fn test_switch_agent_always_sends_new_agent_cmd() {
// Even in worst case (shell never found), new agent cmd is sent
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "/exit")
.returning(|_, _| Ok(()));
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("claude".to_string()));
- mock_tmux.expect_send_keys_literal()
+ mock_tmux
+ .expect_send_keys_literal()
.returning(|_, _| Ok(()));
// This is the key assertion β€” new_agent_cmd must be sent exactly once
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "my-new-agent")
.times(1)
.returning(|_, _| Ok(()));
@@ -7067,13 +7816,18 @@ fn test_switch_agent_always_sends_new_agent_cmd() {
fn test_wait_for_agent_ready_returns_when_process_detected() {
// pane_current_command returns agent process immediately β†’ exits loop on first check
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("claude".to_string())); // not shell β†’ agent detected
- // capture_pane called for settle, returning no indicator content
- mock_tmux.expect_capture_pane()
+ // capture_pane called for settle, returning no indicator content
+ mock_tmux
+ .expect_capture_pane()
.returning(|_| Ok(String::new()));
- let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ let result = wait_for_agent_ready(
+ &(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
+ "proj:task",
+ );
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -7082,12 +7836,17 @@ fn test_wait_for_agent_ready_returns_when_process_detected() {
fn test_wait_for_agent_ready_returns_when_ready_indicator_in_pane() {
// pane_current_command returns shell (bash), but pane content has ready indicator
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string())); // at shell
- mock_tmux.expect_capture_pane()
+ mock_tmux
+ .expect_capture_pane()
.returning(|_| Ok("Type your message\n> ".to_string())); // Gemini ready indicator
- let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ let result = wait_for_agent_ready(
+ &(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
+ "proj:task",
+ );
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -7096,22 +7855,29 @@ fn test_wait_for_agent_ready_returns_when_ready_indicator_in_pane() {
fn test_wait_for_agent_ready_handles_claude_bypass_prompt() {
// Pane contains "Yes, I accept" β†’ sends "2" + Enter and returns immediately
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
- mock_tmux.expect_capture_pane()
+ mock_tmux
+ .expect_capture_pane()
.returning(|_| Ok("Yes, I accept\nSome prompt text".to_string()));
// Must send "2" to accept
- mock_tmux.expect_send_keys_literal()
+ mock_tmux
+ .expect_send_keys_literal()
.withf(|_, key: &str| key == "2")
.times(1)
.returning(|_, _| Ok(()));
// Must send Enter to confirm
- mock_tmux.expect_send_keys_literal()
+ mock_tmux
+ .expect_send_keys_literal()
.withf(|_, key: &str| key == "Enter")
.times(1)
.returning(|_, _| Ok(()));
- let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ let result = wait_for_agent_ready(
+ &(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
+ "proj:task",
+ );
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -7123,23 +7889,26 @@ fn test_wait_for_agent_ready_returns_when_content_stabilizes() {
let call_count2 = call_count.clone();
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string())); // always at shell
- mock_tmux.expect_capture_pane()
- .returning(move |_| {
- let mut n = call_count2.lock().unwrap();
- *n += 1;
- // 3 changes (different content), then stable
- match *n {
- 1 => Ok("loading 1".to_string()),
- 2 => Ok("loading 2".to_string()),
- 3 => Ok("loading 3".to_string()),
- _ => Ok("stable content".to_string()), // unchanged β†’ stable_ticks increment
- }
- });
+ mock_tmux.expect_capture_pane().returning(move |_| {
+ let mut n = call_count2.lock().unwrap();
+ *n += 1;
+ // 3 changes (different content), then stable
+ match *n {
+ 1 => Ok("loading 1".to_string()),
+ 2 => Ok("loading 2".to_string()),
+ 3 => Ok("loading 3".to_string()),
+ _ => Ok("stable content".to_string()), // unchanged β†’ stable_ticks increment
+ }
+ });
- let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ let result = wait_for_agent_ready(
+ &(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
+ "proj:task",
+ );
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -7152,14 +7921,19 @@ fn test_wait_for_agent_ready_always_returns_some() {
// We only run a minimal version: content changes 0 times β†’ loop exits at 150
// With mocks this is instant.
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
- mock_tmux.expect_capture_pane()
+ mock_tmux
+ .expect_capture_pane()
.returning(|_| Ok("same content forever".to_string()));
// Loop runs all 150 iters with no content change β†’ change_count=0, stable never triggered
// Function always returns Some at end regardless.
- let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>), "proj:task");
+ let result = wait_for_agent_ready(
+ &(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
+ "proj:task",
+ );
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -7175,7 +7949,11 @@ fn test_is_pane_at_shell_returns_true_for_shell_process() {
let shell_str = shell.to_string();
mock.expect_pane_current_command()
.returning(move |_| Some(shell_str.clone()));
- assert!(is_pane_at_shell(&mock, "t"), "should be at shell for {}", shell);
+ assert!(
+ is_pane_at_shell(&mock, "t"),
+ "should be at shell for {}",
+ shell
+ );
}
}
@@ -7187,7 +7965,11 @@ fn test_is_pane_at_shell_returns_false_for_agent_processes() {
let agent_str = agent.to_string();
mock.expect_pane_current_command()
.returning(move |_| Some(agent_str.clone()));
- assert!(!is_pane_at_shell(&mock, "t"), "should not be at shell for {}", agent);
+ assert!(
+ !is_pane_at_shell(&mock, "t"),
+ "should not be at shell for {}",
+ agent
+ );
}
}
@@ -7199,7 +7981,10 @@ fn test_is_agent_active_detects_claude_via_indicator() {
.returning(|_| Some("bash".to_string())); // node/bash β€” Check 1 misses
mock.expect_capture_pane()
.returning(|_| Ok("Claude Code v2.1.72\n> ".to_string()));
- assert!(is_agent_active(&mock, "t"), "Claude Code indicator should trigger is_agent_active");
+ assert!(
+ is_agent_active(&mock, "t"),
+ "Claude Code indicator should trigger is_agent_active"
+ );
}
#[test]
@@ -7210,7 +7995,10 @@ fn test_is_agent_active_detects_gemini_via_indicator() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("some output\nType your message".to_string()));
- assert!(is_agent_active(&mock, "t"), "Gemini indicator should trigger is_agent_active");
+ assert!(
+ is_agent_active(&mock, "t"),
+ "Gemini indicator should trigger is_agent_active"
+ );
}
#[test]
@@ -7221,7 +8009,10 @@ fn test_is_agent_active_detects_opencode_via_indicator() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("some output\nAsk anything".to_string()));
- assert!(is_agent_active(&mock, "t"), "OpenCode indicator should trigger is_agent_active");
+ assert!(
+ is_agent_active(&mock, "t"),
+ "OpenCode indicator should trigger is_agent_active"
+ );
}
#[test]
@@ -7232,7 +8023,10 @@ fn test_is_agent_active_detects_cursor_via_indicator() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("some output\nCursor Agent\n> ".to_string()));
- assert!(is_agent_active(&mock, "t"), "Cursor indicator should trigger is_agent_active");
+ assert!(
+ is_agent_active(&mock, "t"),
+ "Cursor indicator should trigger is_agent_active"
+ );
}
#[test]
@@ -7243,7 +8037,10 @@ fn test_is_agent_active_detects_codex_via_indicator() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("some output\nOpenAI Codex".to_string()));
- assert!(is_agent_active(&mock, "t"), "Codex indicator should trigger is_agent_active");
+ assert!(
+ is_agent_active(&mock, "t"),
+ "Codex indicator should trigger is_agent_active"
+ );
}
#[test]
@@ -7254,7 +8051,10 @@ fn test_is_agent_active_returns_false_when_no_indicator() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("just some shell output".to_string()));
- assert!(!is_agent_active(&mock, "t"), "no indicator should return false");
+ assert!(
+ !is_agent_active(&mock, "t"),
+ "no indicator should return false"
+ );
}
// =============================================================================
@@ -7319,13 +8119,16 @@ fn test_wait_for_agent_ready_detects_codex_via_banner() {
fn test_switch_agent_cursor_sends_ctrl_c_not_exit() {
// Cursor is an Ink/Node TUI β€” uses Ctrl+C to exit, no /exit command
let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_send_keys_literal()
+ mock_tmux
+ .expect_send_keys_literal()
.withf(|_, key: &str| key == "C-c")
.times(1)
.returning(|_, _| Ok(()));
- mock_tmux.expect_pane_current_command()
+ mock_tmux
+ .expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
- mock_tmux.expect_send_keys()
+ mock_tmux
+ .expect_send_keys()
.withf(|_, cmd: &str| cmd == "agent --yolo")
.times(1)
.returning(|_, _| Ok(()));
diff --git a/src/tui/board.rs b/src/tui/board.rs
index 993574e..ac13a70 100644
--- a/src/tui/board.rs
+++ b/src/tui/board.rs
@@ -34,9 +34,7 @@ impl BoardState {
/// Get the currently selected task (mutable)
pub fn selected_task_mut(&mut self) -> Option<&mut Task> {
- let status = TaskStatus::columns()
- .get(self.selected_column)
- .copied()?;
+ let status = TaskStatus::columns().get(self.selected_column).copied()?;
let mut matching_indices: Vec<usize> = self
.tasks
@@ -46,7 +44,9 @@ impl BoardState {
.map(|(i, _)| i)
.collect();
- matching_indices.get(self.selected_row).and_then(|&idx| self.tasks.get_mut(idx))
+ matching_indices
+ .get(self.selected_row)
+ .and_then(|&idx| self.tasks.get_mut(idx))
}
/// Move selection left
diff --git a/src/tui/shell_popup.rs b/src/tui/shell_popup.rs
index 7f77711..bfea673 100644
--- a/src/tui/shell_popup.rs
+++ b/src/tui/shell_popup.rs
@@ -191,9 +191,7 @@ pub fn trim_trailing_empty_lines(lines: &[&str]) -> usize {
}
// Find the last non-empty line
- let last_content_line = lines
- .iter()
- .rposition(|line| !line.trim().is_empty());
+ let last_content_line = lines.iter().rposition(|line| !line.trim().is_empty());
match last_content_line {
Some(idx) => {
@@ -263,10 +261,10 @@ pub fn render_shell_popup(
let popup_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
- Constraint::Length(1), // Title bar
- Constraint::Length(escalation_height), // Escalation banner (0 if none)
- Constraint::Min(0), // Shell content
- Constraint::Length(1), // Footer
+ Constraint::Length(1), // Title bar
+ Constraint::Length(escalation_height), // Escalation banner (0 if none)
+ Constraint::Min(0), // Shell content
+ Constraint::Length(1), // Footer
])
.split(inner_area);
@@ -280,11 +278,22 @@ pub fn render_shell_popup(
// Escalation banner (if present)
if let Some(ref note) = popup.escalation_note {
let banner_text = format!(" \u{26a0} {} ", note);
- let padded_banner = format!("{:<width$}", banner_text, width = popup_chunks[1].width as usize);
- let hint = format!("{:<width$}", " Press any key to dismiss", width = popup_chunks[1].width as usize);
+ let padded_banner = format!(
+ "{:<width$}",
+ banner_text,
+ width = popup_chunks[1].width as usize
+ );
+ let hint = format!(
+ "{:<width$}",
+ " Press any key to dismiss",
+ width = popup_chunks[1].width as usize
+ );
let banner_content = format!("{}\n{}", padded_banner, hint);
- let banner = Paragraph::new(banner_content)
- .style(Style::default().fg(colors.escalation_fg).bg(colors.escalation_bg));
+ let banner = Paragraph::new(banner_content).style(
+ Style::default()
+ .fg(colors.escalation_fg)
+ .bg(colors.escalation_bg),
+ );
frame.render_widget(banner, popup_chunks[1]);
}
@@ -300,7 +309,11 @@ pub fn render_shell_popup(
// Footer with scroll indicator (pad to fill width)
let footer_text = build_footer_text(popup.scroll_offset, start_line);
- let padded_footer = format!("{:<width$}", footer_text, width = popup_chunks[3].width as usize);
+ let padded_footer = format!(
+ "{:<width$}",
+ footer_text,
+ width = popup_chunks[3].width as usize
+ );
let footer = Paragraph::new(padded_footer)
.style(Style::default().fg(colors.footer_fg).bg(colors.footer_bg));
frame.render_widget(footer, popup_chunks[3]);
diff --git a/tests/agent_tests.rs b/tests/agent_tests.rs
index 9d311f7..6a85141 100644
--- a/tests/agent_tests.rs
+++ b/tests/agent_tests.rs
@@ -95,10 +95,22 @@ fn test_build_interactive_command_cursor_escapes_single_quotes() {
fn test_build_interactive_command_existing_agents_unchanged() {
let agents = known_agents();
let by_name = |n: &str| agents.iter().find(|a| a.name == n).unwrap().clone();
- assert_eq!(by_name("claude").build_interactive_command(""), "claude --dangerously-skip-permissions");
- assert_eq!(by_name("codex").build_interactive_command(""), "codex --full-auto");
- assert_eq!(by_name("gemini").build_interactive_command(""), "gemini --approval-mode yolo");
- assert_eq!(by_name("opencode").build_interactive_command(""), "opencode");
+ assert_eq!(
+ by_name("claude").build_interactive_command(""),
+ "claude --dangerously-skip-permissions"
+ );
+ assert_eq!(
+ by_name("codex").build_interactive_command(""),
+ "codex --full-auto"
+ );
+ assert_eq!(
+ by_name("gemini").build_interactive_command(""),
+ "gemini --approval-mode yolo"
+ );
+ assert_eq!(
+ by_name("opencode").build_interactive_command(""),
+ "opencode"
+ );
}
// =============================================================================
diff --git a/tests/config_tests.rs b/tests/config_tests.rs
index e5b834e..aab78f1 100644
--- a/tests/config_tests.rs
+++ b/tests/config_tests.rs
@@ -115,7 +115,10 @@ fn test_merged_config_project_overrides() {
assert_eq!(merged.default_agent, "codex");
assert_eq!(merged.base_branch, "develop");
- assert_eq!(merged.github_url, Some("https://github.com/user/repo".to_string()));
+ assert_eq!(
+ merged.github_url,
+ Some("https://github.com/user/repo".to_string())
+ );
assert_eq!(merged.copy_files, Some(".env, .env.local".to_string()));
assert_eq!(merged.init_script, Some("npm install".to_string()));
}
@@ -176,10 +179,7 @@ fn test_first_run_new_user_prompt() {
#[test]
fn test_agent_for_phase_all_defaults() {
- let config = MergedConfig::merge(
- &GlobalConfig::default(),
- &ProjectConfig::default(),
- );
+ let config = MergedConfig::merge(&GlobalConfig::default(), &ProjectConfig::default());
assert_eq!(config.agent_for_phase("research"), "claude");
assert_eq!(config.agent_for_phase("planning"), "claude");
assert_eq!(config.agent_for_phase("running"), "claude");
diff --git a/tests/db_tests.rs b/tests/db_tests.rs
index 350d7e3..4ffb66d 100644
--- a/tests/db_tests.rs
+++ b/tests/db_tests.rs
@@ -1,4 +1,4 @@
-use agtx::db::{Database, Notification, Task, TaskStatus, Project};
+use agtx::db::{Database, Notification, Project, Task, TaskStatus};
// === TaskStatus Tests ===
diff --git a/tests/git_tests.rs b/tests/git_tests.rs
index 3c503df..2290115 100644
--- a/tests/git_tests.rs
+++ b/tests/git_tests.rs
@@ -43,7 +43,6 @@ fn test_worktree_exists_false_for_nonexistent() {
assert!(!git::worktree_exists(temp_dir.path(), "nonexistent-task"));
}
-
// =============================================================================
// Integration tests (require git)
// =============================================================================
@@ -302,7 +301,6 @@ fn test_worktree_with_uncommitted_changes() {
assert!(result.is_ok());
}
-
// =============================================================================
// initialize_worktree tests
// =============================================================================
@@ -379,13 +377,8 @@ fn test_initialize_worktree_init_script_failure() {
let temp_dir = setup_git_repo();
let worktree_path = git::create_worktree(temp_dir.path(), "init-script-fail").unwrap();
- let warnings = git::initialize_worktree(
- temp_dir.path(),
- &worktree_path,
- None,
- Some("exit 1"),
- &[],
- );
+ let warnings =
+ git::initialize_worktree(temp_dir.path(), &worktree_path, None, Some("exit 1"), &[]);
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("init_script"));
}
@@ -439,13 +432,8 @@ fn test_initialize_worktree_empty_copy_files() {
let temp_dir = setup_git_repo();
let worktree_path = git::create_worktree(temp_dir.path(), "init-empty").unwrap();
- let warnings = git::initialize_worktree(
- temp_dir.path(),
- &worktree_path,
- Some(", , "),
- None,
- &[],
- );
+ let warnings =
+ git::initialize_worktree(temp_dir.path(), &worktree_path, Some(", , "), None, &[]);
assert!(warnings.is_empty());
}
@@ -458,13 +446,8 @@ fn test_initialize_worktree_copy_directory_supported() {
let worktree_path = git::create_worktree(temp_dir.path(), "init-dir").unwrap();
- let warnings = git::initialize_worktree(
- temp_dir.path(),
- &worktree_path,
- Some("config"),
- None,
- &[],
- );
+ let warnings =
+ git::initialize_worktree(temp_dir.path(), &worktree_path, Some("config"), None, &[]);
assert_eq!(warnings.len(), 0);
// Directory and its contents should be copied
assert!(worktree_path.join("config").join("app.toml").exists());
@@ -489,11 +472,23 @@ fn test_check_merge_conflicts_no_conflict() {
.unwrap();
std::fs::write(path.join("new_file.txt"), "feature content").unwrap();
- Command::new("git").current_dir(path).args(["add", "."]).output().unwrap();
- Command::new("git").current_dir(path).args(["commit", "-m", "add new file"]).output().unwrap();
+ Command::new("git")
+ .current_dir(path)
+ .args(["add", "."])
+ .output()
+ .unwrap();
+ Command::new("git")
+ .current_dir(path)
+ .args(["commit", "-m", "add new file"])
+ .output()
+ .unwrap();
// Switch back to main
- Command::new("git").current_dir(path).args(["checkout", "main"]).output().unwrap();
+ Command::new("git")
+ .current_dir(path)
+ .args(["checkout", "main"])
+ .output()
+ .unwrap();
let (has_conflicts, files) = git::check_merge_conflicts(path, "main", "task/feature").unwrap();
assert!(!has_conflicts);
@@ -513,15 +508,35 @@ fn test_check_merge_conflicts_with_conflict() {
.unwrap();
std::fs::write(path.join("README.md"), "# Feature branch change").unwrap();
- Command::new("git").current_dir(path).args(["add", "."]).output().unwrap();
- Command::new("git").current_dir(path).args(["commit", "-m", "modify readme on feature"]).output().unwrap();
+ Command::new("git")
+ .current_dir(path)
+ .args(["add", "."])
+ .output()
+ .unwrap();
+ Command::new("git")
+ .current_dir(path)
+ .args(["commit", "-m", "modify readme on feature"])
+ .output()
+ .unwrap();
// Switch back to main and make a conflicting change
- Command::new("git").current_dir(path).args(["checkout", "main"]).output().unwrap();
+ Command::new("git")
+ .current_dir(path)
+ .args(["checkout", "main"])
+ .output()
+ .unwrap();
std::fs::write(path.join("README.md"), "# Main branch change").unwrap();
- Command::new("git").current_dir(path).args(["add", "."]).output().unwrap();
- Command::new("git").current_dir(path).args(["commit", "-m", "modify readme on main"]).output().unwrap();
+ Command::new("git")
+ .current_dir(path)
+ .args(["add", "."])
+ .output()
+ .unwrap();
+ Command::new("git")
+ .current_dir(path)
+ .args(["commit", "-m", "modify readme on main"])
+ .output()
+ .unwrap();
let (has_conflicts, files) = git::check_merge_conflicts(path, "main", "task/feature").unwrap();
assert!(has_conflicts);
diff --git a/tests/mock_infrastructure_tests.rs b/tests/mock_infrastructure_tests.rs
index eb8a324..178c8a3 100644
--- a/tests/mock_infrastructure_tests.rs
+++ b/tests/mock_infrastructure_tests.rs
@@ -11,7 +11,9 @@ use std::path::Path;
use std::sync::Arc;
use agtx::agent::{AgentOperations, AgentRegistry, MockAgentOperations, MockAgentRegistry};
-use agtx::git::{GitOperations, GitProviderOperations, MockGitOperations, MockGitProviderOperations};
+use agtx::git::{
+ GitOperations, GitProviderOperations, MockGitOperations, MockGitProviderOperations,
+};
use agtx::tmux::{MockTmuxOperations, TmuxOperations};
/// Test that mocks can be created and configured
@@ -25,19 +27,20 @@ fn test_mock_infrastructure_works() {
let mut mock_agent = MockAgentOperations::new();
// Configure expectations
- mock_tmux.expect_has_session()
- .returning(|_| false);
+ mock_tmux.expect_has_session().returning(|_| false);
- mock_tmux.expect_create_session()
- .returning(|_, _| Ok(()));
+ mock_tmux.expect_create_session().returning(|_, _| Ok(()));
- mock_git.expect_list_files()
+ mock_git
+ .expect_list_files()
.returning(|_| vec!["src/main.rs".to_string(), "Cargo.toml".to_string()]);
- mock_git_provider.expect_get_pr_state()
+ mock_git_provider
+ .expect_get_pr_state()
.returning(|_, _| Ok(agtx::git::PullRequestState::Open));
- mock_agent.expect_co_author_string()
+ mock_agent
+ .expect_co_author_string()
.return_const("Test Agent <[email protected]>".to_string());
// Verify mocks work as expected
@@ -48,10 +51,15 @@ fn test_mock_infrastructure_works() {
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();
+ 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]>");
+ assert_eq!(
+ mock_agent.co_author_string(),
+ "Test Agent <[email protected]>"
+ );
}
/// Test git operations mock for PR workflow
@@ -60,20 +68,18 @@ 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_add_all().times(1).returning(|_| Ok(()));
- mock_git.expect_has_changes()
- .times(1)
- .returning(|_| true);
+ mock_git.expect_has_changes().times(1).returning(|_| true);
- mock_git.expect_commit()
+ mock_git
+ .expect_commit()
.times(1)
.withf(|_: &Path, msg: &str| msg.contains("Test commit"))
.returning(|_, _| Ok(()));
- mock_git.expect_push()
+ mock_git
+ .expect_push()
.times(1)
.withf(|_, branch, set_upstream| branch == "feature/test" && *set_upstream)
.returning(|_, _, _| Ok(()));
@@ -93,13 +99,15 @@ fn test_tmux_session_management() {
let mut mock_tmux = MockTmuxOperations::new();
// Session doesn't exist initially
- mock_tmux.expect_has_session()
+ mock_tmux
+ .expect_has_session()
.with(mockall::predicate::eq("my-project"))
.times(1)
.returning(|_| false);
// Create session
- mock_tmux.expect_create_session()
+ mock_tmux
+ .expect_create_session()
.with(
mockall::predicate::eq("my-project"),
mockall::predicate::eq("/home/user/project"),
@@ -108,20 +116,31 @@ fn test_tmux_session_management() {
.returning(|_, _| Ok(()));
// Create window in session
- mock_tmux.expect_create_window()
+ mock_tmux
+ .expect_create_window()
.times(1)
.returning(|_, _, _, _| Ok(()));
// Session exists after creation
- mock_tmux.expect_has_session()
+ 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();
+ 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"));
}
@@ -130,28 +149,36 @@ fn test_tmux_session_management() {
fn test_agent_operations_mock() {
let mut mock_agent = MockAgentOperations::new();
- mock_agent.expect_generate_text()
+ 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()
+ 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();
+ 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]>");
+ 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()
+ mock_git
+ .expect_list_files()
.returning(|_| vec!["file1.rs".to_string()]);
// Wrap in Arc (this is how App uses them)
@@ -168,16 +195,17 @@ fn test_mocks_can_be_arc_wrapped() {
#[test]
fn test_agent_registry_mock() {
let mut mock_agent = MockAgentOperations::new();
- mock_agent.expect_co_author_string()
+ mock_agent
+ .expect_co_author_string()
.return_const("Claude <[email protected]>".to_string());
- mock_agent.expect_build_interactive_command()
+ mock_agent
+ .expect_build_interactive_command()
.returning(|prompt| format!("claude '{}'", prompt));
let agent_arc: Arc<dyn AgentOperations> = Arc::new(mock_agent);
let mut mock_registry = MockAgentRegistry::new();
- mock_registry.expect_get()
- .return_const(agent_arc);
+ mock_registry.expect_get().return_const(agent_arc);
// Registry returns the mock agent for any name
let agent = mock_registry.get("claude");
diff --git a/tests/shell_popup_tests.rs b/tests/shell_popup_tests.rs
index 0a57458..6a249f5 100644
--- a/tests/shell_popup_tests.rs
+++ b/tests/shell_popup_tests.rs
@@ -1,7 +1,6 @@
use agtx::tui::shell_popup::{
- compute_visible_lines, build_footer_text, render_shell_popup,
- trim_content_to_cursor, trim_trailing_empty_lines,
- ShellPopup, ShellPopupColors, MAX_TRAILING_EMPTY_LINES,
+ build_footer_text, compute_visible_lines, render_shell_popup, trim_content_to_cursor,
+ trim_trailing_empty_lines, ShellPopup, ShellPopupColors, MAX_TRAILING_EMPTY_LINES,
};
use ratatui::backend::TestBackend;
use ratatui::prelude::*;
@@ -208,10 +207,12 @@ fn test_render_shell_popup_basic() {
Line::from("Line 3"),
];
- terminal.draw(|frame| {
- let area = Rect::new(0, 0, 80, 24);
- render_shell_popup(&popup, frame, area, lines, &colors);
- }).unwrap();
+ terminal
+ .draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ })
+ .unwrap();
// Verify the popup was rendered by checking the buffer
let buffer = terminal.backend().buffer();
@@ -235,10 +236,12 @@ fn test_render_shell_popup_with_content() {
Line::from("$ "),
];
- terminal.draw(|frame| {
- let area = Rect::new(0, 0, 80, 24);
- render_shell_popup(&popup, frame, area, lines, &colors);
- }).unwrap();
+ terminal
+ .draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ })
+ .unwrap();
let buffer = terminal.backend().buffer();
let buffer_content: String = buffer.content().iter().map(|c| c.symbol()).collect();
@@ -260,10 +263,12 @@ fn test_render_shell_popup_scrolled_up() {
let colors = ShellPopupColors::default();
let lines: Vec<Line> = (0..30).map(|i| Line::from(format!("Line {}", i))).collect();
- terminal.draw(|frame| {
- let area = Rect::new(0, 0, 80, 24);
- render_shell_popup(&popup, frame, area, lines, &colors);
- }).unwrap();
+ terminal
+ .draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ })
+ .unwrap();
let buffer = terminal.backend().buffer();
let buffer_content: String = buffer.content().iter().map(|c| c.symbol()).collect();
@@ -283,10 +288,12 @@ fn test_render_shell_popup_empty_content() {
let colors = ShellPopupColors::default();
let lines: Vec<Line> = vec![];
- terminal.draw(|frame| {
- let area = Rect::new(0, 0, 80, 24);
- render_shell_popup(&popup, frame, area, lines, &colors);
- }).unwrap();
+ terminal
+ .draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ })
+ .unwrap();
let buffer = terminal.backend().buffer();
let buffer_content: String = buffer.content().iter().map(|c| c.symbol()).collect();
@@ -315,10 +322,12 @@ fn test_render_shell_popup_custom_colors() {
let lines: Vec<Line> = vec![Line::from("content")];
- terminal.draw(|frame| {
- let area = Rect::new(0, 0, 80, 24);
- render_shell_popup(&popup, frame, area, lines, &colors);
- }).unwrap();
+ terminal
+ .draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ })
+ .unwrap();
// Just verify it doesn't crash with custom colors
let buffer = terminal.backend().buffer();
@@ -335,10 +344,12 @@ fn test_render_shell_popup_small_area() {
let colors = ShellPopupColors::default();
let lines: Vec<Line> = vec![Line::from("test")];
- terminal.draw(|frame| {
- let area = Rect::new(0, 0, 40, 10);
- render_shell_popup(&popup, frame, area, lines, &colors);
- }).unwrap();
+ terminal
+ .draw(|frame| {
+ let area = Rect::new(0, 0, 40, 10);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ })
+ .unwrap();
// Should handle small areas gracefully
let buffer = terminal.backend().buffer();
@@ -428,7 +439,8 @@ fn test_trim_content_to_cursor_with_cursor_info() {
fn test_trim_content_to_cursor_tui_cursor_mid_screen() {
// TUI app (OpenCode, Gemini) with cursor in the middle β€” content below cursor is NOT empty
// Should keep all content, not trim at cursor
- let content = b"header\nstatus bar\n\ninput field\n\noutput area\nmore output\nbottom bar".to_vec();
+ let content =
+ b"header\nstatus bar\n\ninput field\n\noutput area\nmore output\nbottom bar".to_vec();
let cursor_info = Some((3, 8)); // cursor_y=3 (mid-screen), pane_height=8
let result = trim_content_to_cursor(content, cursor_info);
let result_str = String::from_utf8_lossy(&result);