#!/bin/bash # claude-notify: Claude Code hook that shows a Windows toast (toastback) when a session needs you. # Needs bash, jq and toastback (https://github.com/gergodrazsdik/toastback). Register it for the events # below in ~/.claude/settings.json (see claude-notify-hooks.json next to this file). # # PermissionRequest remember what is being asked (no toast: you may be at the terminal) # Notification permission_prompt # (sent after ~6 s unanswered) "Allow Bash?" with the command, file, URL, plan # PreToolUse AskUserQuestion after CLAUDE_NOTIFY_QUESTION_DELAY s (5) unanswered: the question and its options # Stop "Claude finished" with the start of the reply, if the turn took at least # CLAUDE_NOTIFY_MIN_TURN s (30); shorter turns get the idle toast after ~60 s instead # StopFailure "Claude stopped: rate limit" etc. (API errors) # Notification idle_prompt "Claude is waiting for you" (skipped while a toast is already shown) # Notification elicitation_* an MCP server asks for input # UserPromptSubmit, PostToolUse, PostToolUseFailure, SessionEnd (and Stop) # remove the session's toast (and cancel a delayed one) once you've answered # # One toast id per session (claude-), so a newer toast replaces the older one. State lives in # $XDG_RUNTIME_DIR/claude-notify/: claude- (toast shown; holds its kind), pending- (delayed toast), # turn- (turn start), perm- (last permission request), last- (last reply excerpt). # Reads the hook JSON on stdin and never prints to stdout (PermissionRequest/PreToolUse would read it as a # decision). CLAUDE_NOTIFY=0 turns it off for a session. # Test: claude-notify --dry-run <<<'{"hook_event_name":"Notification","session_id":"x", # "notification_type":"idle_prompt","message":"Claude is waiting for your input","cwd":"/tmp"}' set -uo pipefail TOASTBACK=${TOASTBACK:-$HOME/.local/bin/toastback} STATE=${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/claude-notify MIN_TURN=${CLAUDE_NOTIFY_MIN_TURN:-30} QUESTION_DELAY=${CLAUDE_NOTIFY_QUESTION_DELAY:-5} # show SPEC KIND MARKER: show the toast and record it as shown show() { if (( dry )); then printf '%s\n' "$1" >&2; return; fi mkdir -p "$STATE" "$TOASTBACK" - <<<"$1" >/dev/null 2>&1 && printf '%s\n' "$2" >"$3" } # Delayed toast, started detached by the PreToolUse branch: --deliver PENDING_FILE TOKEN DELAY if [[ ${1:-} == --deliver ]]; then dry=0 pending=$2 token=$3 sleep "$4" [[ $(head -n1 "$pending" 2>/dev/null) == "$token" ]] || exit 0 spec=$(tail -n +2 "$pending") rm -f "$pending" show "$spec" question "${pending/\/pending-//claude-}" exit 0 fi [[ ${CLAUDE_NOTIFY:-1} == 0 ]] && { cat >/dev/null; exit 0; } dry=0 [[ ${1:-} == --dry-run ]] && dry=1 input=$(cat) event=$(jq -r '.hook_event_name // ""' <<<"$input") # Fast path for the most frequent event: nothing shown or scheduled, nothing to remove. if [[ $event == PostToolUse || $event == PostToolUseFailure ]] && ! compgen -G "$STATE/claude-*" >/dev/null \ && ! compgen -G "$STATE/pending-*" >/dev/null && ! compgen -G "$STATE/perm-*" >/dev/null; then exit 0 fi sid=$(jq -r '.session_id // ""' <<<"$input") [[ $sid =~ ^[A-Za-z0-9._-]{1,56}$ ]] || exit 0 id=claude-$sid marker=$STATE/$id pending=$STATE/pending-$sid turn=$STATE/turn-$sid perm=$STATE/perm-$sid last=$STATE/last-$sid # Remove the toast (if one is shown) and cancel a delayed one. clear_toast() { rm -f "$pending" "$perm" [[ -e $marker ]] || return 0 rm -f "$marker" if (( dry )); then echo "remove $id" >&2; return; fi "$TOASTBACK" remove "$id" >/dev/null 2>&1 || true } # Shared jq helpers: clip(n) squeezes whitespace and cuts to n chars; plain strips common markdown. # shellcheck disable=SC2016 # $vars are jq variables JQ_LIB=' def clip($n): gsub("\\s+"; " ") | ltrimstr(" ") | if length > $n then .[:$n - 1] + "…" else . end; def plain: gsub("\\[(?[^\\]]*)\\]\\([^)]*\\)"; "\(.t)") | gsub("[`*_#>|]"; ""); def project: .cwd // "" | if . == "" then "" else split("/") | map(select(. != "")) | last // "/" end; def attribution: project as $p | "Claude Code" + (if $p == "" then "" else " · " + $p end); ' # spec TITLE BODY [DETAILS [ICON]]: the toast spec as JSON spec() { jq -n --argjson in "$input" --arg id "$id" --arg title "$1" --arg body "$2" \ --arg details "${3:-}" --arg icon "${4:-}" "$JQ_LIB"' {id: $id, title: $title, body: $body, attribution: ($in | attribution), expires: "1h", notify_on_error: false} + (if $details == "" then {} else {details: $details} end) + (if $icon == "" then {} else {icon: $icon} end)' } case $event in UserPromptSubmit) clear_toast mkdir -p "$STATE" && date +%s >"$turn" ;; PostToolUse | PostToolUseFailure) clear_toast ;; SessionEnd) clear_toast rm -f "$turn" "$perm" "$last" ;; PermissionRequest) # Only remember the request: the Notification sent ~6 s later (if still unanswered) shows it. # AskUserQuestion comes through here too; its PreToolUse toast says more. [[ $(jq -r '.tool_name // ""' <<<"$input") == AskUserQuestion ]] && exit 0 mkdir -p "$STATE" jq "$JQ_LIB"' (.tool_name // "a tool") as $t | (.tool_input // {}) as $i | (.cwd // "") as $cwd | def rel: if $cwd != "" and startswith($cwd + "/") then .[($cwd | length) + 1:] else . end; ($t | if startswith("mcp__") then ltrimstr("mcp__") | split("__") | "\(.[0]) \(.[1:] | join("__"))" else . end) as $name | if $t == "ExitPlanMode" then {title: "Approve the plan?", full: ($i.plan // "")} | .body = (.full | plain | clip(220)) else (if $t == "Bash" then ($i.command // "") elif $i.file_path then ($i.file_path | rel) elif $i.notebook_path then ($i.notebook_path | rel) elif $i.url then $i.url elif $i.query then $i.query elif $i.pattern then $i.pattern elif $i.prompt then $i.prompt elif ($i | length) == 0 then "" else ($i | tojson) end) as $what | {title: "Allow \($name)?", body: ((if $t == "Bash" and ($i.description // "") != "" then ($i.description | clip(80)) + "\n" else "" end) + ($what | clip(200))), full: (if $t == "Bash" then $what else ($i | tojson) end)} end | .details = (if (.full | length) > 200 then .full[:4000] else "" end) | del(.full)' \ <<<"$input" >"$perm.tmp" && mv "$perm.tmp" "$perm" ;; PreToolUse) [[ $(jq -r '.tool_name // ""' <<<"$input") == AskUserQuestion ]] || exit 0 fields=$(jq "$JQ_LIB"' (.tool_input.questions // []) as $qs | ($qs[0] // {}) as $q | {title: (if ($q.header // "") != "" then "Claude asks: \($q.header)" else "Claude has a question" end), body: (($q.question // "" | clip(160)) + (if ($q.options // []) == [] then "" else "\n" + ([$q.options[].label] | join(" · ") | clip(120)) end) + (if ($qs | length) > 1 then "\n(+\(($qs | length) - 1) more)" else "" end)), details: ($qs | map("\(.question)\n" + ([.options[]? | " • \(.label)" + (if (.description // "") != "" then ": \(.description)" else "" end)] | join("\n"))) | join("\n\n"))}' <<<"$input") s=$(spec "$(jq -r .title <<<"$fields")" "$(jq -r .body <<<"$fields")" \ "$(jq -r .details <<<"$fields")" question) if (( dry )); then echo "after ${QUESTION_DELAY}s:" >&2; printf '%s\n' "$s" >&2; exit 0; fi token=$$-$EPOCHREALTIME mkdir -p "$STATE" printf '%s\n%s\n' "$token" "$s" >"$pending" setsid -f "$0" --deliver "$pending" "$token" "$QUESTION_DELAY" /dev/null 2>&1 ;; Stop) started=$(cat "$turn" 2>/dev/null || echo "") rm -f "$turn" clear_toast # e.g. a permission toast left after a denial ended the turn msg=$(jq -r "$JQ_LIB"'.last_assistant_message // "" | plain | clip(220)' <<<"$input") mkdir -p "$STATE" && printf '%s' "$msg" >"$last" [[ $started =~ ^[0-9]+$ ]] || exit 0 took=$(( $(date +%s) - started )) (( took >= MIN_TURN )) || exit 0 if (( took >= 60 )); then dur="$((took / 60))m $((took % 60))s"; else dur="${took}s"; fi show "$(spec "Claude finished ($dur)" "${msg:-Your turn.}" "" info)" stop "$marker" ;; StopFailure) rm -f "$turn" fields=$(jq "$JQ_LIB"' {title: ("Claude stopped: " + (.error // "unknown" | gsub("_"; " "))), body: ([.error_details, .last_assistant_message] | map(select(. != null and . != "") | clip(160)) | join("\n"))}' <<<"$input") show "$(spec "$(jq -r .title <<<"$fields")" "$(jq -r .body <<<"$fields")" "" error)" error "$marker" ;; Notification) ntype=$(jq -r '.notification_type // ""' <<<"$input") message=$(jq -r '.message // ""' <<<"$input") case $ntype in permission_prompt) # AskUserQuestion also waits on a dialog: its own toast says more. [[ -e $pending || $(cat "$marker" 2>/dev/null) == question ]] && exit 0 if [[ -s $perm ]] && [[ -n $(find "$perm" -mmin -10 2>/dev/null) ]]; then s=$(spec "$(jq -r .title "$perm")" "$(jq -r .body "$perm")" "$(jq -r .details "$perm")" question) else s=$(spec "Claude needs your permission" "$message" "" question) fi rm -f "$perm" show "$s" permission "$marker" ;; idle_prompt) [[ -e $marker || -e $pending ]] && exit 0 body=$(cat "$last" 2>/dev/null) show "$(spec "Claude is waiting for you" "${body:-$message}")" idle "$marker" ;; elicitation_dialog | elicitation_url_dialog) title=$(jq -r '.title // "An MCP server needs your input"' <<<"$input") show "$(spec "$title" "$message" "" question)" elicitation "$marker" ;; esac ;; esac exit 0