fix(daemon): SIGTERM/SIGKILL when switch_agent quit signals don't land

execute_switch_agent sent /exit then Ctrl+C, but Claude's TUI swallows
both when it's busy mid-task — so the new-agent launch_cmd was typed
into the live old agent (claude received "cd /path && agent" as a
prompt instead of bash executing it). Verified live: ran switch claude→
cursor, daemon logged "done ✓" but the old claude PID was still alive
and cursor never started.

Add _kill_agents_in_dir as the escalation path: after the existing
quit+Ctrl+C dance, if the agent is still running in the project dir,
SIGTERM the PIDs (basename-matched, cwd-scoped), wait 1.5s, then SIGKILL
the holdouts. Only fires when the gentler signals didn't land, so
well-behaved CLIs (grok, codex, openclaw) keep their clean exit path.
This commit is contained in:
g-but committed 2026-05-31 00:03:56 +02:00
1 parent d6215feda6
commit 0ccb43d6ec
1 file changed
+33
+33
View File
@@ -488,6 +488,24 @@ _is_agent_running_in_dir() {
[ "$found" = "1" ]
}
# Kill (sig = TERM/KILL) every process whose basename matches the agent and
# whose cwd lives in $dir. Used as the escalation path for switch_agent when
# the agent TUI ignored /exit + Ctrl+C.
_kill_agents_in_dir() {
local agent="$1" dir="$2" sig="${3:-TERM}"
_scan_agents 2>/dev/null | while IFS=' ' read -r cwd aname; do
[ "$aname" = "$agent" ] || continue
[ "$cwd" = "$dir" ] || [[ "$cwd" == "$dir/"* ]] || continue
# Find the PIDs whose cwd matches (one agent name can have multiple processes;
# _scan_agents already filtered by basename + cwd, but it emits one line per match).
for pd in /proc/[0-9]*/; do
local p="${pd%/}"; p="${p##*/}"
[ "$(readlink "$pd/cwd" 2>/dev/null)" = "$cwd" ] || continue
kill -s "$sig" "$p" 2>/dev/null || true
done
done
}
execute_switch_agent() {
local id="$1" tab="$2" dir="$3" to_agent="$4" from_agent="${5:-}" model="${6:-}"
@@ -528,6 +546,21 @@ execute_switch_agent() {
sleep 0.6
fi
fi
# Escalation: if the agent TUI swallowed /exit + Ctrl+C (Claude when busy,
# for example), the new-agent launch would be typed *into* the live old
# agent. Send SIGTERM, then SIGKILL, to the agent processes whose cwd is
# this project dir so the launch lands in a bare shell.
if _is_agent_running_in_dir "$from_agent" "$dir"; then
log "switch_agent: $from_agent still alive — SIGTERM on its PIDs"
_kill_agents_in_dir "$from_agent" "$dir" TERM
sleep 1.5
if _is_agent_running_in_dir "$from_agent" "$dir"; then
log "switch_agent: $from_agent still alive — SIGKILL"
_kill_agents_in_dir "$from_agent" "$dir" KILL
sleep 0.5
fi
fi
fi
if inject_prompt "$tab" "$launch_cmd" 2>/dev/null; then