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: increase test coverage of app_rs (#30)

Fynn FlΓΌgge6919b6738597
diff --git a/CLAUDE.md b/CLAUDE.md
index b31fef0..3bff1d9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -57,6 +57,7 @@ plugins/ # Bundled plugin configs (embedded at compile time)
β”œβ”€β”€ agtx/plugin.toml # Default workflow with skills and prompts
β”œβ”€β”€ gsd/plugin.toml # Get Shit Done workflow
β”œβ”€β”€ spec-kit/plugin.toml # GitHub spec-kit workflow
+β”œβ”€β”€ openspec/plugin.toml # OpenSpec specification framework
└── void/plugin.toml # Plain agent session, no prompting
tests/
@@ -98,6 +99,9 @@ Plugins customize the task lifecycle per phase. A plugin is a TOML file (`plugin
- **copy_back**: Files/dirs to copy from worktree back to project root when a phase completes
- **cyclic**: When true, enables Review β†’ Planning transition with incrementing phase counter
- **supported_agents**: Agent whitelist (empty = all supported)
+- **auto_dismiss**: Rules to auto-dismiss interactive prompts before sending the task prompt
+
+Phase gating is derived from the config: if a phase's command or prompt contains `{task}`, the phase can be entered directly from Backlog. Otherwise, it requires a prior phase artifact. This replaces the old `research_required` flag β€” all behavior is now inferred from the plugin TOML.
Plugin resolution: project-local `.agtx/plugins/{name}/` β†’ global `~/.config/agtx/plugins/{name}/` β†’ bundled.
diff --git a/README.md b/README.md
index 3d22a36..365be35 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,15 @@
<div align="center">
-<img src="https://github.com/user-attachments/assets/f8d3f9b6-712b-49d0-a84e-2a2c9400bacc" width="680" />
+[//]: <img src="https://github.com/user-attachments/assets/54ac039b-085e-490b-aacc-36c8e244e313" width="428" />
-### **Terminal-native kanban board for managing spec-driven AI coding agent sessions.**
+<img width="1486" height="680" src="https://github.com/user-attachments/assets/45858e09-ab61-422b-b708-db060c73a900" />
-Let different coding agents collaborate on the same task. Plug in any existing spec-driven development framework or specify your own workflow as a custom plugin with per-phase skills, prompts, artifact tracking and autonomous execution.
+## Run and manage multi-agent AI coding workflows from a single terminal board
+Let different AI coding agents collaborate on the same task. **Gemini β†’ research β†’ Claude β†’ implement β†’ Codex β†’ review.**
+Plug in any existing spec-driven development framework or specify your own workflow as a custom plugin with per-phase skills, prompts, artifact tracking and autonomous execution.
-<img width="960" height="645" alt="Screenshot 2026-02-28 at 18 32 06" src="https://github.com/user-attachments/assets/442965f4-d2c4-435f-a065-df56dc483ab7" />
+
+[//]: <img width="1486" height="680" src="https://github.com/user-attachments/assets/45858e09-ab61-422b-b708-db060c73a900" />
</div>
@@ -14,14 +17,11 @@ Let different coding agents collaborate on the same task. Plug in any existing s
## Features
-- **Kanban workflow**: Backlog β†’ Planning β†’ Running β†’ Review β†’ Done (with optional research and cyclic phases)
+- **Multi-project dashboard**: Manage and orchestrate coding agent sessions across all your projects
+- **Multi-agent task lifecycle**: Configure different agents per workflow phase β€” e.g. Gemini for planning, Claude for implementation, Codex for review β€” with automatic agent switching in the same tmux window
- **Git worktree and tmux isolation**: Each task gets its own worktree and tmux window, keeping work separated
-- **Coding agent integrations**: Automatic session management for Claude Code, Codex, Gemini, OpenCode and Copilot
-- **Multi-agent per task**: Configure different agents per workflow phase β€” e.g. Gemini for planning, Claude for implementation, Codex for review β€” with automatic agent switching in the same tmux window
- **Spec-driven development plugins**: Plug in any spec-driven development framework or select from a predefined set of plugins like GSD, Spec-kit or OpenSpec β€” or define custom skills, prompts and artifact tracking - with automatic execution and tracking at each phase
-- **Multi-project dashboard**: Manage tasks across all your projects
-- **PR workflow**: Generate descriptions with AI, create PRs directly from the TUI
-- **Customizable themes**: Configure colors via config file
+- **Multi-agent per task**: Configure different agents per workflow phase β€” e.g. Gemini for planning, Claude for implementation, Codex for review β€” with automatic agent switching in the same tmux window
## Installation
@@ -88,13 +88,6 @@ When writing a task description, you can reference files and agent skills inline
| `#` or `@` | Fuzzy search and insert a file path |
| `!` | Fuzzy search and insert an agent skill/command |
-**Skill references** (`!`) discover commands from your active agent's native command directory (e.g., `.claude/commands/` for Claude, `.codex/skills/` for Codex). The dropdown shows all available slash commands with descriptions, and inserts them in the agent's native invocation format:
-
-```
-/agtx:research the authentication module, then /agtx:plan a fix for the session timeout bug
-```
-
-This includes agtx built-in skills, plugin commands, and any custom user-defined commands.
### Agent Session Features
@@ -131,29 +124,25 @@ By default, all phases use `default_agent`. You can override the agent for speci
default_agent = "claude"
[agents]
-research = "claude"
+research = "gemini"
planning = "claude"
-running = "codex"
-review = "claude"
+running = "claude"
+review = "codex"
```
```toml
# .agtx/config.toml (project override β€” takes precedence over global)
[agents]
-running = "gemini"
+running = "codex"
```
-When a task moves to a phase with a different agent configured, the current agent session is terminated and the new agent starts automatically in the same tmux window. The worktree, git state, and all file changes are preserved across the switch.
-
-Phases without an explicit agent override keep whatever agent is currently running β€” no unnecessary switching occurs.
-
## Spec-driven Development Plugins
-agtx ships with a fully declarative plugin framework β€” a single TOML file is all it takes to integrate any spec-driven development framework into the task lifecycle. No code changes, no custom adapters. The plugin defines commands, prompts, artifact paths, and copy-back rules β€” agtx handles the rest: phase gating, artifact polling, worktree sync, agent switching, and autonomous execution.
+agtx ships with a fully declarative plugin framework β€” a single TOML file is all it takes to integrate any spec-driven development framework into the task lifecycle.
-All runtime behavior is derived from the TOML config. Commands are written once in canonical format and translated automatically for every supported agent. Phases are flexible β€” plugins can skip research, combine research and planning, or define cyclic multi-milestone workflows. Phase accessibility is inferred from the config: if a phase's command or prompt contains `{task}`, it can be entered directly from Backlog; otherwise it's gated behind a prior phase.
+A plugin defines commands, prompts and artifacts β€” agtx handles the rest: phase gating, artifact polling, worktree sync, agent switching, and autonomous execution.
-Press `P` to select a plugin for the current project. The active plugin is shown in the header bar.
+Press `P` to activate a plugin for the current project. The active plugin is shown in the header bar.
| Plugin | Description |
|--------|-------------|
diff --git a/src/db/models.rs b/src/db/models.rs
index 2580a59..45c92f2 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -97,6 +97,11 @@ 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()
+ }
+
/// Generate tmux session name: task-{id}--{project}--{slug}
pub fn generate_session_name(&self, project_name: &str) -> String {
let slug = self
diff --git a/src/db/schema.rs b/src/db/schema.rs
index cb757df..7b4e14b 100644
--- a/src/db/schema.rs
+++ b/src/db/schema.rs
@@ -66,6 +66,24 @@ impl Database {
Ok(db)
}
+ /// Open an in-memory project database (for testing only)
+ #[cfg(feature = "test-mocks")]
+ pub fn open_in_memory_project() -> Result<Self> {
+ let conn = Connection::open_in_memory()?;
+ let db = Self { conn };
+ db.init_project_schema()?;
+ Ok(db)
+ }
+
+ /// Open an in-memory global database (for testing only)
+ #[cfg(feature = "test-mocks")]
+ pub fn open_in_memory_global() -> Result<Self> {
+ let conn = Connection::open_in_memory()?;
+ let db = Self { conn };
+ db.init_global_schema()?;
+ Ok(db)
+ }
+
fn init_project_schema(&self) -> Result<()> {
self.conn.execute_batch(
r#"
diff --git a/src/skills.rs b/src/skills.rs
index 402e509..5f40dc5 100644
--- a/src/skills.rs
+++ b/src/skills.rs
@@ -9,7 +9,7 @@ pub const REVIEW_SKILL: &str = include_str!("../plugins/agtx/skills/review.md");
/// Default built-in skills: (directory_name, SKILL.md content)
/// Used for worktree phases (Research, Planning, Running, Review)
-pub const DEFAULT_SKILLS: &[(&str, &str)] = &[
+pub const BUILTIN_SKILLS: &[(&str, &str)] = &[
("agtx-research", RESEARCH_SKILL),
("agtx-plan", PLAN_SKILL),
("agtx-execute", EXECUTE_SKILL),
@@ -170,6 +170,23 @@ pub fn extract_description(content: &str) -> Option<String> {
None
}
+/// Enumerate built-in skills as agent-native `(command, description)` pairs.
+/// Uses compile-time embedded `BUILTIN_SKILLS` β€” no filesystem access needed.
+pub fn enumerate_available_skills(agent_name: &str) -> Vec<(String, String)> {
+ let mut results = Vec::new();
+ for (skill_name, skill_content) in BUILTIN_SKILLS {
+ let canonical = format!("/{}", skill_name_to_command(skill_name));
+ let command = match transform_plugin_command(&canonical, agent_name) {
+ Some(cmd) => cmd,
+ None => canonical,
+ };
+ let description = extract_description(skill_content)
+ .unwrap_or_else(|| skill_name.replace('-', " "));
+ results.push((command, description));
+ }
+ results
+}
+
/// Extract description from a markdown file with YAML frontmatter on disk.
fn extract_description_from_file(path: &std::path::Path) -> Option<String> {
let mut buf = vec![0u8; 512];
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 3698082..213d4b3 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -52,7 +52,102 @@ fn build_footer_text(input_mode: InputMode, sidebar_focused: bool, selected_colu
}
}
-type Terminal = ratatui::Terminal<CrosstermBackend<Stdout>>;
+type Terminal = ratatui::Terminal<AppBackend>;
+
+/// Backend abstraction: real CrosstermBackend in production, TestBackend in tests.
+enum AppBackend {
+ Crossterm(CrosstermBackend<Stdout>),
+ #[cfg(feature = "test-mocks")]
+ Test(ratatui::backend::TestBackend),
+}
+
+impl ratatui::backend::Backend for AppBackend {
+ type Error = io::Error;
+
+ fn draw<'a, I>(&mut self, content: I) -> io::Result<()>
+ where
+ I: Iterator<Item = (u16, u16, &'a ratatui::buffer::Cell)>,
+ {
+ 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)),
+ }
+ }
+
+ fn hide_cursor(&mut self) -> io::Result<()> {
+ 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)),
+ }
+ }
+
+ fn show_cursor(&mut self) -> io::Result<()> {
+ 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)),
+ }
+ }
+
+ fn get_cursor_position(&mut self) -> io::Result<ratatui::layout::Position> {
+ 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)),
+ }
+ }
+
+ 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)),
+ }
+ }
+
+ fn clear(&mut self) -> io::Result<()> {
+ 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)),
+ }
+ }
+
+ fn clear_region(&mut self, clear_type: ratatui::backend::ClearType) -> io::Result<()> {
+ 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)),
+ }
+ }
+
+ fn size(&self) -> io::Result<ratatui::layout::Size> {
+ 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)),
+ }
+ }
+
+ fn window_size(&mut self) -> io::Result<ratatui::backend::WindowSize> {
+ 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)),
+ }
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ 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)),
+ }
+ }
+}
/// Shell popup dimensions - used for both rendering and tmux window sizing
const SHELL_POPUP_WIDTH: u16 = 128; // Total width including borders
@@ -308,7 +403,7 @@ impl App {
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen)?;
let backend = CrosstermBackend::new(stdout);
- let terminal = Terminal::new(backend)?;
+ let terminal = ratatui::Terminal::new(AppBackend::Crossterm(backend))?;
// Load configs
let global_config = GlobalConfig::load().unwrap_or_default();
@@ -409,6 +504,87 @@ impl App {
Ok(app)
}
+ /// Create an App instance for testing with in-memory databases and TestBackend.
+ /// No real terminal, no real filesystem databases, no agent detection.
+ #[cfg(feature = "test-mocks")]
+ pub fn new_for_test(
+ project_path: Option<PathBuf>,
+ tmux_ops: Arc<dyn TmuxOperations>,
+ git_ops: Arc<dyn GitOperations>,
+ git_provider_ops: Arc<dyn GitProviderOperations>,
+ agent_registry: Arc<dyn agent::AgentRegistry>,
+ ) -> Result<Self> {
+ let backend = ratatui::backend::TestBackend::new(80, 24);
+ let terminal = ratatui::Terminal::new(AppBackend::Test(backend))?;
+
+ let global_db = Database::open_in_memory_global()?;
+ let (db, mode, project_name) = if let Some(ref path) = project_path {
+ let name = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("test-project")
+ .to_string();
+ let db = Database::open_in_memory_project()?;
+ (Some(db), AppMode::Project(path.clone()), name)
+ } else {
+ (None, AppMode::Dashboard, "Dashboard".to_string())
+ };
+
+ let config = MergedConfig::merge(&GlobalConfig::default(), &ProjectConfig::default());
+
+ Ok(Self {
+ terminal,
+ state: AppState {
+ mode,
+ should_quit: false,
+ board: BoardState::new(),
+ input_mode: InputMode::Normal,
+ input_buffer: String::new(),
+ input_cursor: 0,
+ pending_task_title: String::new(),
+ editing_task_id: None,
+ db,
+ global_db,
+ config,
+ project_path,
+ project_name,
+ available_agents: vec![],
+ tmux_ops,
+ git_ops,
+ git_provider_ops,
+ agent_registry,
+ sidebar_visible: false,
+ sidebar_focused: false,
+ projects: vec![],
+ selected_project: 0,
+ show_project_list: false,
+ shell_popup: None,
+ file_search: None,
+ skill_search: None,
+ highlighted_references: HashSet::new(),
+ task_search: None,
+ pr_confirm_popup: None,
+ review_to_running_task_id: None,
+ diff_popup: None,
+ pr_generation_rx: None,
+ pr_status_popup: None,
+ pr_creation_rx: None,
+ setup_rx: None,
+ done_confirm_popup: None,
+ move_confirm_popup: None,
+ skip_move_confirm: false,
+ delete_confirm_popup: None,
+ review_confirm_popup: None,
+ phase_status_cache: HashMap::new(),
+ spinner_frame: 0,
+ pane_content_hashes: HashMap::new(),
+ cached_plugin: None,
+ warning_message: None,
+ plugin_select_popup: None,
+ },
+ })
+ }
+
pub async fn run(&mut self) -> Result<()> {
while !self.state.should_quit {
self.draw()?;
@@ -503,7 +679,7 @@ impl App {
Ok(())
}
- fn draw(&mut self) -> Result<()> {
+ pub fn draw(&mut self) -> Result<()> {
let state = &self.state;
self.terminal.draw(|frame| {
let area = frame.area();
@@ -1594,7 +1770,7 @@ impl App {
frame.render_widget(footer, chunks[2]);
}
- fn handle_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
+ pub fn handle_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
// 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
@@ -2745,14 +2921,24 @@ impl App {
self.state.input_buffer.insert(self.state.input_cursor, '!');
self.state.input_cursor += 1;
- let all_skills = if let Some(ref project_path) = self.state.project_path {
- skills::scan_agent_skills(&self.state.config.default_agent, project_path)
- .into_iter()
- .map(|(command, description)| SkillEntry { command, description })
- .collect()
- } else {
- vec![]
- };
+ // 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();
+
+ // 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) {
+ if seen.insert(command.clone()) {
+ all_skills.push(SkillEntry { command, description });
+ }
+ }
+ }
self.state.skill_search = Some(SkillSearchState {
pattern: String::new(),
@@ -2881,7 +3067,6 @@ impl App {
}
fn move_task_right(&mut self) -> Result<()> {
- // Clone task to avoid borrow issues
let (mut task, project_path) = match (
self.state.board.selected_task().cloned(),
self.state.project_path.clone(),
@@ -2900,356 +3085,315 @@ impl App {
};
if let Some(new_status) = next_status {
- // Check if phase is incomplete and agent is still working
- if !self.state.skip_move_confirm
- && matches!(current_status, TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review)
- {
- let plugin = self.load_task_plugin(&task);
- if let Some(ref wt_path) = task.worktree_path {
- if !phase_artifact_exists(wt_path, current_status, &plugin, task.cycle) {
- // Check if agent is still running in the tmux pane
- let agent_running = task.session_name.as_ref().map_or(false, |target| {
- self.state.tmux_ops.window_exists(target).unwrap_or(false)
- && is_agent_active(&*self.state.tmux_ops, target)
- });
- if agent_running {
- self.state.move_confirm_popup = Some(MoveConfirmPopup {
- task_id: task.id.clone(),
- from_status: current_status,
- to_status: new_status,
- });
- return Ok(());
- }
- }
- }
+ if self.check_phase_incomplete(&task, current_status, new_status) {
+ return Ok(());
}
- // Create worktree and tmux window when moving from Backlog to Planning
- if current_status == TaskStatus::Backlog && new_status == TaskStatus::Planning {
- // Stamp plugin on task if not already set (may be set from research)
- if task.plugin.is_none() {
- task.plugin = self.state.config.workflow_plugin.clone();
- }
- let plugin = self.load_task_plugin(&task);
+ 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)?,
+ _ => false,
+ };
- // 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 !has_research {
- self.state.warning_message = Some((
- format!("Research phase required first β€” press R to start research"),
- std::time::Instant::now(),
- ));
- return Ok(());
- }
+ if !handled {
+ task.status = new_status;
+ task.updated_at = chrono::Utc::now();
+ if let Some(db) = &self.state.db {
+ db.update_task(&task)?;
}
+ }
+ }
+ self.refresh_tasks()?;
+ Ok(())
+ }
- let (planning_agent, agent_switch) = needs_agent_switch(&self.state.config, &task, "planning");
+ /// 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 {
+ if self.state.skip_move_confirm {
+ return false;
+ }
+ 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 };
+ if phase_artifact_exists(wt_path, current_status, &plugin, task.cycle) {
+ return false;
+ }
+ let agent_running = task.session_name.as_ref().map_or(false, |target| {
+ self.state.tmux_ops.window_exists(target).unwrap_or(false)
+ && is_agent_active(&*self.state.tmux_ops, target)
+ });
+ if agent_running {
+ self.state.move_confirm_popup = Some(MoveConfirmPopup {
+ task_id: task.id.clone(),
+ from_status: current_status,
+ to_status: new_status,
+ });
+ return true;
+ }
+ false
+ }
- let has_live_session = task.session_name.as_ref().map_or(false, |s| {
- self.state.tmux_ops.window_exists(s).unwrap_or(false)
- });
+ /// Backlog β†’ Planning: create worktree and tmux window, or reuse existing research session.
+ /// Returns Ok(true) if handled separately (setup spawned, warning shown), Ok(false) to continue with db update.
+ fn transition_to_planning(&mut self, task: &mut Task, project_path: &Path) -> Result<bool> {
+ if task.plugin.is_none() {
+ task.plugin = self.state.config.workflow_plugin.clone();
+ }
+ let plugin = self.load_task_plugin(task);
- if has_live_session {
- // Reuse existing session from research β€” switch agent if needed, then send planning command
- let target = task.session_name.clone().unwrap();
- let task_content = if let Some(desc) = &task.description {
- desc.clone()
- } else {
- task.title.clone()
- };
- // If research artifact exists, agent already has context β€” don't resend task description
- let has_research = task.worktree_path.as_ref().map_or(false, |wt| {
- research_artifact_exists(wt, &task.id, &plugin)
- });
- let planning_phase = if has_research { "planning_with_research" } else { "planning" };
- 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);
+ // 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 !has_research {
+ self.state.warning_message = Some((
+ format!("Research phase required first β€” press R to start research"),
+ std::time::Instant::now(),
+ ));
+ return Ok(true);
+ }
+ }
- let tmux_ops = Arc::clone(&self.state.tmux_ops);
- let task_content_clone = task_content.clone();
- let agent_registry = Arc::clone(&self.state.agent_registry);
- let planning_agent_clone = planning_agent.clone();
- let current_agent_clone = task.agent.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(), &target, &current_agent_clone, &new_cmd);
- let _ = wait_for_agent_ready(&tmux_ops, &target);
- }
- send_skill_and_prompt(&tmux_ops, &target, &skill_cmd, &prompt, &prompt_trigger, &task_content_clone, &planning_agent_clone, &auto_dismiss);
- });
- } else if self.state.setup_rx.is_some() {
- // Setup already in progress, skip
- return Ok(());
- } else {
- // No research session β€” create worktree + tmux window from scratch (non-blocking)
- let task_content = if let Some(desc) = &task.description {
- desc.clone()
- } else {
- task.title.clone()
- };
- 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 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 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);
- let git_ops = Arc::clone(&self.state.git_ops);
- let agent_ops = self.state.agent_registry.get(&planning_agent);
- let task_id = task.id.clone();
- 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 (planning_agent, agent_switch) = needs_agent_switch(&self.state.config, task, "planning");
- let (tx, rx) = mpsc::channel();
- self.state.setup_rx = Some(rx);
+ let has_live_session = task.session_name.as_ref().map_or(false, |s| {
+ self.state.tmux_ops.window_exists(s).unwrap_or(false)
+ });
- std::thread::spawn(move || {
- let mut tmp_task = Task::new(&task_title, &planning_agent_clone, &project_name);
- tmp_task.id = task_id.clone();
- 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(),
- );
+ if has_live_session {
+ // 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 prompt_trigger = resolve_prompt_trigger(&plugin, planning_phase);
+ 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,
+ );
+ task.agent = planning_agent;
+ return Ok(false);
+ }
- match result {
- Ok(target) => {
- let _ = tx.send(SetupResult {
- task_id: task_id.clone(),
- session_name: tmp_task.session_name.unwrap_or_default(),
- worktree_path: tmp_task.worktree_path.unwrap_or_default(),
- branch_name: tmp_task.branch_name.unwrap_or_default(),
- new_status: Some(TaskStatus::Planning),
- agent: planning_agent_clone.clone(),
- plugin: plugin_name,
- error: None,
- });
+ if self.state.setup_rx.is_some() {
+ return Ok(true);
+ }
- 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);
- }
- }
- Err(e) => {
- let _ = tx.send(SetupResult {
- task_id,
- session_name: String::new(),
- worktree_path: String::new(),
- branch_name: String::new(),
- new_status: None,
- agent: planning_agent_clone,
- plugin: plugin_name,
- error: Some(format!("Planning setup failed: {}", e)),
- });
- }
- }
- });
+ // 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 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 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);
+ let git_ops = Arc::clone(&self.state.git_ops);
+ let agent_ops = self.state.agent_registry.get(&planning_agent);
+ let task_id = task.id.clone();
+ 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 project_path = project_path.to_path_buf();
- return Ok(());
- }
- task.agent = planning_agent;
- }
+ let (tx, rx) = mpsc::channel();
+ self.state.setup_rx = Some(rx);
- // When moving from Planning to Running, send skill command to agent
- if current_status == TaskStatus::Planning && new_status == TaskStatus::Running {
- 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 task_content = if let Some(desc) = &task.description {
- desc.clone()
- } else {
- task.title.clone()
- };
- let has_prior_phase = task.worktree_path.as_ref().map_or(false, |wt| {
- research_artifact_exists(wt, &task.id, &plugin)
- || phase_artifact_exists(wt, TaskStatus::Planning, &plugin, task.cycle)
+ std::thread::spawn(move || {
+ let mut tmp_task = Task::new(&task_title, &planning_agent_clone, &project_name);
+ tmp_task.id = task_id.clone();
+ 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(),
+ );
+
+ match result {
+ Ok(target) => {
+ let _ = tx.send(SetupResult {
+ task_id: task_id.clone(),
+ session_name: tmp_task.session_name.unwrap_or_default(),
+ worktree_path: tmp_task.worktree_path.unwrap_or_default(),
+ branch_name: tmp_task.branch_name.unwrap_or_default(),
+ new_status: Some(TaskStatus::Planning),
+ agent: planning_agent_clone.clone(),
+ plugin: plugin_name,
+ error: None,
});
- let run_phase = if has_prior_phase { "running_with_research_or_planning" } else { "running" };
- let skill_cmd = resolve_skill_command(&plugin, "running", &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, "running");
- let session_clone = session_name.clone();
- let tmux_ops = Arc::clone(&self.state.tmux_ops);
- let agent_registry = Arc::clone(&self.state.agent_registry);
- let running_agent_clone = running_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());
- std::thread::spawn(move || {
- if agent_switch {
- 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);
- 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, &running_agent_clone, &auto_dismiss);
+ 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);
+ }
+ }
+ Err(e) => {
+ let _ = tx.send(SetupResult {
+ task_id,
+ session_name: String::new(),
+ worktree_path: String::new(),
+ branch_name: String::new(),
+ new_status: None,
+ agent: planning_agent_clone,
+ plugin: plugin_name,
+ error: Some(format!("Planning setup failed: {}", e)),
});
- task.agent = running_agent;
}
}
+ });
- // When moving from Running to Review: send skill command, then ask about PR
- if current_status == TaskStatus::Running && new_status == TaskStatus::Review {
- // Send review skill command to agent (with optional agent switch)
- let (review_agent, agent_switch) = needs_agent_switch(&self.state.config, &task, "review");
- if let Some(session_name) = &task.session_name {
- let plugin = self.load_task_plugin(&task);
- let task_content = if let Some(desc) = &task.description {
- desc.clone()
- } else {
- task.title.clone()
- };
- 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 session_clone = session_name.clone();
- let tmux_ops = Arc::clone(&self.state.tmux_ops);
- let agent_registry = Arc::clone(&self.state.agent_registry);
- let review_agent_clone = review_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());
- std::thread::spawn(move || {
- if agent_switch {
- let agent_ops = agent_registry.get(&review_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);
- 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, &review_agent_clone, &auto_dismiss);
- });
- }
- task.agent = review_agent.clone();
- // Check if PR already exists (task was resumed from Review)
- if task.pr_number.is_some() {
- // PR already exists - just commit and push the new changes
- self.state.pr_status_popup = Some(PrStatusPopup {
- status: PrCreationStatus::Pushing,
- pr_url: None,
- error_message: None,
- });
+ Ok(true)
+ }
- let task_clone = task.clone();
- let project_path_clone = project_path.clone();
- let git_ops = Arc::clone(&self.state.git_ops);
- let agent_ops = self.state.agent_registry.get(&review_agent);
+ /// Planning β†’ Running: send execution skill/prompt to agent.
+ /// Always returns Ok(false) to continue with db update.
+ 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 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, "running", &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, "running");
+ 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,
+ );
+ task.agent = running_agent;
+ }
+ Ok(false)
+ }
- let (tx, rx) = mpsc::channel();
- self.state.pr_creation_rx = Some(rx);
+ /// Running β†’ Review: send review skill/prompt, then handle PR state.
+ /// Returns Ok(true) always (PR push or review confirm popup shown).
+ fn transition_to_review(&mut self, task: &mut Task, project_path: &Path) -> Result<bool> {
+ let (review_agent, agent_switch) = needs_agent_switch(&self.state.config, task, "review");
+ 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 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());
+ 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,
+ );
+ }
+ task.agent = review_agent.clone();
+
+ // PR already exists (task was resumed from Review) β€” push new changes
+ if task.pr_number.is_some() {
+ self.state.pr_status_popup = Some(PrStatusPopup {
+ status: PrCreationStatus::Pushing,
+ pr_url: None,
+ error_message: None,
+ });
- std::thread::spawn(move || {
- let result = push_changes_to_existing_pr(&task_clone, git_ops.as_ref(), agent_ops.as_ref());
- match result {
- Ok(pr_url) => {
- // Update task in database
- // Keep session_name so popup can still be opened in Review
- if let Ok(db) = crate::db::Database::open_project(&project_path_clone) {
- let mut updated_task = task_clone;
- updated_task.status = TaskStatus::Review;
- updated_task.updated_at = chrono::Utc::now();
- let _ = db.update_task(&updated_task);
- }
- let _ = tx.send(Ok((0, pr_url)));
- }
- Err(e) => {
- let _ = tx.send(Err(e.to_string()));
- }
+ let task_clone = task.clone();
+ let project_path_clone = project_path.to_path_buf();
+ let git_ops = Arc::clone(&self.state.git_ops);
+ let agent_ops = self.state.agent_registry.get(&review_agent);
+
+ let (tx, rx) = mpsc::channel();
+ self.state.pr_creation_rx = Some(rx);
+
+ std::thread::spawn(move || {
+ let result = push_changes_to_existing_pr(&task_clone, 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) {
+ let mut updated_task = task_clone;
+ updated_task.status = TaskStatus::Review;
+ updated_task.updated_at = chrono::Utc::now();
+ let _ = db.update_task(&updated_task);
}
- });
-
- // Keep tmux window open - session_name stays set for resume
-
- return Ok(());
+ let _ = tx.send(Ok((0, pr_url)));
+ }
+ Err(e) => {
+ let _ = tx.send(Err(e.to_string()));
+ }
}
+ });
- // No PR yet - show confirmation popup asking if user wants to create PR
- self.state.review_confirm_popup = Some(ReviewConfirmPopup {
- task_id: task.id.clone(),
- task_title: task.title.clone(),
- });
- return Ok(());
- }
-
- // When moving from Review to Done: Show confirmation with PR state
- if current_status == TaskStatus::Review && new_status == TaskStatus::Done {
- if let Some(pr_number) = task.pr_number {
- let pr_state = 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,
- PullRequestState::Open => DoneConfirmPrState::Open,
- PullRequestState::Unknown => DoneConfirmPrState::Unknown,
- };
+ return Ok(true);
+ }
- self.state.done_confirm_popup = Some(DoneConfirmPopup {
- task_id: task.id.clone(),
- pr_number,
- pr_state: confirm_state,
- });
- return Ok(());
- }
- // No PR - check for uncommitted changes before allowing move to Done
- 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(),
- pr_number: 0,
- pr_state: DoneConfirmPrState::UncommittedChanges,
- });
- return Ok(());
- }
+ // No PR yet β€” show confirmation popup
+ self.state.review_confirm_popup = Some(ReviewConfirmPopup {
+ task_id: task.id.clone(),
+ task_title: task.title.clone(),
+ });
+ Ok(true)
+ }
- // Cleanup resources in background (archive, kill tmux, remove worktree)
- let session_name = task.session_name.clone();
- let worktree_path = task.worktree_path.clone();
- let branch_name = task.branch_name.clone();
- task.session_name = None;
- task.worktree_path = None;
+ /// Review β†’ Done: check PR state, uncommitted changes, or clean up.
+ /// 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 confirm_state = match pr_state {
+ PullRequestState::Merged => DoneConfirmPrState::Merged,
+ PullRequestState::Closed => DoneConfirmPrState::Closed,
+ PullRequestState::Open => DoneConfirmPrState::Open,
+ PullRequestState::Unknown => DoneConfirmPrState::Unknown,
+ };
+ self.state.done_confirm_popup = Some(DoneConfirmPopup {
+ task_id: task.id.clone(),
+ pr_number,
+ pr_state: confirm_state,
+ });
+ return Ok(true);
+ }
- let tmux_ops = Arc::clone(&self.state.tmux_ops);
- let git_ops = Arc::clone(&self.state.git_ops);
- let task_id_clone = task.id.clone();
- let project_path_clone = project_path.clone();
- 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(),
- );
- });
- }
+ // 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))
+ });
+ if has_uncommitted {
+ self.state.done_confirm_popup = Some(DoneConfirmPopup {
+ task_id: task.id.clone(),
+ pr_number: 0,
+ pr_state: DoneConfirmPrState::UncommittedChanges,
+ });
+ return Ok(true);
+ }
- task.status = new_status;
- task.updated_at = chrono::Utc::now();
+ // Clean β€” spawn background cleanup
+ let session_name = task.session_name.clone();
+ let worktree_path = task.worktree_path.clone();
+ let branch_name = task.branch_name.clone();
+ task.session_name = None;
+ task.worktree_path = None;
- if let Some(db) = &self.state.db {
- db.update_task(&task)?;
- }
- }
- self.refresh_tasks()?;
- Ok(())
+ let tmux_ops = Arc::clone(&self.state.tmux_ops);
+ let git_ops = Arc::clone(&self.state.git_ops);
+ let task_id_clone = task.id.clone();
+ 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(),
+ );
+ });
+ Ok(false)
}
/// Start a research session for a Backlog task (creates worktree, reused in planning)
@@ -3282,11 +3426,7 @@ impl App {
let agent_name = self.state.config.agent_for_phase("research").to_string();
- let task_content = if let Some(desc) = &task.description {
- desc.clone()
- } else {
- task.title.clone()
- };
+ let task_content = task.content_text();
let all_agents = collect_phase_agents(&self.state.config);
let project_name = self.state.project_name.clone();
@@ -3420,11 +3560,7 @@ impl App {
}
// Build prompt - skip planning, go straight to implementation
- let task_content = if let Some(desc) = &task.description {
- desc.clone()
- } else {
- task.title.clone()
- };
+ let task_content = task.content_text();
let plugin_name = task.plugin.clone();
let plugin = self.load_task_plugin(&task);
@@ -3654,19 +3790,10 @@ 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> {
- let plugin = match &task.plugin {
- Some(name) => WorkflowPlugin::load(name, self.state.project_path.as_deref()).ok(),
- None => skills::load_bundled_plugin("agtx"),
- };
- if let Some(ref p) = plugin {
- if !p.supports_agent(&self.state.config.default_agent) {
- return None;
- }
- }
- plugin
+ load_task_plugin(task, self.state.project_path.as_deref(), &self.state.config.default_agent)
}
- fn refresh_tasks(&mut self) -> Result<()> {
+ pub fn refresh_tasks(&mut self) -> Result<()> {
if let Some(db) = &self.state.db {
self.state.board.tasks = db.get_all_tasks()?;
}
@@ -3877,8 +4004,14 @@ impl App {
impl Drop for App {
fn drop(&mut self) {
- let _ = disable_raw_mode();
- let _ = execute!(self.terminal.backend_mut(), LeaveAlternateScreen);
+ match self.terminal.backend_mut() {
+ AppBackend::Crossterm(backend) => {
+ let _ = disable_raw_mode();
+ let _ = execute!(backend, LeaveAlternateScreen);
+ }
+ #[cfg(feature = "test-mocks")]
+ AppBackend::Test(_) => {}
+ }
}
}
@@ -4763,8 +4896,32 @@ fn resolve_skill_command(plugin: &Option<WorkflowPlugin>, phase: &str, agent_nam
skills::transform_plugin_command(&expanded, agent_name)
}
-/// Resolve the prompt trigger text for a given phase.
-/// When set, the system polls the tmux pane for this text before sending the prompt.
+/// Spawn a background thread that optionally switches agent, waits for readiness,
+/// then sends a skill command and prompt to the tmux pane.
+fn spawn_send_to_agent(
+ tmux_ops: Arc<dyn TmuxOperations>,
+ agent_registry: Arc<dyn agent::AgentRegistry>,
+ target: String,
+ current_agent: String,
+ target_agent: String,
+ needs_switch: bool,
+ skill_cmd: Option<String>,
+ prompt: String,
+ prompt_trigger: Option<String>,
+ task_content: String,
+ auto_dismiss: Vec<crate::config::AutoDismiss>,
+) {
+ std::thread::spawn(move || {
+ if needs_switch {
+ let agent_ops = agent_registry.get(&target_agent);
+ let new_cmd = agent_ops.build_interactive_command("");
+ 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 command and prompt to the agent via tmux.
/// When there is no prompt_trigger, combines skill command + prompt into a single message
/// (separated by a newline). When a prompt_trigger is set, sends them as two separate messages
@@ -4871,6 +5028,8 @@ 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 {
@@ -4952,6 +5111,40 @@ fn research_artifact_exists(worktree_path: &str, task_id: &str, plugin: &Option<
artifact_path_exists(worktree_path, &rel_template, 1)
}
+/// Determine the phase variant name based on whether prior-phase artifacts exist.
+/// Returns the base phase name or a `_with_*` variant.
+fn determine_phase_variant(
+ phase: &str,
+ worktree_path: Option<&str>,
+ task_id: &str,
+ plugin: &Option<WorkflowPlugin>,
+ cycle: i32,
+) -> &'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" }
+ }
+ "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" }
+ }
+ _ => {
+ // Phases without variants leak the &str β€” use a known static
+ match phase {
+ "review" => "review",
+ "research" => "research",
+ _ => "running",
+ }
+ }
+ }
+}
+
/// Check if an artifact path exists, trying both zero-padded and non-padded {phase} substitution.
fn artifact_path_exists(worktree_path: &str, rel_template: &str, cycle: i32) -> bool {
// Try zero-padded first (e.g. "01"), then non-padded (e.g. "1")
@@ -5249,6 +5442,20 @@ fn wait_for_agent_ready(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> Opt
Some(target.to_string())
}
+/// Load the workflow plugin for a task, checking agent compatibility.
+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(),
+ None => skills::load_bundled_plugin("agtx"),
+ };
+ if let Some(ref p) = plugin {
+ if !p.supports_agent(default_agent) {
+ return None;
+ }
+ }
+ plugin
+}
+
/// Load workflow plugin if configured
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
@@ -5279,7 +5486,7 @@ fn write_skills_to_worktree(worktree_path: &str, project_path: &Path, plugin: &O
if let Some(ref p) = plugin {
// Copy skills from plugin directory, falling back to built-in defaults
if let Some(plugin_dir) = WorkflowPlugin::plugin_dir(&p.name, Some(project_path)) {
- for (skill_name, default_content) in skills::DEFAULT_SKILLS {
+ for (skill_name, default_content) in skills::BUILTIN_SKILLS {
let src = plugin_dir.join(skill_name).join("SKILL.md");
let dst_dir = skills_dir.join(skill_name);
let _ = std::fs::create_dir_all(&dst_dir);
@@ -5291,7 +5498,7 @@ fn write_skills_to_worktree(worktree_path: &str, project_path: &Path, plugin: &O
}
} else {
// Plugin dir not found, write defaults
- for (skill_name, skill_content) in skills::DEFAULT_SKILLS {
+ for (skill_name, skill_content) in skills::BUILTIN_SKILLS {
let skill_dir = skills_dir.join(skill_name);
let _ = std::fs::create_dir_all(&skill_dir);
let _ = std::fs::write(skill_dir.join("SKILL.md"), skill_content);
@@ -5299,7 +5506,7 @@ fn write_skills_to_worktree(worktree_path: &str, project_path: &Path, plugin: &O
}
} else {
// Write built-in default skills
- for (skill_name, skill_content) in skills::DEFAULT_SKILLS {
+ for (skill_name, skill_content) in skills::BUILTIN_SKILLS {
let skill_dir = skills_dir.join(skill_name);
let _ = std::fs::create_dir_all(&skill_dir);
let _ = std::fs::write(skill_dir.join("SKILL.md"), skill_content);
@@ -5317,7 +5524,7 @@ 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::DEFAULT_SKILLS {
+ for (skill_dir_name, default_content) in skills::BUILTIN_SKILLS {
let content = resolve_skill_content(plugin, skill_dir_name, project_path, default_content);
match *agent_name {
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index 7562820..31e1bbb 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -1816,6 +1816,37 @@ fn test_agtx_plugin_has_commands() {
assert_eq!(plugin.commands.review.as_deref(), Some("/agtx:review"));
}
+#[test]
+fn test_enumerate_available_skills_claude() {
+ let skills = skills::enumerate_available_skills("claude");
+ assert_eq!(skills.len(), 4);
+ let commands: Vec<&str> = skills.iter().map(|(c, _)| c.as_str()).collect();
+ assert!(commands.contains(&"/agtx:research"));
+ assert!(commands.contains(&"/agtx:plan"));
+ assert!(commands.contains(&"/agtx:execute"));
+ assert!(commands.contains(&"/agtx:review"));
+ // Each should have a description
+ for (_, desc) in &skills {
+ assert!(!desc.is_empty());
+ }
+}
+
+#[test]
+fn test_enumerate_available_skills_codex() {
+ let skills = skills::enumerate_available_skills("codex");
+ let commands: Vec<&str> = skills.iter().map(|(c, _)| c.as_str()).collect();
+ assert!(commands.contains(&"$agtx-research"));
+ assert!(commands.contains(&"$agtx-plan"));
+}
+
+#[test]
+fn test_enumerate_available_skills_opencode() {
+ let skills = skills::enumerate_available_skills("opencode");
+ let commands: Vec<&str> = skills.iter().map(|(c, _)| c.as_str()).collect();
+ assert!(commands.contains(&"/agtx-research"));
+ assert!(commands.contains(&"/agtx-plan"));
+}
+
#[test]
fn test_resolve_skill_command_no_plugin() {
// No plugin: no commands, returns None for all agents/phases
@@ -2721,6 +2752,79 @@ fn test_phase_artifact_exists_with_phase_substitution() {
let _ = std::fs::remove_dir_all(&tmp);
}
+#[test]
+fn test_determine_phase_variant_planning_no_artifact() {
+ let dir = tempfile::tempdir().unwrap();
+ let wt = dir.path().to_string_lossy().to_string();
+ assert_eq!(
+ determine_phase_variant("planning", Some(&wt), "task-1", &None, 1),
+ "planning"
+ );
+}
+
+#[test]
+fn test_determine_phase_variant_planning_with_research() {
+ use crate::config::WorkflowPlugin;
+ let dir = tempfile::tempdir().unwrap();
+ let artifact_dir = dir.path().join(".planning").join("phases").join("research");
+ std::fs::create_dir_all(&artifact_dir).unwrap();
+ std::fs::write(artifact_dir.join("01-CONTEXT.md"), "# Context").unwrap();
+
+ let plugin_toml = r#"
+ name = "gsd"
+ init_script = "echo test"
+ [commands]
+ [prompts]
+ [artifacts]
+ research = ".planning/phases/research/{phase}-CONTEXT.md"
+ "#;
+ let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();
+ let wt = dir.path().to_string_lossy().to_string();
+ assert_eq!(
+ determine_phase_variant("planning", Some(&wt), "task-1", &Some(plugin), 1),
+ "planning_with_research"
+ );
+}
+
+#[test]
+fn test_determine_phase_variant_running_no_artifact() {
+ let dir = tempfile::tempdir().unwrap();
+ let wt = dir.path().to_string_lossy().to_string();
+ assert_eq!(
+ determine_phase_variant("running", Some(&wt), "task-1", &None, 1),
+ "running"
+ );
+}
+
+#[test]
+fn test_determine_phase_variant_running_with_planning() {
+ use crate::config::WorkflowPlugin;
+ let dir = tempfile::tempdir().unwrap();
+ let plan_dir = dir.path().join(".planning").join("01");
+ std::fs::create_dir_all(&plan_dir).unwrap();
+ std::fs::write(plan_dir.join("PLAN.md"), "# Plan").unwrap();
+
+ let plugin_toml = r#"
+ name = "gsd"
+ init_script = "echo test"
+ [commands]
+ [prompts]
+ [artifacts]
+ planning = ".planning/{phase}/PLAN.md"
+ "#;
+ let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();
+ let wt = dir.path().to_string_lossy().to_string();
+ assert_eq!(
+ determine_phase_variant("running", Some(&wt), "task-1", &Some(plugin), 1),
+ "running_with_research_or_planning"
+ );
+}
+
+#[test]
+fn test_determine_phase_variant_review_passthrough() {
+ assert_eq!(determine_phase_variant("review", None, "t", &None, 1), "review");
+}
+
#[test]
fn test_footer_text_review_non_cyclic_no_next_phase() {
let text = build_footer_text(InputMode::Normal, false, 3, false);
@@ -2793,3 +2897,594 @@ fn test_gsd_plugin_has_cyclic_and_copy_back() {
let preresearch_entries = &plugin.copy_back["preresearch"];
assert!(preresearch_entries.contains(&".planning/PROJECT.md".to_string()));
}
+
+// =============================================================================
+// Tests for send_skill_and_prompt
+// =============================================================================
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_skill_and_prompt_gemini_combined() {
+ let mut mock = MockTmuxOperations::new();
+ 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_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", &[],
+ );
+ 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 == "Enter"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_skill_and_prompt_codex_combined() {
+ let mut mock = MockTmuxOperations::new();
+ 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_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", &[],
+ );
+ 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 == "Enter"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_skill_and_prompt_claude_with_trigger() {
+ let mut mock = MockTmuxOperations::new();
+ 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_literal().returning(|_, _| Ok(()));
+ // Return trigger text immediately
+ mock.expect_capture_pane()
+ .returning(|_| Ok("Ready for input >".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()), "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");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_skill_and_prompt_prompt_only() {
+ let mut mock = MockTmuxOperations::new();
+ 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(())
+ });
+
+ 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", &[],
+ );
+ let calls = keys_calls.lock().unwrap();
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0], "just a prompt");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_skill_and_prompt_void_prefill() {
+ let mut mock = MockTmuxOperations::new();
+ 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(())
+ });
+
+ 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", &[],
+ );
+ let calls = literal_calls.lock().unwrap();
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0], "fix the login bug");
+}
+
+// =============================================================================
+// Tests for wait_for_prompt_trigger
+// =============================================================================
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_prompt_trigger_found_immediately() {
+ let mut mock = MockTmuxOperations::new();
+ mock.expect_capture_pane()
+ .returning(|_| Ok("some output\nReady for input >".to_string()));
+
+ let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
+ let result = wait_for_prompt_trigger(&tmux, "sess:win", "Ready for input", &[]);
+ assert!(result);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_prompt_trigger_auto_dismiss_then_trigger() {
+ use crate::config::AutoDismiss;
+ let mut mock = MockTmuxOperations::new();
+ let call_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
+ let call_c = call_count.clone();
+ 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(())
+ });
+
+ let auto_dismiss = vec![AutoDismiss {
+ detect: vec!["Do you accept?".to_string()],
+ response: "y".to_string(),
+ }];
+
+ let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
+ let result = wait_for_prompt_trigger(&tmux, "sess:win", "Ready for input", &auto_dismiss);
+ assert!(result);
+ assert!(dismiss_sent.load(std::sync::atomic::Ordering::SeqCst));
+}
+
+// =============================================================================
+// Tests for wait_for_agent_ready
+// =============================================================================
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_agent_ready_detects_agent_process() {
+ let mut mock = MockTmuxOperations::new();
+ mock.expect_pane_current_command()
+ .returning(|_| Some("claude".to_string()));
+ mock.expect_capture_pane().returning(|_| Ok(String::new()));
+
+ 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()));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_agent_ready_detects_ready_indicator() {
+ let mut mock = MockTmuxOperations::new();
+ mock.expect_pane_current_command()
+ .returning(|_| Some("bash".to_string()));
+ mock.expect_capture_pane()
+ .returning(|_| Ok("Welcome to Gemini\nType your message".to_string()));
+
+ 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()));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_wait_for_agent_ready_claude_bypass_accept() {
+ let mut mock = MockTmuxOperations::new();
+ let literal_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
+ let literal_c = literal_calls.clone();
+
+ mock.expect_pane_current_command()
+ .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(())
+ });
+
+ 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(&"Enter".to_string()), "should send Enter");
+}
+
+// =============================================================================
+// Tests for write_skills_to_worktree
+// =============================================================================
+
+#[test]
+fn test_write_skills_to_worktree_claude() {
+ let dir = tempfile::tempdir().unwrap();
+ let wt = dir.path().to_string_lossy().to_string();
+
+ write_skills_to_worktree(&wt, dir.path(), &None, &["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());
+
+ // 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());
+}
+
+#[test]
+fn test_write_skills_to_worktree_gemini_toml() {
+ let dir = tempfile::tempdir().unwrap();
+ let wt = dir.path().to_string_lossy().to_string();
+
+ write_skills_to_worktree(&wt, dir.path(), &None, &["gemini"]);
+
+ 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");
+}
+
+#[test]
+fn test_write_skills_to_worktree_codex() {
+ let dir = tempfile::tempdir().unwrap();
+ let wt = dir.path().to_string_lossy().to_string();
+
+ write_skills_to_worktree(&wt, dir.path(), &None, &["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());
+}
+
+#[test]
+fn test_write_skills_to_worktree_opencode() {
+ let dir = tempfile::tempdir().unwrap();
+ let wt = dir.path().to_string_lossy().to_string();
+
+ write_skills_to_worktree(&wt, dir.path(), &None, &["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");
+}
+
+// =============================================================================
+// Tests for load_task_plugin
+// =============================================================================
+
+#[test]
+fn test_load_task_plugin_no_plugin_returns_agtx_default() {
+ let task = crate::db::Task::new("Test", "claude", "proj");
+ let plugin = load_task_plugin(&task, None, "claude");
+ assert!(plugin.is_some());
+ assert_eq!(plugin.unwrap().name, "agtx");
+}
+
+#[test]
+fn test_load_task_plugin_from_disk() {
+ // Create a temporary plugin on 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#"
+ name = "test-plug"
+ [commands]
+ [prompts]
+ [artifacts]
+ "#).unwrap();
+
+ let mut task = crate::db::Task::new("Test", "claude", "proj");
+ task.plugin = Some("test-plug".to_string());
+ let plugin = load_task_plugin(&task, Some(dir.path()), "claude");
+ assert!(plugin.is_some());
+ assert_eq!(plugin.unwrap().name, "test-plug");
+}
+
+#[test]
+fn test_load_task_plugin_unsupported_agent_returns_none() {
+ // Create a plugin that only supports claude
+ 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#"
+ name = "claude-only"
+ supported_agents = ["claude"]
+ [commands]
+ [prompts]
+ [artifacts]
+ "#).unwrap();
+
+ let mut task = crate::db::Task::new("Test", "gemini", "proj");
+ task.plugin = Some("claude-only".to_string());
+ let plugin = load_task_plugin(&task, Some(dir.path()), "gemini");
+ assert!(plugin.is_none(), "should reject unsupported agent");
+}
+
+#[test]
+fn test_load_task_plugin_nonexistent_returns_none() {
+ let mut task = crate::db::Task::new("Test", "claude", "proj");
+ task.plugin = Some("nonexistent-plugin-xyz".to_string());
+ let plugin = load_task_plugin(&task, None, "claude");
+ assert!(plugin.is_none());
+}
+
+// === App Integration Tests ===
+
+#[cfg(feature = "test-mocks")]
+use crate::agent::MockAgentRegistry;
+
+/// Helper: create an App wired with default (no-op) mocks for integration tests.
+/// Returns App in project mode with an empty in-memory DB.
+#[cfg(feature = "test-mocks")]
+fn make_test_app() -> App {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
+ mock_tmux.expect_has_session().returning(|_| false);
+
+ App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(MockGitOperations::new()),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(MockAgentRegistry::new()),
+ ).unwrap()
+}
+
+/// Helper: simulate a key press on the App.
+#[cfg(feature = "test-mocks")]
+fn press_key(app: &mut App, code: KeyCode) {
+ app.handle_key(crossterm::event::KeyEvent::new(
+ code,
+ crossterm::event::KeyModifiers::NONE,
+ )).unwrap();
+}
+
+/// Helper: simulate typing a string into the App (character by character).
+#[cfg(feature = "test-mocks")]
+fn type_str(app: &mut App, s: &str) {
+ for c in s.chars() {
+ press_key(app, KeyCode::Char(c));
+ }
+}
+
+// --- Smoke tests ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_app_new_for_test_project_mode() {
+ let app = make_test_app();
+ assert_eq!(app.state.project_name, "test-project");
+ assert!(app.state.db.is_some());
+ assert!(app.state.project_path.is_some());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_app_new_for_test_dashboard_mode() {
+ let app = App::new_for_test(
+ None,
+ Arc::new(MockTmuxOperations::new()),
+ Arc::new(MockGitOperations::new()),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(MockAgentRegistry::new()),
+ ).unwrap();
+ assert_eq!(app.state.project_name, "Dashboard");
+ assert!(app.state.db.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_app_new_for_test_can_draw() {
+ let mut app = make_test_app();
+ assert!(app.draw().is_ok());
+}
+
+// --- Task creation flow ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_create_task_full_flow() {
+ let mut app = make_test_app();
+
+ // Start in Normal mode, board is empty
+ assert_eq!(app.state.input_mode, InputMode::Normal);
+ assert!(app.state.board.tasks.is_empty());
+
+ // Press 'o' to start task creation
+ press_key(&mut app, KeyCode::Char('o'));
+ assert_eq!(app.state.input_mode, InputMode::InputTitle);
+
+ // Type a title
+ type_str(&mut app, "Fix login bug");
+ assert_eq!(app.state.input_buffer, "Fix login bug");
+
+ // Press Enter to move to description
+ press_key(&mut app, KeyCode::Enter);
+ assert_eq!(app.state.input_mode, InputMode::InputDescription);
+ assert_eq!(app.state.pending_task_title, "Fix login bug");
+ assert!(app.state.input_buffer.is_empty());
+
+ // Type a description
+ type_str(&mut app, "Users report 500 error on /login");
+
+ // Press Enter to save
+ press_key(&mut app, KeyCode::Enter);
+ assert_eq!(app.state.input_mode, InputMode::Normal);
+
+ // Task should now be in the board
+ 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 /login"));
+ assert_eq!(task.status, TaskStatus::Backlog);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_create_task_without_description() {
+ let mut app = make_test_app();
+
+ press_key(&mut app, KeyCode::Char('o'));
+ type_str(&mut app, "Quick fix");
+ press_key(&mut app, KeyCode::Enter); // to description
+ press_key(&mut app, KeyCode::Enter); // save with empty description
+
+ assert_eq!(app.state.board.tasks.len(), 1);
+ let task = &app.state.board.tasks[0];
+ assert_eq!(task.title, "Quick fix");
+ assert!(task.description.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_create_task_cancel_with_esc() {
+ let mut app = make_test_app();
+
+ press_key(&mut app, KeyCode::Char('o'));
+ type_str(&mut app, "Abandoned task");
+ press_key(&mut app, KeyCode::Esc);
+
+ assert_eq!(app.state.input_mode, InputMode::Normal);
+ assert!(app.state.board.tasks.is_empty());
+}
+
+// --- Board navigation ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_board_navigation_with_tasks() {
+ let mut app = make_test_app();
+
+ // 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();
+ app.refresh_tasks().unwrap();
+ assert_eq!(app.state.board.tasks.len(), 2);
+
+ // Board starts at column 0 (Backlog), row 0
+ assert_eq!(app.state.board.selected_column, 0);
+ assert_eq!(app.state.board.selected_row, 0);
+
+ // Press 'j' to move down
+ press_key(&mut app, KeyCode::Char('j'));
+ assert_eq!(app.state.board.selected_row, 1);
+
+ // Press 'k' to move up
+ press_key(&mut app, KeyCode::Char('k'));
+ assert_eq!(app.state.board.selected_row, 0);
+
+ // Press 'l' to move to next column (Planning β€” empty, but cursor moves)
+ press_key(&mut app, KeyCode::Char('l'));
+ assert_eq!(app.state.board.selected_column, 1);
+
+ // Press 'h' to move back
+ press_key(&mut app, KeyCode::Char('h'));
+ assert_eq!(app.state.board.selected_column, 0);
+}
+
+// --- Delete task flow ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_delete_task_confirm() {
+ let mut app = make_test_app();
+
+ // Create a task
+ let db = app.state.db.as_ref().unwrap();
+ db.create_task(&Task::new("Delete me", "claude", "test-project")).unwrap();
+ app.refresh_tasks().unwrap();
+ assert_eq!(app.state.board.tasks.len(), 1);
+
+ // Press 'x' to delete β€” should show confirmation popup
+ press_key(&mut app, KeyCode::Char('x'));
+ assert!(app.state.delete_confirm_popup.is_some());
+
+ // Press 'y' to confirm
+ press_key(&mut app, KeyCode::Char('y'));
+ assert!(app.state.delete_confirm_popup.is_none());
+ assert!(app.state.board.tasks.is_empty());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+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();
+ app.refresh_tasks().unwrap();
+
+ press_key(&mut app, KeyCode::Char('x'));
+ assert!(app.state.delete_confirm_popup.is_some());
+
+ // Press Esc to cancel
+ press_key(&mut app, KeyCode::Esc);
+ assert!(app.state.delete_confirm_popup.is_none());
+ assert_eq!(app.state.board.tasks.len(), 1);
+}
+
+// --- Quit ---
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_quit_sets_should_quit() {
+ let mut app = make_test_app();
+ assert!(!app.state.should_quit);
+ press_key(&mut app, KeyCode::Char('q'));
+ assert!(app.state.should_quit);
+}
+
diff --git a/tests/db_tests.rs b/tests/db_tests.rs
index 490f869..b62e387 100644
--- a/tests/db_tests.rs
+++ b/tests/db_tests.rs
@@ -1,4 +1,4 @@
-use agtx::db::{Task, TaskStatus, Project};
+use agtx::db::{Database, Task, TaskStatus, Project};
// === TaskStatus Tests ===
@@ -92,6 +92,19 @@ fn test_task_unique_ids() {
assert_ne!(task1.id, task2.id);
}
+#[test]
+fn test_task_content_text_with_description() {
+ let mut task = Task::new("My Title", "claude", "proj");
+ task.description = Some("Detailed description".to_string());
+ assert_eq!(task.content_text(), "Detailed description");
+}
+
+#[test]
+fn test_task_content_text_without_description() {
+ let task = Task::new("My Title", "claude", "proj");
+ assert_eq!(task.content_text(), "My Title");
+}
+
// === Project Tests ===
#[test]
@@ -112,3 +125,70 @@ fn test_project_unique_ids() {
assert_ne!(project1.id, project2.id);
}
+
+// === In-Memory Database Tests ===
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_in_memory_project_db_creates_successfully() {
+ let db = Database::open_in_memory_project().unwrap();
+ // Should be able to create and retrieve a task
+ let task = Task::new("Test Task", "claude", "proj-1");
+ db.create_task(&task).unwrap();
+ let retrieved = db.get_task(&task.id).unwrap().unwrap();
+ assert_eq!(retrieved.title, "Test Task");
+ assert_eq!(retrieved.status, TaskStatus::Backlog);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_in_memory_project_db_update_task() {
+ let db = Database::open_in_memory_project().unwrap();
+ let mut task = Task::new("Original", "claude", "proj-1");
+ db.create_task(&task).unwrap();
+
+ task.status = TaskStatus::Running;
+ task.session_name = Some("session-1".to_string());
+ db.update_task(&task).unwrap();
+
+ let retrieved = db.get_task(&task.id).unwrap().unwrap();
+ assert_eq!(retrieved.status, TaskStatus::Running);
+ assert_eq!(retrieved.session_name.as_deref(), Some("session-1"));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_in_memory_project_db_list_tasks() {
+ let db = Database::open_in_memory_project().unwrap();
+ let task1 = Task::new("Task 1", "claude", "proj-1");
+ let task2 = Task::new("Task 2", "gemini", "proj-1");
+ db.create_task(&task1).unwrap();
+ db.create_task(&task2).unwrap();
+
+ let tasks = db.get_tasks_by_status(TaskStatus::Backlog).unwrap();
+ assert_eq!(tasks.len(), 2);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_in_memory_global_db_creates_successfully() {
+ let db = Database::open_in_memory_global().unwrap();
+ let project = Project::new("myproject", "/path/to/project");
+ db.upsert_project(&project).unwrap();
+ let projects = db.get_all_projects().unwrap();
+ assert_eq!(projects.len(), 1);
+ assert_eq!(projects[0].name, "myproject");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_in_memory_dbs_are_isolated() {
+ let db1 = Database::open_in_memory_project().unwrap();
+ let db2 = Database::open_in_memory_project().unwrap();
+ let task = Task::new("Only in db1", "claude", "proj-1");
+ db1.create_task(&task).unwrap();
+
+ // db2 should be empty β€” each in-memory DB is independent
+ let tasks = db2.get_tasks_by_status(TaskStatus::Backlog).unwrap();
+ assert_eq!(tasks.len(), 0);
+}