diff --git a/agent.sh b/agent.sh index e7eb913..6ef7f2f 100755 --- a/agent.sh +++ b/agent.sh @@ -41,5 +41,17 @@ else tmux set-window-option -t agent @agent_dir "$dir" fi +# Prune windows whose recorded directory no longer exists. This runs after the +# current directory's window is guaranteed to exist, so the session always +# keeps at least one live window and is never killed out from under us. +for window_id in $(tmux list-windows -t agent -F '#{window_id}'); do + window_dir=$(tmux show-window-option -t "$window_id" -v @agent_dir 2>/dev/null || true) + # Skip windows with no recorded directory rather than risk pruning them. + [ -n "$window_dir" ] || continue + if [ ! -d "$window_dir" ]; then + tmux kill-window -t "$window_id" 2>/dev/null || true + fi +done + # Attach to the session tmux attach-session -t agent