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.

feat: improve task navigation

fynnfluegge23a1e3434b66
diff --git a/CLAUDE.md b/CLAUDE.md
index 81ee39b..913101b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -24,29 +24,35 @@ src/
β”œβ”€β”€ tui/
β”‚ β”œβ”€β”€ mod.rs # Re-exports
β”‚ β”œβ”€β”€ app.rs # Main App struct, event loop, rendering (largest file)
+β”‚ β”œβ”€β”€ app_tests.rs # Unit tests for app.rs (included via #[path])
β”‚ β”œβ”€β”€ board.rs # BoardState - kanban column/row navigation
-β”‚ └── input.rs # InputMode enum for UI states
+β”‚ β”œβ”€β”€ input.rs # InputMode enum for UI states
+β”‚ └── shell_popup.rs # Shell popup state, rendering, content trimming
β”œβ”€β”€ db/
β”‚ β”œβ”€β”€ mod.rs # Re-exports
β”‚ β”œβ”€β”€ schema.rs # Database struct, SQLite operations
β”‚ └── models.rs # Task, Project, TaskStatus enums
β”œβ”€β”€ tmux/
-β”‚ └── mod.rs # Tmux server "agtx", session management
+β”‚ β”œβ”€β”€ mod.rs # Tmux server "agtx", session management
+β”‚ └── operations.rs # TmuxOperations trait (mockable for testing)
β”œβ”€β”€ git/
β”‚ β”œβ”€β”€ mod.rs # is_git_repo helper
-β”‚ └── worktree.rs # Git worktree create/remove/list
+β”‚ β”œβ”€β”€ worktree.rs # Git worktree create/remove/list
+β”‚ β”œβ”€β”€ operations.rs # GitOperations trait (mockable for testing)
+β”‚ └── provider.rs # GitProviderOperations trait (GitHub PR ops)
β”œβ”€β”€ agent/
-β”‚ └── mod.rs # Agent definitions, detection, spawn args
-β”œβ”€β”€ config/
-β”‚ └── mod.rs # GlobalConfig, ProjectConfig, ThemeConfig
-└── operations.rs # Traits for tmux/git operations (for testing)
+β”‚ β”œβ”€β”€ mod.rs # Agent definitions, detection, spawn args
+β”‚ └── operations.rs # AgentOperations/CodingAgent traits (mockable)
+└── config/
+ └── mod.rs # GlobalConfig, ProjectConfig, ThemeConfig
tests/
β”œβ”€β”€ db_tests.rs # Database and model tests
β”œβ”€β”€ config_tests.rs # Configuration tests
β”œβ”€β”€ board_tests.rs # Board navigation tests
β”œβ”€β”€ git_tests.rs # Git worktree tests
-└── workflow_tests.rs # Task workflow tests
+β”œβ”€β”€ mock_infrastructure_tests.rs # Mock infrastructure tests
+└── shell_popup_tests.rs # Shell popup logic tests
```
## Key Concepts
@@ -113,14 +119,15 @@ Structure:
Colors configurable via `~/.config/agtx/config.toml`:
```toml
[theme]
-color_selected = "#FFFF99" # Selected elements (light yellow)
-color_normal = "#00FFFF" # Normal borders (cyan)
-color_dimmed = "#666666" # Inactive elements (gray)
-color_text = "#FFFFFF" # Text (white)
-color_accent = "#00FFFF" # Accents (cyan)
-color_description = "#E8909C" # Task descriptions (rose)
-color_popup_border = "#00FF00" # Popup borders (green)
-color_popup_header = "#00FFFF" # Popup headers (cyan)
+color_selected = "#ead49a" # Selected elements (yellow)
+color_normal = "#5cfff7" # Normal borders (cyan)
+color_dimmed = "#9C9991" # Inactive elements (dark gray)
+color_text = "#f2ece6" # Text (light rose)
+color_accent = "#5cfff7" # Accents (cyan)
+color_description = "#C4B0AC" # Task descriptions (dimmed rose)
+color_column_header = "#a0d2fa" # Column headers (light blue gray)
+color_popup_border = "#9ffcf8" # Popup borders (light cyan)
+color_popup_header = "#69fae7" # Popup headers (light cyan)
```
## Keyboard Shortcuts
@@ -159,9 +166,10 @@ color_popup_header = "#00FFFF" # Popup headers (cyan)
### Task Edit (Description)
| Key | Action |
|-----|--------|
-| `#` | Start file search (fuzzy find) |
+| `#` or `@` | Start file search (fuzzy find) |
| `\` + Enter | Line continuation (multi-line) |
| Arrow keys | Move cursor |
+| `Alt+Left/Right` or `Alt+b/f` | Word-by-word navigation |
| `Home/End` | Jump to start/end |
## Code Patterns
@@ -244,15 +252,18 @@ Dependencies require:
5. Add key handler function `handle_my_popup_key()`
6. Add check in `handle_key()` to route to handler
-## Planning Docs
+## Supported Agents
-See `docs/planning/` for future enhancements:
-- `codex-cli-integration.md` - Plan for Codex CLI agent support
-- `dependency-injection-testing.md` - Plan for improved test coverage
-- `tmux-popup-focus-bug.md` - Known issue with tmux attachment
+Detected automatically via `known_agents()` in order of preference:
+1. **claude** - Anthropic's Claude Code CLI
+2. **aider** - AI pair programming in your terminal
+3. **codex** - OpenAI's Codex CLI
+4. **gh-copilot** - GitHub Copilot CLI
+5. **opencode** - AI-powered coding assistant
+6. **cline** - AI coding assistant for VS Code
+7. **q** - Amazon Q Developer CLI
## Future Enhancements
- Auto-detect Claude idle status (show spinner when working)
- Reopen Done tasks (recreate worktree from preserved branch)
-- Support for additional agents (Aider, Codex, GitHub Copilot CLI)
- Notification when Claude finishes work
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 0c423e0..eb293b8 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -28,6 +28,26 @@ fn hex_to_color(hex: &str) -> Color {
.unwrap_or(Color::White)
}
+/// Build footer help text based on current UI state
+fn build_footer_text(input_mode: InputMode, sidebar_focused: bool, selected_column: usize) -> String {
+ match input_mode {
+ InputMode::Normal => {
+ if sidebar_focused {
+ " [j/k] navigate [Enter] open [l] board [e] hide sidebar [q] quit ".to_string()
+ } else {
+ match selected_column {
+ 0 => " [o] new [/] search [Enter] open [x] del [d] diff [m] plan [M] run [e] sidebar [q] quit".to_string(),
+ 1 => " [o] new [/] search [Enter] open [x] del [d] diff [m] run [e] sidebar [q] quit".to_string(),
+ 2 | 3 => " [o] new [/] search [Enter] open [x] del [d] diff [m] move [r] move left [e] sidebar [q] quit".to_string(),
+ _ => " [o] new [/] search [Enter] open [x] del [e] sidebar [q] quit".to_string(),
+ }
+ }
+ }
+ InputMode::InputTitle => " Enter task title... [Esc] cancel [Enter] next ".to_string(),
+ InputMode::InputDescription => " Enter prompt for agent... [#] file search [Esc] cancel [\\+Enter] newline [Enter] save ".to_string(),
+ }
+}
+
type Terminal = ratatui::Terminal<CrosstermBackend<Stdout>>;
/// Shell popup dimensions - used for both rendering and tmux window sizing
@@ -535,23 +555,7 @@ impl App {
}
// Footer with help
- let footer_text = match state.input_mode {
- InputMode::Normal => {
- if state.sidebar_focused {
- " [j/k] navigate [Enter] open [l] board [e] hide sidebar [q] quit ".to_string()
- } else {
- // Show [r] resume only when Review column is focused
- let is_review_column = state.board.selected_column == 3; // Review is index 3
- if is_review_column {
- " [o] new [/] search [Enter] open [x] del [d] diff [m] move [r] resume [e] sidebar [q] quit".to_string()
- } else {
- " [o] new [/] search [Enter] open [x] del [d] diff [m] move [e] sidebar [q] quit".to_string()
- }
- }
- }
- InputMode::InputTitle => " Enter task title... [Esc] cancel [Enter] next ".to_string(),
- InputMode::InputDescription => " Enter prompt for agent... [#] file search [Esc] cancel [\\+Enter] newline [Enter] save ".to_string(),
- };
+ let footer_text = build_footer_text(state.input_mode, state.sidebar_focused, state.board.selected_column);
let footer = Paragraph::new(footer_text.as_str())
.style(Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)))
@@ -1852,12 +1856,16 @@ impl App {
KeyCode::Char('x') => self.delete_selected_task()?,
KeyCode::Char('d') => self.show_task_diff()?,
KeyCode::Char('m') => self.move_task_right()?,
+ KeyCode::Char('M') => self.move_backlog_to_running()?,
KeyCode::Char('r') => {
- // Move Review task back to Running (for PR changes)
if let Some(task) = self.state.board.selected_task() {
- if task.status == TaskStatus::Review {
- let task_id = task.id.clone();
- self.move_review_to_running(&task_id)?;
+ let task_id = task.id.clone();
+ match task.status {
+ // Move Review task back to Running (for PR changes)
+ TaskStatus::Review => self.move_review_to_running(&task_id)?,
+ // Move Running task back to Planning
+ TaskStatus::Running => self.move_running_to_planning(&task_id)?,
+ _ => {}
}
}
}
@@ -2219,34 +2227,6 @@ impl App {
if let Some(new_status) = next_status {
// Create worktree and tmux window when moving from Backlog to Planning
if current_status == TaskStatus::Backlog && new_status == TaskStatus::Planning {
- let unique_slug = generate_task_slug(&task.id, &task.title);
- let window_name = format!("task-{}", unique_slug);
- let target = format!("{}:{}", self.state.project_name, window_name);
-
- // Create git worktree from main branch
- let worktree_path_str = match self.state.git_ops.create_worktree(&project_path, &unique_slug) {
- Ok(path) => path,
- Err(e) => {
- // Log error but don't crash - worktree might already exist
- eprintln!("Failed to create worktree: {}", e);
- // Try to use existing worktree path
- project_path.join(".agtx").join("worktrees").join(&unique_slug)
- .to_string_lossy().to_string()
- }
- };
-
- // Initialize worktree: copy files and run init script
- let worktree_path = Path::new(&worktree_path_str);
- let init_warnings = self.state.git_ops.initialize_worktree(
- &project_path,
- worktree_path,
- self.state.config.copy_files.clone(),
- self.state.config.init_script.clone(),
- );
- for warning in &init_warnings {
- eprintln!("Worktree init: {}", warning);
- }
-
// Build the prompt from task title and description
// Instruct agent to plan first and wait for approval
let task_content = if let Some(desc) = &task.description {
@@ -2261,18 +2241,15 @@ impl App {
task_content
);
- // Get the default agent and build the interactive command
- let agent = agent::default_agent().unwrap_or_else(|| agent::get_agent("claude").unwrap());
- let agent_cmd = agent.build_interactive_command(&prompt);
-
- // Ensure project tmux session exists
- ensure_project_tmux_session(&self.state.project_name, &project_path, self.state.tmux_ops.as_ref());
-
- self.state.tmux_ops.create_window(
+ let target = setup_task_worktree(
+ &mut task,
+ &project_path,
&self.state.project_name,
- &window_name,
- &worktree_path_str,
- Some(agent_cmd),
+ &prompt,
+ self.state.config.copy_files.clone(),
+ self.state.config.init_script.clone(),
+ self.state.tmux_ops.as_ref(),
+ self.state.git_ops.as_ref(),
)?;
// Wait for agent to show the bypass warning prompt, then accept it and rename session
@@ -2307,10 +2284,6 @@ impl App {
let _ = tmux_ops.send_keys(&target_clone, &rename_cmd);
}
});
-
- task.session_name = Some(target);
- task.worktree_path = Some(worktree_path_str);
- task.branch_name = Some(format!("task/{}", unique_slug));
}
// When moving from Planning to Running, tell agent to start implementing
@@ -2413,6 +2386,79 @@ impl App {
Ok(())
}
+ /// Move task directly from Backlog to Running (skip Planning)
+ fn move_backlog_to_running(&mut self) -> Result<()> {
+ let (mut task, project_path) = match (
+ self.state.board.selected_task().cloned(),
+ self.state.project_path.clone(),
+ ) {
+ (Some(t), Some(p)) => (t, p),
+ _ => return Ok(()),
+ };
+
+ if task.status != TaskStatus::Backlog {
+ return Ok(());
+ }
+
+ // Build prompt - skip planning, go straight to implementation
+ let task_content = if let Some(desc) = &task.description {
+ format!("{}\n\n{}", task.title, desc)
+ } else {
+ task.title.clone()
+ };
+ let prompt = format!(
+ "Task: {}\n\nPlease implement this task directly. No need to plan first - go ahead and make the changes.",
+ task_content
+ );
+
+ let target = setup_task_worktree(
+ &mut task,
+ &project_path,
+ &self.state.project_name,
+ &prompt,
+ self.state.config.copy_files.clone(),
+ self.state.config.init_script.clone(),
+ self.state.tmux_ops.as_ref(),
+ self.state.git_ops.as_ref(),
+ )?;
+
+ // Wait for agent to show the bypass warning prompt, then accept it and rename session
+ let target_clone = target.clone();
+ let task_id_clone = task.id.clone();
+ let tmux_ops = Arc::clone(&self.state.tmux_ops);
+ std::thread::spawn(move || {
+ let mut accepted = false;
+ for _ in 0..50 {
+ std::thread::sleep(std::time::Duration::from_millis(100));
+
+ if let Ok(content) = tmux_ops.capture_pane(&target_clone) {
+ if content.contains("Yes, I accept") || content.contains("I accept the risk") {
+ let _ = tmux_ops.send_keys_literal(&target_clone, "2");
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ let _ = tmux_ops.send_keys_literal(&target_clone, "Enter");
+ accepted = true;
+ break;
+ }
+ }
+ }
+
+ if accepted {
+ std::thread::sleep(std::time::Duration::from_millis(1000));
+ let rename_cmd = format!("/rename {}", task_id_clone);
+ let _ = tmux_ops.send_keys(&target_clone, &rename_cmd);
+ }
+ });
+
+ task.status = TaskStatus::Running;
+ task.updated_at = chrono::Utc::now();
+
+ if let Some(db) = &self.state.db {
+ db.update_task(&task)?;
+ }
+ self.refresh_tasks()?;
+ Ok(())
+ }
+
/// Move task from Review back to Running (only allowed transition backwards)
/// The tmux window should still be open from when it was in Running state
fn move_review_to_running(&mut self, task_id: &str) -> Result<()> {
@@ -2432,6 +2478,23 @@ impl App {
Ok(())
}
+ fn move_running_to_planning(&mut self, task_id: &str) -> Result<()> {
+ if let (Some(db), Some(_project_path)) = (&self.state.db, &self.state.project_path) {
+ if let Some(mut task) = db.get_task(task_id)? {
+ if task.status != TaskStatus::Running {
+ return Ok(());
+ }
+
+ // Just move the task back to Planning - the tmux window should still be open
+ task.status = TaskStatus::Planning;
+ task.updated_at = chrono::Utc::now();
+ db.update_task(&task)?;
+ self.refresh_tasks()?;
+ }
+ }
+ Ok(())
+ }
+
fn open_selected_task(&mut self) -> Result<()> {
if let Some(task) = self.state.board.selected_task() {
if let Some(window_name) = &task.session_name.clone() {
@@ -2592,6 +2655,67 @@ fn cleanup_task_for_done(
task.updated_at = chrono::Utc::now();
}
+/// Set up a worktree and tmux window for a task.
+/// Creates worktree, initializes it (copy files + init script), creates tmux window with agent.
+/// Updates task fields (session_name, worktree_path, branch_name) in place.
+/// Returns the tmux target string on success.
+fn setup_task_worktree(
+ task: &mut Task,
+ project_path: &Path,
+ project_name: &str,
+ prompt: &str,
+ copy_files: Option<String>,
+ init_script: Option<String>,
+ tmux_ops: &dyn TmuxOperations,
+ git_ops: &dyn GitOperations,
+) -> Result<String> {
+ let unique_slug = generate_task_slug(&task.id, &task.title);
+ 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) {
+ 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()
+ }
+ };
+
+ // Initialize worktree: copy files and run init script
+ let worktree_path = Path::new(&worktree_path_str);
+ let init_warnings = git_ops.initialize_worktree(
+ project_path,
+ worktree_path,
+ copy_files,
+ init_script,
+ );
+ for warning in &init_warnings {
+ 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);
+
+ // Ensure project tmux session exists
+ ensure_project_tmux_session(project_name, project_path, tmux_ops);
+
+ tmux_ops.create_window(
+ project_name,
+ &window_name,
+ &worktree_path_str,
+ Some(agent_cmd),
+ )?;
+
+ task.session_name = Some(target.clone());
+ task.worktree_path = Some(worktree_path_str);
+ task.branch_name = Some(format!("task/{}", unique_slug));
+
+ Ok(target)
+}
+
/// Delete task resources: kill tmux window, remove worktree, delete branch
fn delete_task_resources(
task: &Task,
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index 7f8aa4c..c7e3430 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -1246,3 +1246,326 @@ fn test_word_boundary_roundtrip() {
let pos = word_boundary_left(s, pos); // -> 0 (start of "hello")
assert_eq!(pos, 0);
}
+
+// =============================================================================
+// Tests for build_footer_text
+// =============================================================================
+
+#[test]
+fn test_footer_text_sidebar_focused() {
+ let text = build_footer_text(InputMode::Normal, true, 0);
+ assert!(text.contains("[j/k] navigate"));
+ assert!(text.contains("[e] hide sidebar"));
+ assert!(!text.contains("[o] new"));
+}
+
+#[test]
+fn test_footer_text_backlog_column() {
+ let text = build_footer_text(InputMode::Normal, false, 0);
+ assert!(text.contains("[M] run"));
+ assert!(text.contains("[m] plan"));
+ assert!(!text.contains("[r] move left"));
+}
+
+#[test]
+fn test_footer_text_planning_column() {
+ let text = build_footer_text(InputMode::Normal, false, 1);
+ assert!(text.contains("[m] run"));
+ assert!(!text.contains("[M] run"));
+ assert!(!text.contains("[r] move left"));
+}
+
+#[test]
+fn test_footer_text_running_column() {
+ let text = build_footer_text(InputMode::Normal, false, 2);
+ assert!(text.contains("[r] move left"));
+ assert!(text.contains("[m] move"));
+}
+
+#[test]
+fn test_footer_text_review_column() {
+ let text = build_footer_text(InputMode::Normal, false, 3);
+ assert!(text.contains("[r] move left"));
+ assert!(text.contains("[m] move"));
+}
+
+#[test]
+fn test_footer_text_done_column() {
+ let text = build_footer_text(InputMode::Normal, false, 4);
+ assert!(!text.contains("[m] move"));
+ assert!(!text.contains("[r]"));
+ assert!(!text.contains("[d] diff"));
+}
+
+#[test]
+fn test_footer_text_input_title() {
+ let text = build_footer_text(InputMode::InputTitle, false, 0);
+ assert!(text.contains("Enter task title"));
+ assert!(text.contains("[Esc] cancel"));
+}
+
+#[test]
+fn test_footer_text_input_description() {
+ let text = build_footer_text(InputMode::InputDescription, false, 0);
+ assert!(text.contains("[#] file search"));
+ assert!(text.contains("[\\+Enter] newline"));
+}
+
+// =============================================================================
+// Tests for setup_task_worktree
+// =============================================================================
+
+/// Test setup_task_worktree creates worktree, initializes it, and creates tmux window
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_setup_task_worktree_success() {
+ use crate::db::Task;
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+
+ // Expect worktree creation
+ mock_git
+ .expect_create_worktree()
+ .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+
+ // Expect worktree initialization
+ mock_git
+ .expect_initialize_worktree()
+ .returning(|_, _, _, _| vec![]);
+
+ // Expect tmux session check and window creation
+ mock_tmux
+ .expect_has_session()
+ .returning(|_| true);
+
+ mock_tmux
+ .expect_create_window()
+ .returning(|_, _, _, _| Ok(()));
+
+ let mut task = Task::new("Add login feature", "claude", "project-1");
+ task.status = TaskStatus::Backlog;
+
+ let result = setup_task_worktree(
+ &mut task,
+ Path::new("/project"),
+ "my-project",
+ "implement this",
+ None,
+ None,
+ &mock_tmux,
+ &mock_git,
+ );
+
+ assert!(result.is_ok());
+ let target = result.unwrap();
+ assert!(target.starts_with("my-project:task-"));
+ assert!(task.session_name.is_some());
+ assert!(task.worktree_path.is_some());
+ assert!(task.branch_name.is_some());
+ assert!(task.branch_name.as_ref().unwrap().starts_with("task/"));
+}
+
+/// Test setup_task_worktree sets correct task fields
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_setup_task_worktree_sets_task_fields() {
+ use crate::db::Task;
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_create_worktree()
+ .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+ mock_git
+ .expect_initialize_worktree()
+ .returning(|_, _, _, _| vec![]);
+ mock_tmux.expect_has_session().returning(|_| true);
+ mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+
+ let mut task = Task::new("Fix bug", "claude", "project-1");
+
+ let target = setup_task_worktree(
+ &mut task,
+ Path::new("/project"),
+ "my-project",
+ "fix the bug",
+ Some("CLAUDE.md".to_string()),
+ Some("./init.sh".to_string()),
+ &mock_tmux,
+ &mock_git,
+ ).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/"));
+ // 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));
+}
+
+/// Test setup_task_worktree handles worktree creation failure gracefully
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_setup_task_worktree_worktree_creation_fails() {
+ use crate::db::Task;
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+
+ // Worktree creation fails
+ mock_git
+ .expect_create_worktree()
+ .returning(|_, _| Err(anyhow::anyhow!("worktree already exists")));
+
+ // Should still initialize and create window with fallback path
+ mock_git
+ .expect_initialize_worktree()
+ .returning(|_, _, _, _| vec![]);
+ mock_tmux.expect_has_session().returning(|_| true);
+ mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+
+ let mut task = Task::new("Test task", "claude", "project-1");
+
+ let result = setup_task_worktree(
+ &mut task,
+ Path::new("/project"),
+ "my-project",
+ "do something",
+ None,
+ None,
+ &mock_tmux,
+ &mock_git,
+ );
+
+ // 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/"));
+}
+
+/// Test setup_task_worktree fails when tmux window creation fails
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_setup_task_worktree_tmux_window_fails() {
+ use crate::db::Task;
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_create_worktree()
+ .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+ mock_git
+ .expect_initialize_worktree()
+ .returning(|_, _, _, _| vec![]);
+ mock_tmux.expect_has_session().returning(|_| true);
+
+ // Tmux window creation fails
+ mock_tmux
+ .expect_create_window()
+ .returning(|_, _, _, _| Err(anyhow::anyhow!("tmux not running")));
+
+ let mut task = Task::new("Test task", "claude", "project-1");
+
+ let result = setup_task_worktree(
+ &mut task,
+ Path::new("/project"),
+ "my-project",
+ "do something",
+ None,
+ None,
+ &mock_tmux,
+ &mock_git,
+ );
+
+ // Should propagate the error
+ assert!(result.is_err());
+ assert!(result.unwrap_err().to_string().contains("tmux not running"));
+}
+
+/// Test setup_task_worktree creates tmux session when missing
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_setup_task_worktree_creates_session_when_missing() {
+ use crate::db::Task;
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_create_worktree()
+ .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+ mock_git
+ .expect_initialize_worktree()
+ .returning(|_, _, _, _| vec![]);
+
+ // Session doesn't exist yet
+ mock_tmux
+ .expect_has_session()
+ .returning(|_| false);
+ mock_tmux
+ .expect_create_session()
+ .returning(|_, _| Ok(()));
+ mock_tmux
+ .expect_create_window()
+ .returning(|_, _, _, _| Ok(()));
+
+ let mut task = Task::new("New task", "claude", "project-1");
+
+ let result = setup_task_worktree(
+ &mut task,
+ Path::new("/project"),
+ "my-project",
+ "do work",
+ None,
+ None,
+ &mock_tmux,
+ &mock_git,
+ );
+
+ assert!(result.is_ok());
+}
+
+/// Test setup_task_worktree passes copy_files and init_script to initialize_worktree
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_setup_task_worktree_passes_init_config() {
+ use crate::db::Task;
+
+ let mut mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+
+ mock_git
+ .expect_create_worktree()
+ .returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
+
+ // Verify copy_files and init_script are passed through
+ mock_git
+ .expect_initialize_worktree()
+ .withf(|_, _, copy_files, init_script| {
+ copy_files.as_deref() == Some("CLAUDE.md,.env")
+ && init_script.as_deref() == Some("./setup.sh")
+ })
+ .returning(|_, _, _, _| vec!["warning: .env not found".to_string()]);
+
+ mock_tmux.expect_has_session().returning(|_| true);
+ mock_tmux.expect_create_window().returning(|_, _, _, _| Ok(()));
+
+ let mut task = Task::new("Task with config", "claude", "project-1");
+
+ let result = setup_task_worktree(
+ &mut task,
+ Path::new("/project"),
+ "my-project",
+ "implement feature",
+ Some("CLAUDE.md,.env".to_string()),
+ Some("./setup.sh".to_string()),
+ &mock_tmux,
+ &mock_git,
+ );
+
+ assert!(result.is_ok());
+}