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.

refactor: add agent registry (#20)

Fynn Flügged8d3e89ba5ca
diff --git a/src/agent/mod.rs b/src/agent/mod.rs
index a652705..57f715c 100644
--- a/src/agent/mod.rs
+++ b/src/agent/mod.rs
@@ -1,9 +1,9 @@
mod operations;
-pub use operations::{AgentOperations, CodingAgent};
+pub use operations::{AgentOperations, AgentRegistry, CodingAgent, RealAgentRegistry};
#[cfg(feature = "test-mocks")]
-pub use operations::MockAgentOperations;
+pub use operations::{MockAgentOperations, MockAgentRegistry};
use serde::{Deserialize, Serialize};
diff --git a/src/agent/operations.rs b/src/agent/operations.rs
index c93a600..5b67872 100644
--- a/src/agent/operations.rs
+++ b/src/agent/operations.rs
@@ -4,7 +4,9 @@
//! like Claude Code, Aider, Codex, etc.
use anyhow::Result;
+use std::collections::HashMap;
use std::path::Path;
+use std::sync::Arc;
#[cfg(feature = "test-mocks")]
use mockall::automock;
@@ -21,6 +23,9 @@ pub trait AgentOperations: Send + Sync {
/// Get the co-author string for git commits
/// e.g., "Claude <[email protected]>"
fn co_author_string(&self) -> &str;
+
+ /// Build the shell command to start the agent interactively with a prompt
+ fn build_interactive_command(&self, prompt: &str) -> String;
}
/// Generic agent implementation that works with any Agent config
@@ -71,4 +76,65 @@ impl AgentOperations for CodingAgent {
fn co_author_string(&self) -> &str {
&self.agent.co_author
}
+
+ fn build_interactive_command(&self, prompt: &str) -> String {
+ self.agent.build_interactive_command(prompt)
+ }
+}
+
+/// Registry that maps agent names to AgentOperations instances.
+/// Enables per-stage agent selection (e.g., different agents for planning, running, review).
+#[cfg_attr(feature = "test-mocks", automock)]
+pub trait AgentRegistry: Send + Sync {
+ /// Get the AgentOperations instance for a given agent name.
+ /// Falls back to the default agent if the name is unknown or unavailable.
+ fn get(&self, agent_name: &str) -> Arc<dyn AgentOperations>;
+}
+
+/// Production implementation of AgentRegistry.
+/// Holds all available agents, keyed by name.
+pub struct RealAgentRegistry {
+ agents: HashMap<String, Arc<dyn AgentOperations>>,
+ default_name: String,
+}
+
+impl RealAgentRegistry {
+ /// Create a new registry populated with all available agents.
+ /// `default_name` is used as the fallback when a requested name isn't found.
+ pub fn new(default_name: &str) -> Self {
+ let mut agents: HashMap<String, Arc<dyn AgentOperations>> = HashMap::new();
+
+ for agent in super::known_agents() {
+ if agent.is_available() {
+ let name = agent.name.clone();
+ agents.insert(name, Arc::new(CodingAgent::new(agent)));
+ }
+ }
+
+ // Ensure we have the default agent even if not detected as available
+ if !agents.contains_key(default_name) {
+ if let Some(agent) = super::get_agent(default_name) {
+ agents.insert(default_name.to_string(), Arc::new(CodingAgent::new(agent)));
+ }
+ }
+
+ Self {
+ agents,
+ default_name: default_name.to_string(),
+ }
+ }
+}
+
+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")
+ })
+ }
}
diff --git a/src/tui/app.rs b/src/tui/app.rs
index eb293b8..40597d1 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -10,7 +10,7 @@ use std::io::{self, Stdout};
use std::path::{Path, PathBuf};
use std::sync::{mpsc, Arc};
-use crate::agent::{self, AgentOperations, CodingAgent};
+use crate::agent::{self, AgentOperations};
use crate::config::{GlobalConfig, MergedConfig, ProjectConfig, ThemeConfig};
use crate::db::{Database, Task, TaskStatus};
use crate::git::{self, GitOperations, GitProviderOperations, PullRequestState, RealGitHubOps, RealGitOps};
@@ -79,8 +79,8 @@ struct AppState {
git_ops: Arc<dyn git::GitOperations>,
// Git provider operations (injectable for testing)
git_provider_ops: Arc<dyn GitProviderOperations>,
- // Agent operations (injectable for testing)
- agent_ops: Arc<dyn AgentOperations>,
+ // Agent registry (injectable for testing)
+ agent_registry: Arc<dyn agent::AgentRegistry>,
// Sidebar
sidebar_visible: bool,
sidebar_focused: bool,
@@ -217,7 +217,7 @@ impl App {
Arc::new(RealTmuxOps),
Arc::new(RealGitOps),
Arc::new(RealGitHubOps),
- Arc::new(CodingAgent::default()),
+ Arc::new(agent::RealAgentRegistry::new("claude")),
)
}
@@ -226,7 +226,7 @@ impl App {
tmux_ops: Arc<dyn TmuxOperations>,
git_ops: Arc<dyn GitOperations>,
git_provider_ops: Arc<dyn GitProviderOperations>,
- agent_ops: Arc<dyn AgentOperations>,
+ agent_registry: Arc<dyn agent::AgentRegistry>,
) -> Result<Self> {
// Setup terminal
enable_raw_mode()?;
@@ -288,7 +288,7 @@ impl App {
tmux_ops,
git_ops,
git_provider_ops,
- agent_ops,
+ agent_registry,
sidebar_visible: true,
sidebar_focused: false,
projects: vec![],
@@ -749,7 +749,7 @@ impl App {
.as_millis() / 100) as usize % spinner_chars.len();
let spinner = spinner_chars[spinner_idx];
- let agent_name = agent::default_agent().map(|a| a.name).unwrap_or_else(|| "agent".to_string());
+ let agent_name = state.config.default_agent.clone();
let loading_text = format!("{} Generating PR description with {}...", spinner, agent_name);
let loading = Paragraph::new(loading_text)
.style(Style::default().fg(Color::Cyan))
@@ -1413,7 +1413,7 @@ impl App {
let title_for_thread = task_title.clone();
let worktree_for_thread = worktree_path.clone();
let git_ops = Arc::clone(&self.state.git_ops);
- let agent_ops = Arc::clone(&self.state.agent_ops);
+ 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,
@@ -1511,7 +1511,7 @@ 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 = Arc::clone(&self.state.agent_ops);
+ let agent_ops = self.state.agent_registry.get(&self.state.config.default_agent);
// Create channel for result
let (tx, rx) = mpsc::channel();
@@ -2250,6 +2250,7 @@ impl App {
self.state.config.init_script.clone(),
self.state.tmux_ops.as_ref(),
self.state.git_ops.as_ref(),
+ self.state.agent_registry.get(&self.state.config.default_agent).as_ref(),
)?;
// Wait for agent to show the bypass warning prompt, then accept it and rename session
@@ -2308,7 +2309,7 @@ impl App {
let task_clone = task.clone();
let project_path_clone = project_path.clone();
let git_ops = Arc::clone(&self.state.git_ops);
- let agent_ops = Arc::clone(&self.state.agent_ops);
+ let agent_ops = self.state.agent_registry.get(&self.state.config.default_agent);
let (tx, rx) = mpsc::channel();
self.state.pr_creation_rx = Some(rx);
@@ -2420,6 +2421,7 @@ impl App {
self.state.config.init_script.clone(),
self.state.tmux_ops.as_ref(),
self.state.git_ops.as_ref(),
+ self.state.agent_registry.get(&self.state.config.default_agent).as_ref(),
)?;
// Wait for agent to show the bypass warning prompt, then accept it and rename session
@@ -2668,6 +2670,7 @@ fn setup_task_worktree(
init_script: Option<String>,
tmux_ops: &dyn TmuxOperations,
git_ops: &dyn GitOperations,
+ agent_ops: &dyn AgentOperations,
) -> Result<String> {
let unique_slug = generate_task_slug(&task.id, &task.title);
let window_name = format!("task-{}", unique_slug);
@@ -2695,9 +2698,8 @@ fn setup_task_worktree(
eprintln!("Worktree init: {}", warning);
}
- // Get the default agent and build the interactive command
- let agent = agent::default_agent().unwrap_or_else(|| agent::get_agent("claude").unwrap());
- let agent_cmd = agent.build_interactive_command(prompt);
+ // Build the interactive command using injected agent ops
+ let agent_cmd = agent_ops.build_interactive_command(prompt);
// Ensure project tmux session exists
ensure_project_tmux_session(project_name, project_path, tmux_ops);
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index c7e3430..045a1e6 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -1323,6 +1323,7 @@ fn test_setup_task_worktree_success() {
let mut mock_tmux = MockTmuxOperations::new();
let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
// Expect worktree creation
mock_git
@@ -1334,6 +1335,11 @@ fn test_setup_task_worktree_success() {
.expect_initialize_worktree()
.returning(|_, _, _, _| vec![]);
+ // Expect agent command building
+ mock_agent
+ .expect_build_interactive_command()
+ .returning(|prompt| format!("claude --dangerously-skip-permissions '{}'", prompt));
+
// Expect tmux session check and window creation
mock_tmux
.expect_has_session()
@@ -1355,6 +1361,7 @@ fn test_setup_task_worktree_success() {
None,
&mock_tmux,
&mock_git,
+ &mock_agent,
);
assert!(result.is_ok());
@@ -1374,6 +1381,7 @@ fn test_setup_task_worktree_sets_task_fields() {
let mut mock_tmux = MockTmuxOperations::new();
let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
mock_git
.expect_create_worktree()
@@ -1381,6 +1389,9 @@ fn test_setup_task_worktree_sets_task_fields() {
mock_git
.expect_initialize_worktree()
.returning(|_, _, _, _| vec![]);
+ mock_agent
+ .expect_build_interactive_command()
+ .returning(|prompt| format!("claude '{}'", prompt));
mock_tmux.expect_has_session().returning(|_| true);
mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
@@ -1395,6 +1406,7 @@ fn test_setup_task_worktree_sets_task_fields() {
Some("./init.sh".to_string()),
&mock_tmux,
&mock_git,
+ &mock_agent,
).unwrap();
// session_name should be the returned target
@@ -1414,6 +1426,7 @@ fn test_setup_task_worktree_worktree_creation_fails() {
let mut mock_tmux = MockTmuxOperations::new();
let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
// Worktree creation fails
mock_git
@@ -1424,6 +1437,9 @@ fn test_setup_task_worktree_worktree_creation_fails() {
mock_git
.expect_initialize_worktree()
.returning(|_, _, _, _| vec![]);
+ mock_agent
+ .expect_build_interactive_command()
+ .returning(|prompt| format!("claude '{}'", prompt));
mock_tmux.expect_has_session().returning(|_| true);
mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
@@ -1438,6 +1454,7 @@ fn test_setup_task_worktree_worktree_creation_fails() {
None,
&mock_tmux,
&mock_git,
+ &mock_agent,
);
// Should succeed despite worktree creation failure (uses fallback path)
@@ -1454,6 +1471,7 @@ fn test_setup_task_worktree_tmux_window_fails() {
let mut mock_tmux = MockTmuxOperations::new();
let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
mock_git
.expect_create_worktree()
@@ -1461,6 +1479,9 @@ fn test_setup_task_worktree_tmux_window_fails() {
mock_git
.expect_initialize_worktree()
.returning(|_, _, _, _| vec![]);
+ mock_agent
+ .expect_build_interactive_command()
+ .returning(|prompt| format!("claude '{}'", prompt));
mock_tmux.expect_has_session().returning(|_| true);
// Tmux window creation fails
@@ -1479,6 +1500,7 @@ fn test_setup_task_worktree_tmux_window_fails() {
None,
&mock_tmux,
&mock_git,
+ &mock_agent,
);
// Should propagate the error
@@ -1494,6 +1516,7 @@ fn test_setup_task_worktree_creates_session_when_missing() {
let mut mock_tmux = MockTmuxOperations::new();
let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
mock_git
.expect_create_worktree()
@@ -1501,6 +1524,9 @@ fn test_setup_task_worktree_creates_session_when_missing() {
mock_git
.expect_initialize_worktree()
.returning(|_, _, _, _| vec![]);
+ mock_agent
+ .expect_build_interactive_command()
+ .returning(|prompt| format!("claude '{}'", prompt));
// Session doesn't exist yet
mock_tmux
@@ -1524,6 +1550,7 @@ fn test_setup_task_worktree_creates_session_when_missing() {
None,
&mock_tmux,
&mock_git,
+ &mock_agent,
);
assert!(result.is_ok());
@@ -1537,6 +1564,7 @@ fn test_setup_task_worktree_passes_init_config() {
let mut mock_tmux = MockTmuxOperations::new();
let mut mock_git = MockGitOperations::new();
+ let mut mock_agent = MockAgentOperations::new();
mock_git
.expect_create_worktree()
@@ -1551,6 +1579,9 @@ fn test_setup_task_worktree_passes_init_config() {
})
.returning(|_, _, _, _| vec!["warning: .env not found".to_string()]);
+ mock_agent
+ .expect_build_interactive_command()
+ .returning(|prompt| format!("claude '{}'", prompt));
mock_tmux.expect_has_session().returning(|_| true);
mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
@@ -1565,6 +1596,7 @@ fn test_setup_task_worktree_passes_init_config() {
Some("./setup.sh".to_string()),
&mock_tmux,
&mock_git,
+ &mock_agent,
);
assert!(result.is_ok());
diff --git a/tests/mock_infrastructure_tests.rs b/tests/mock_infrastructure_tests.rs
index feb9174..eb8a324 100644
--- a/tests/mock_infrastructure_tests.rs
+++ b/tests/mock_infrastructure_tests.rs
@@ -10,7 +10,7 @@
use std::path::Path;
use std::sync::Arc;
-use agtx::agent::{AgentOperations, MockAgentOperations};
+use agtx::agent::{AgentOperations, AgentRegistry, MockAgentOperations, MockAgentRegistry};
use agtx::git::{GitOperations, GitProviderOperations, MockGitOperations, MockGitProviderOperations};
use agtx::tmux::{MockTmuxOperations, TmuxOperations};
@@ -163,3 +163,28 @@ fn test_mocks_can_be_arc_wrapped() {
let files = arc_git_clone.list_files(Path::new("/tmp"));
assert_eq!(files.len(), 1);
}
+
+/// Test agent registry mock returns different agents by name
+#[test]
+fn test_agent_registry_mock() {
+ let mut mock_agent = MockAgentOperations::new();
+ mock_agent.expect_co_author_string()
+ .return_const("Claude <[email protected]>".to_string());
+ 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);
+
+ // Registry returns the mock agent for any name
+ let agent = mock_registry.get("claude");
+ assert_eq!(agent.co_author_string(), "Claude <[email protected]>");
+ assert!(agent.build_interactive_command("test").contains("claude"));
+
+ // Same agent returned for unknown names (fallback behavior)
+ let agent2 = mock_registry.get("unknown");
+ assert_eq!(agent2.co_author_string(), "Claude <[email protected]>");
+}