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: recover agent sessions after tmux/server restart (#66)

Pablo Speciale34827fadbe7b
diff --git a/src/agent/mod.rs b/src/agent/mod.rs
index 822bf1f..cc9141a 100644
--- a/src/agent/mod.rs
+++ b/src/agent/mod.rs
@@ -33,6 +33,20 @@ impl Agent {
which::which(&self.command).is_ok()
}
+ /// Build the shell command to resume the agent's most recent session
+ /// in the current working directory. Used to recover from tmux/server restarts.
+ pub fn build_resume_command(&self) -> String {
+ match self.name.as_str() {
+ "claude" => "claude --dangerously-skip-permissions --continue".to_string(),
+ "codex" => "codex resume --last".to_string(),
+ "copilot" => "copilot --allow-all-tools --continue".to_string(),
+ "gemini" => "gemini --approval-mode yolo --resume".to_string(),
+ "opencode" => "opencode --continue".to_string(),
+ "cursor" => "agent --yolo --continue".to_string(),
+ _ => self.build_interactive_command(""),
+ }
+ }
+
/// Build the shell command to start the agent interactively.
/// When prompt is empty, the agent starts with no initial message
/// (task content and skill commands are sent later via tmux send_keys).
@@ -154,24 +168,3 @@ pub fn parse_agent_selection(input: &str, agent_count: usize) -> Option<usize> {
None
}
-/// Build the command arguments for spawning an agent
-pub fn build_spawn_args(agent: &Agent, prompt: &str, task_id: &str) -> Vec<String> {
- let mut args = agent.args.clone();
-
- match agent.name.as_str() {
- "claude" => {
- // Claude Code supports session persistence
- args.extend(["--session".to_string(), task_id.to_string()]);
- args.push(prompt.to_string());
- }
- "copilot" => {
- args.extend(["-p".to_string(), prompt.to_string()]);
- }
- _ => {
- // Default: just pass the prompt
- args.push(prompt.to_string());
- }
- }
-
- args
-}
diff --git a/src/agent/operations.rs b/src/agent/operations.rs
index 3a4cab0..7ceebfa 100644
--- a/src/agent/operations.rs
+++ b/src/agent/operations.rs
@@ -28,6 +28,10 @@ pub trait AgentOperations: Send + Sync {
/// When prompt is empty, the agent starts with no initial message.
fn build_interactive_command(&self, prompt: &str) -> String;
+ /// Build the shell command to resume the agent's most recent session
+ /// in the current working directory. Used to recover from tmux/server restarts.
+ fn build_resume_command(&self) -> String;
+
/// Build the full shell command to run this agent as an orchestrator.
/// Includes MCP registration (if supported by the agent) and cleanup on exit.
/// Default implementation: no MCP, just launches the agent interactively.
@@ -81,6 +85,10 @@ impl AgentOperations for CodingAgent {
self.agent.build_interactive_command(prompt)
}
+ fn build_resume_command(&self) -> String {
+ self.agent.build_resume_command()
+ }
+
fn build_orchestrator_command(&self, mcp_json: &str, _agtx_bin: &str) -> String {
match self.agent.name.as_str() {
"claude" => format!(
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 264b99b..1624b86 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -628,6 +628,42 @@ impl App {
// Load projects from global database
app.refresh_projects()?;
+ // Recover tasks whose tmux windows were lost (server restart, manual kill, etc.)
+ {
+ let tasks_to_recover: Vec<_> = app
+ .state
+ .board
+ .tasks
+ .iter()
+ .filter(|t| {
+ matches!(
+ t.status,
+ TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review
+ ) && t.session_name.is_some()
+ && t.worktree_path.is_some()
+ })
+ .filter(|t| {
+ let sn = t.session_name.as_ref().unwrap();
+ !app.state.tmux_ops.window_exists(sn).unwrap_or(true)
+ })
+ .cloned()
+ .collect();
+
+ for task in &tasks_to_recover {
+ let agent_ops = app.state.agent_registry.get(&task.agent);
+ let _ = recover_task_session(
+ task,
+ &app.state.tmux_project_name,
+ app.state
+ .project_path
+ .as_deref()
+ .unwrap_or(Path::new(".")),
+ app.state.tmux_ops.as_ref(),
+ agent_ops.as_ref(),
+ );
+ }
+ }
+
// Detect existing orchestrator session (survives agtx restarts)
if app.state.flags.experimental {
let orch_target = format!("{}:orchestrator", app.state.tmux_project_name);
@@ -4910,8 +4946,15 @@ impl App {
let agent_registry = Arc::clone(&self.state.agent_registry);
let running_agent_clone = running_agent.clone();
let current_agent_clone = task.agent.clone();
+ let wt_path = task.worktree_path.clone();
std::thread::spawn(move || {
let agent_ops = agent_registry.get(&running_agent_clone);
+ ensure_window_or_recover(
+ tmux_ops.as_ref(),
+ &session_clone,
+ agent_ops.as_ref(),
+ wt_path.as_deref(),
+ );
let new_cmd = agent_ops.build_interactive_command("");
switch_agent_in_tmux(
tmux_ops.as_ref(),
@@ -4975,9 +5018,17 @@ impl App {
let auto_dismiss = plugin
.as_ref()
.map_or_else(Vec::new, |p| p.auto_dismiss.clone());
+ let wt_path = task.worktree_path.clone();
std::thread::spawn(move || {
+ let agent_ops = agent_registry.get(&planning_agent_clone);
+ // Recover window if it was lost
+ ensure_window_or_recover(
+ tmux_ops.as_ref(),
+ &session_clone,
+ agent_ops.as_ref(),
+ wt_path.as_deref(),
+ );
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(),
@@ -5027,8 +5078,15 @@ impl App {
let agent_registry = Arc::clone(&self.state.agent_registry);
let planning_agent_clone = planning_agent.clone();
let current_agent_clone = task.agent.clone();
+ let wt_path = task.worktree_path.clone();
std::thread::spawn(move || {
let agent_ops = agent_registry.get(&planning_agent_clone);
+ ensure_window_or_recover(
+ tmux_ops.as_ref(),
+ &session_clone,
+ agent_ops.as_ref(),
+ wt_path.as_deref(),
+ );
let new_cmd = agent_ops.build_interactive_command("");
switch_agent_in_tmux(
tmux_ops.as_ref(),
@@ -5403,6 +5461,31 @@ impl App {
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() {
+ // If the tmux window is gone, try to recover it before opening
+ if !self
+ .state
+ .tmux_ops
+ .window_exists(window_name)
+ .unwrap_or(true)
+ {
+ let agent_ops = self.state.agent_registry.get(&task.agent);
+ let project_path = self
+ .state
+ .project_path
+ .as_deref()
+ .unwrap_or(Path::new("."));
+ let _ = recover_task_session(
+ task,
+ &self.state.tmux_project_name,
+ project_path,
+ self.state.tmux_ops.as_ref(),
+ agent_ops.as_ref(),
+ );
+ // Clear stale phase status so it gets re-evaluated
+ self.state.phase_status_cache.remove(&task.id);
+ self.state.pane_content_hashes.remove(&task.id);
+ }
+
let task_id = task.id.clone();
let escalation_note = task.escalation_note.clone();
let mut popup = ShellPopup::new(task.title.clone(), window_name.clone());
@@ -5714,8 +5797,19 @@ impl App {
}
}
- // Capture tmux content hash for idle detection (only when Working)
- let content_hash = if phase_status == PhaseStatus::Working {
+ // Check if tmux window still exists β€” if not, mark as Exited
+ // (unless phase artifact was found, in which case it completed before the crash)
+ let window_gone = session_name
+ .as_ref()
+ .map_or(false, |sn| !tmux_ops.window_exists(sn).unwrap_or(true));
+ let phase_status = if window_gone && phase_status == PhaseStatus::Working {
+ PhaseStatus::Exited
+ } else {
+ phase_status
+ };
+
+ // Capture tmux content hash for idle detection (only when Working and window alive)
+ let content_hash = if phase_status == PhaseStatus::Working && !window_gone {
session_name.as_ref().and_then(|sn| {
tmux_ops.capture_pane(sn).ok().map(|content| {
use std::hash::{Hash, Hasher};
@@ -5767,6 +5861,8 @@ impl App {
}
} else if phase == PhaseStatus::Ready {
self.state.pane_content_hashes.remove(&task_status.task_id);
+ } else if phase == PhaseStatus::Exited {
+ self.state.pane_content_hashes.remove(&task_status.task_id);
}
let newly_ready = phase == PhaseStatus::Ready && !task_status.was_ready;
@@ -6059,6 +6155,43 @@ fn ensure_project_tmux_session(
}
}
+/// Recover a task's tmux session by creating a new window with the agent's resume command.
+/// Used when the tmux window has been lost (server restart, manual kill, etc.)
+/// but the task's worktree and agent session data still exist on disk.
+/// Returns the tmux target string on success.
+fn recover_task_session(
+ task: &Task,
+ project_name: &str,
+ project_path: &Path,
+ tmux_ops: &dyn TmuxOperations,
+ agent_ops: &dyn AgentOperations,
+) -> Result<String> {
+ let worktree_path = task
+ .worktree_path
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Task has no worktree path"))?;
+
+ if !Path::new(worktree_path).exists() {
+ anyhow::bail!("Worktree no longer exists: {}", worktree_path);
+ }
+
+ let target = task
+ .session_name
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Task has no session name"))?;
+ let (session, window) = target
+ .split_once(':')
+ .ok_or_else(|| anyhow::anyhow!("Invalid session name format: {}", target))?;
+
+ ensure_project_tmux_session(project_name, project_path, tmux_ops);
+
+ let resume_cmd = agent_ops.build_resume_command();
+
+ tmux_ops.create_window(session, window, worktree_path, Some(resume_cmd))?;
+
+ Ok(target.clone())
+}
+
/// Copy files/dirs from worktree back to project root.
/// Used by plugins with `[copy_back]` to sync artifacts after phase completion.
fn copy_back_to_project(worktree: &Path, project_root: &Path, entries: &[String]) {
@@ -7095,6 +7228,17 @@ fn spawn_send_to_agent(
plugin: Option<WorkflowPlugin>,
) {
std::thread::spawn(move || {
+ // If the tmux window is gone, recover it with the agent's resume command
+ {
+ let agent_ops = agent_registry.get(&target_agent);
+ ensure_window_or_recover(
+ tmux_ops.as_ref(),
+ &target,
+ agent_ops.as_ref(),
+ worktree_path.as_deref(),
+ );
+ }
+
if needs_switch {
// Deploy skills for the incoming agent only if its native skill directory
// doesn't exist yet. This handles the case where a worktree was created
@@ -7576,6 +7720,31 @@ fn is_agent_active(tmux_ops: &dyn TmuxOperations, target: &str) -> bool {
false
}
+/// If the tmux window for `target` is gone, recreate it with the agent's resume command.
+/// Used before `switch_agent_in_tmux` and `send_skill_and_prompt` to handle dead windows.
+fn ensure_window_or_recover(
+ tmux_ops: &dyn TmuxOperations,
+ target: &str,
+ agent_ops: &dyn AgentOperations,
+ worktree_path: Option<&str>,
+) {
+ if tmux_ops.window_exists(target).unwrap_or(true) {
+ return;
+ }
+ let Some(wt_path) = worktree_path else { return };
+ if !Path::new(wt_path).exists() {
+ return;
+ }
+ let Some((session, window)) = target.split_once(':') else {
+ return;
+ };
+ if !tmux_ops.has_session(session) {
+ let _ = tmux_ops.create_session(session, wt_path);
+ }
+ let resume_cmd = agent_ops.build_resume_command();
+ let _ = tmux_ops.create_window(session, window, wt_path, Some(resume_cmd));
+}
+
/// Gracefully switch the agent running in a tmux window.
/// Terminates the current agent, waits for the shell prompt,
/// then starts the new agent.
diff --git a/tests/agent_tests.rs b/tests/agent_tests.rs
index 6a85141..3fb4c9a 100644
--- a/tests/agent_tests.rs
+++ b/tests/agent_tests.rs
@@ -113,6 +113,49 @@ fn test_build_interactive_command_existing_agents_unchanged() {
);
}
+// =============================================================================
+// Tests for build_resume_command
+// =============================================================================
+
+#[test]
+fn test_build_resume_command_all_agents() {
+ let agents = known_agents();
+ let by_name = |n: &str| agents.iter().find(|a| a.name == n).unwrap().clone();
+
+ assert_eq!(
+ by_name("claude").build_resume_command(),
+ "claude --dangerously-skip-permissions --continue"
+ );
+ assert_eq!(
+ by_name("codex").build_resume_command(),
+ "codex resume --last"
+ );
+ assert_eq!(
+ by_name("copilot").build_resume_command(),
+ "copilot --allow-all-tools --continue"
+ );
+ assert_eq!(
+ by_name("gemini").build_resume_command(),
+ "gemini --approval-mode yolo --resume"
+ );
+ assert_eq!(
+ by_name("opencode").build_resume_command(),
+ "opencode --continue"
+ );
+ assert_eq!(
+ by_name("cursor").build_resume_command(),
+ "agent --yolo --continue"
+ );
+}
+
+#[test]
+fn test_build_resume_command_unknown_agent_falls_back_to_interactive() {
+ use agtx::agent::Agent;
+ let agent = Agent::new("custom-agent", "my-agent", "A custom agent", "Custom <[email protected]>");
+ // Unknown agent should fall back to build_interactive_command("")
+ assert_eq!(agent.build_resume_command(), agent.build_interactive_command(""));
+}
+
// =============================================================================
// Tests for cursor skill integration
// =============================================================================