#!/bin/bash
# Emit one line whenever a watched Claude session finishes a turn, opens a selection dialog or shows an API error.
# Meant as the command of the Monitor tool (one line = one notification). Usage: cc-watch %446 %448 ...
set -uo pipefail
state=$(mktemp -d)
mark() { tmux capture-pane -p -t "$1" 2>/dev/null | grep -oE 'done [0-9]{1,2}:[0-9]{2}|Enter to select|API Error' | tail -1; }
for p in "$@"; do mark "$p" > "$state/${p#%}"; done
while true; do
  for p in "$@"; do
    t=$(mark "$p")
    if [[ -n $t && $t != "$(cat "$state/${p#%}")" ]]; then
      echo "$p $(tmux display -p -t "$p" '#{window_name}' 2>/dev/null | cut -c1-40): $t"
      echo "$t" > "$state/${p#%}"
    fi
  done
  sleep 15
done
