use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde_json::{json, Map, Value};
const HOOK_SCRIPT: &str = r#"#!/usr/bin/env bash
# TmuxTango status hook for Claude Code
# Writes pane status to /tmp/tango-status/ for TmuxTango to read.
set -e
PANE_ID="${TMUX_PANE:-}"
[ -z "$PANE_ID" ] && exit 0
STATUS_DIR="/tmp/tango-status"
mkdir -p "$STATUS_DIR"
PANE_FILE="${STATUS_DIR}/${PANE_ID//%/_}"
INPUT=$(cat)
EVENT=$(printf '%s' "$INPUT" | sed -n 's/.*"hook_event_name":"\([^"]*\)".*/\1/p')
case "$EVENT" in
UserPromptSubmit|PreToolUse)
printf 'active' > "$PANE_FILE" ;;
Stop)
printf 'idle' > "$PANE_FILE" ;;
Notification)
TYPE=$(printf '%s' "$INPUT" | sed -n 's/.*"notification_type":"\([^"]*\)".*/\1/p')
case "$TYPE" in
permission_prompt|elicitation_dialog) printf 'waiting' > "$PANE_FILE" ;;
idle_prompt) printf 'idle' > "$PANE_FILE" ;;
esac ;;
esac
"#;
const TANGO_MARKER: &str = "_tango_managed";
const EVENTS: &[(&str, &str)] = &[
("UserPromptSubmit", ""),
("PreToolUse", ""),
("Stop", ""),
("Notification", "permission_prompt|idle_prompt|elicitation_dialog"),
];
fn hook_script_path() -> Result<PathBuf> {
Ok(hook_script_path_in(&home_dir()?))
}
fn hook_script_path_in(home: &Path) -> PathBuf {
home.join(".config").join("tango").join("status-hook.sh")
}
fn claude_settings_path() -> Result<PathBuf> {
Ok(claude_settings_path_in(&home_dir()?))
}
fn claude_settings_path_in(home: &Path) -> PathBuf {
home.join(".claude").join("settings.json")
}
fn home_dir() -> Result<PathBuf> {
std::env::var("HOME")
.map(PathBuf::from)
.context("HOME environment variable not set")
}
fn normalize_path_str(s: &str, home: &Path) -> String {
let home_str = home.to_string_lossy();
let home_trimmed = home_str.trim_end_matches('/');
if let Some(rest) = s.strip_prefix("$HOME/") {
return format!("{}/{}", home_trimmed, rest);
}
if let Some(rest) = s.strip_prefix("${HOME}/") {
return format!("{}/{}", home_trimmed, rest);
}
if let Some(rest) = s.strip_prefix("~/") {
return format!("{}/{}", home_trimmed, rest);
}
s.to_string()
}
fn portable_script_path_string(script_path: &Path, home: &Path) -> String {
let script = script_path.to_string_lossy();
if let Ok(rest) = script_path.strip_prefix(home) {
return format!("$HOME/{}", rest.to_string_lossy());
}
script.to_string()
}
fn command_matches_script(command: &str, script_path: &Path, home: &Path) -> bool {
normalize_path_str(command, home) == script_path.to_string_lossy()
}
fn tango_hook_entry(script_path: &Path, home: &Path) -> Value {
json!({
"type": "command",
"command": portable_script_path_string(script_path, home)
})
}
fn tango_rule(script_path: &Path, matcher: &str, home: &Path) -> Value {
json!({
TANGO_MARKER: true,
"matcher": matcher,
"hooks": [tango_hook_entry(script_path, home)]
})
}
fn rule_is_tango(rule: &Value, script_path: &Path, home: &Path) -> bool {
if rule
.get(TANGO_MARKER)
.and_then(|v| v.as_bool())
.unwrap_or(false)
{
return true;
}
rule.get("hooks")
.and_then(|h| h.as_array())
.map_or(false, |arr| {
arr.iter().any(|entry| {
entry
.get("command")
.and_then(|c| c.as_str())
.map_or(false, |cmd| command_matches_script(cmd, script_path, home))
})
})
}
fn read_settings(path: &Path) -> Result<Value> {
if !path.exists() {
return Ok(json!({}));
}
let content = fs::read_to_string(path).context("Failed to read Claude settings")?;
if content.trim().is_empty() {
return Ok(json!({}));
}
serde_json::from_str(&content).context("Failed to parse Claude settings.json")
}
fn write_settings(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).context("Failed to create .claude directory")?;
}
let content = serde_json::to_string_pretty(value).context("Failed to serialize settings")?;
fs::write(path, content + "\n").context("Failed to write Claude settings")?;
Ok(())
}
fn strip_tango_rules(hooks: &mut Map<String, Value>, script_path: &Path, home: &Path) {
for (_event, rules) in hooks.iter_mut() {
if let Some(arr) = rules.as_array_mut() {
arr.retain(|rule| !rule_is_tango(rule, script_path, home));
}
}
hooks.retain(|_k, v| v.as_array().map_or(true, |a| !a.is_empty()));
}
fn is_canonical(hooks: &Map<String, Value>, script_path: &Path, home: &Path) -> bool {
let expected_command = portable_script_path_string(script_path, home);
for (event, expected_matcher) in EVENTS {
let rules = match hooks.get(*event).and_then(|v| v.as_array()) {
Some(arr) => arr,
None => return false,
};
let ours: Vec<&Value> = rules
.iter()
.filter(|r| rule_is_tango(r, script_path, home))
.collect();
if ours.len() != 1 {
return false;
}
let rule = ours[0];
if !rule
.get(TANGO_MARKER)
.and_then(|v| v.as_bool())
.unwrap_or(false)
{
return false;
}
if rule.get("matcher").and_then(|m| m.as_str()) != Some(*expected_matcher) {
return false;
}
let commands: Vec<&str> = rule
.get("hooks")
.and_then(|h| h.as_array())
.map_or(vec![], |arr| {
arr.iter()
.filter_map(|e| e.get("command").and_then(|c| c.as_str()))
.collect()
});
if commands.len() != 1 || commands[0] != expected_command {
return false;
}
}
true
}
pub fn install() -> Result<()> {
install_quiet()?;
let script_path = hook_script_path()?;
let settings_path = claude_settings_path()?;
println!("Hook script installed to {}", script_path.display());
println!("Claude Code settings updated at {}", settings_path.display());
println!("\nStatus monitoring hooks are now active for new Claude Code sessions.");
println!("Existing sessions need to be restarted to pick up the hooks.");
Ok(())
}
pub fn ensure_installed() {
if is_installed().unwrap_or(false) {
return;
}
let _ = install_quiet();
}
fn is_installed() -> Result<bool> {
let home = home_dir()?;
let script_path = hook_script_path_in(&home);
let settings_path = claude_settings_path_in(&home);
if !script_path.exists() || !settings_path.exists() {
return Ok(false);
}
let settings = read_settings(&settings_path)?;
Ok(settings
.get("hooks")
.and_then(|h| h.as_object())
.map_or(false, |hooks| is_canonical(hooks, &script_path, &home)))
}
fn install_quiet() -> Result<()> {
let home = home_dir()?;
let script_path = hook_script_path_in(&home);
let settings_path = claude_settings_path_in(&home);
install_into(&home, &script_path, &settings_path)
}
fn install_into(home: &Path, script_path: &Path, settings_path: &Path) -> Result<()> {
if let Some(parent) = script_path.parent() {
fs::create_dir_all(parent).context("Failed to create config directory")?;
}
fs::write(script_path, HOOK_SCRIPT).context("Failed to write hook script")?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(script_path, fs::Permissions::from_mode(0o755))
.context("Failed to set hook script permissions")?;
}
let mut settings = read_settings(settings_path)?;
let hooks = settings
.as_object_mut()
.context("Settings is not a JSON object")?
.entry("hooks")
.or_insert_with(|| json!({}))
.as_object_mut()
.context("hooks is not a JSON object")?;
strip_tango_rules(hooks, script_path, home);
for (event, matcher) in EVENTS {
let rule = tango_rule(script_path, matcher, home);
let arr = hooks
.entry(*event)
.or_insert_with(|| json!([]))
.as_array_mut()
.context("Hook event entry is not an array")?;
arr.push(rule);
}
write_settings(settings_path, &settings)?;
Ok(())
}
pub fn uninstall() -> Result<()> {
let home = home_dir()?;
let script_path = hook_script_path_in(&home);
let settings_path = claude_settings_path_in(&home);
if settings_path.exists() {
let mut settings = read_settings(&settings_path)?;
if let Some(hooks) = settings
.as_object_mut()
.and_then(|obj| obj.get_mut("hooks"))
.and_then(|h| h.as_object_mut())
{
strip_tango_rules(hooks, &script_path, &home);
if hooks.is_empty() {
settings.as_object_mut().unwrap().remove("hooks");
}
}
write_settings(&settings_path, &settings)?;
println!("Removed TmuxTango hooks from {}", settings_path.display());
}
if script_path.exists() {
fs::remove_file(&script_path).context("Failed to remove hook script")?;
println!("Removed hook script at {}", script_path.display());
}
if let Some(parent) = script_path.parent() {
let _ = fs::remove_dir(parent);
}
println!("\nTmuxTango hooks have been uninstalled.");
Ok(())
}
pub fn status() -> Result<()> {
let home = home_dir()?;
let script_path = hook_script_path_in(&home);
let settings_path = claude_settings_path_in(&home);
let script_installed = script_path.exists();
let (hooks_registered, hooks_canonical) = if settings_path.exists() {
let settings = read_settings(&settings_path)?;
let hooks = settings.get("hooks").and_then(|h| h.as_object());
let any_marker = hooks.map_or(false, |h| {
h.values().any(|rules| {
rules.as_array().map_or(false, |arr| {
arr.iter()
.any(|rule| rule_is_tango(rule, &script_path, &home))
})
})
});
let canonical = hooks.map_or(false, |h| is_canonical(h, &script_path, &home));
(any_marker, canonical)
} else {
(false, false)
};
if script_installed && hooks_canonical {
println!("TmuxTango hooks: installed");
println!(" Script: {}", script_path.display());
println!(" Settings: {}", settings_path.display());
} else if script_installed && hooks_registered {
println!("TmuxTango hooks: installed with stale or duplicate entries");
println!(" Run `tango hooks install` to migrate to the canonical form.");
} else if script_installed {
println!("TmuxTango hooks: partially installed (script exists but not registered)");
println!(" Run `tango hooks install` to complete installation.");
} else if hooks_registered {
println!("TmuxTango hooks: partially installed (registered but script missing)");
println!(" Run `tango hooks install` to complete installation.");
} else {
println!("TmuxTango hooks: not installed");
println!(" Run `tango hooks install` to enable hook-based status detection.");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn fake_home() -> (tempfile::TempDir, PathBuf) {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().to_path_buf();
(dir, home)
}
#[test]
fn test_normalize_path_str_expands_home_variants() {
let home = Path::new("/home/alice");
assert_eq!(
normalize_path_str("$HOME/.config/tango/status-hook.sh", home),
"/home/alice/.config/tango/status-hook.sh"
);
assert_eq!(
normalize_path_str("${HOME}/.config/tango/status-hook.sh", home),
"/home/alice/.config/tango/status-hook.sh"
);
assert_eq!(
normalize_path_str("~/.config/tango/status-hook.sh", home),
"/home/alice/.config/tango/status-hook.sh"
);
assert_eq!(
normalize_path_str("/home/alice/.config/tango/status-hook.sh", home),
"/home/alice/.config/tango/status-hook.sh"
);
assert_eq!(normalize_path_str("other.sh", home), "other.sh");
}
#[test]
fn test_portable_path_when_under_home() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
assert_eq!(
portable_script_path_string(&script, home),
"$HOME/.config/tango/status-hook.sh"
);
}
#[test]
fn test_portable_path_outside_home() {
let home = Path::new("/home/alice");
let script = Path::new("/opt/tango/status-hook.sh");
assert_eq!(
portable_script_path_string(script, home),
"/opt/tango/status-hook.sh"
);
}
#[test]
fn test_command_matches_script_across_forms() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
assert!(command_matches_script(
"$HOME/.config/tango/status-hook.sh",
&script,
home
));
assert!(command_matches_script(
"~/.config/tango/status-hook.sh",
&script,
home
));
assert!(command_matches_script(
"/home/alice/.config/tango/status-hook.sh",
&script,
home
));
assert!(!command_matches_script("/usr/bin/unrelated", &script, home));
}
#[test]
fn test_tango_rule_has_marker_and_portable_command() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
let rule = tango_rule(&script, "", home);
assert_eq!(rule[TANGO_MARKER], true);
assert_eq!(rule["matcher"], "");
assert_eq!(
rule["hooks"][0]["command"],
"$HOME/.config/tango/status-hook.sh"
);
}
#[test]
fn test_strip_removes_marked_rules() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
let mut hooks = Map::new();
hooks.insert(
"Stop".to_string(),
json!([
{ TANGO_MARKER: true, "matcher": "", "hooks": [] },
{ "matcher": "", "hooks": [{ "type": "command", "command": "other.sh" }] }
]),
);
strip_tango_rules(&mut hooks, &script, home);
let stop = hooks.get("Stop").unwrap().as_array().unwrap();
assert_eq!(stop.len(), 1);
assert!(stop[0].get(TANGO_MARKER).is_none());
}
#[test]
fn test_strip_removes_unmarked_entries_by_path() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
let mut hooks = Map::new();
hooks.insert(
"Stop".to_string(),
json!([
{
"matcher": "",
"hooks": [{ "type": "command", "command": "/home/alice/.config/tango/status-hook.sh" }]
},
{
"matcher": "",
"hooks": [{ "type": "command", "command": "other.sh" }]
}
]),
);
strip_tango_rules(&mut hooks, &script, home);
let stop = hooks.get("Stop").unwrap().as_array().unwrap();
assert_eq!(stop.len(), 1);
assert_eq!(stop[0]["hooks"][0]["command"], "other.sh");
}
#[test]
fn test_strip_removes_home_form_entry() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
let mut hooks = Map::new();
hooks.insert(
"Stop".to_string(),
json!([
{
"matcher": "",
"hooks": [{ "type": "command", "command": "$HOME/.config/tango/status-hook.sh" }]
}
]),
);
strip_tango_rules(&mut hooks, &script, home);
assert!(!hooks.contains_key("Stop"));
}
#[test]
fn test_strip_removes_tilde_form_entry() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
let mut hooks = Map::new();
hooks.insert(
"Stop".to_string(),
json!([
{
"matcher": "",
"hooks": [{ "type": "command", "command": "~/.config/tango/status-hook.sh" }]
}
]),
);
strip_tango_rules(&mut hooks, &script, home);
assert!(!hooks.contains_key("Stop"));
}
#[test]
fn test_strip_preserves_other_scripts() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
let mut hooks = Map::new();
hooks.insert(
"Stop".to_string(),
json!([
{
"matcher": "",
"hooks": [{ "type": "command", "command": "/usr/bin/my-other-hook" }]
}
]),
);
strip_tango_rules(&mut hooks, &script, home);
let stop = hooks.get("Stop").unwrap().as_array().unwrap();
assert_eq!(stop.len(), 1);
}
#[test]
fn test_strip_removes_empty_events() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
let mut hooks = Map::new();
hooks.insert(
"Stop".to_string(),
json!([{ TANGO_MARKER: true, "matcher": "", "hooks": [] }]),
);
strip_tango_rules(&mut hooks, &script, home);
assert!(!hooks.contains_key("Stop"));
}
#[test]
fn test_is_canonical_true_after_fresh_install() {
let (_dir, home) = fake_home();
let script_path = hook_script_path_in(&home);
let settings_path = claude_settings_path_in(&home);
install_into(&home, &script_path, &settings_path).unwrap();
let settings = read_settings(&settings_path).unwrap();
let hooks = settings.get("hooks").unwrap().as_object().unwrap();
assert!(is_canonical(hooks, &script_path, &home));
}
#[test]
fn test_is_canonical_false_on_legacy_duplicates() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
let mut hooks = Map::new();
for (event, matcher) in EVENTS {
hooks.insert(
event.to_string(),
json!([
{ "matcher": matcher, "hooks": [{ "type": "command", "command": "/home/alice/.config/tango/status-hook.sh" }] },
{ "matcher": matcher, "hooks": [{ "type": "command", "command": "/home/alice/.config/tango/status-hook.sh" }] },
{ TANGO_MARKER: true, "matcher": matcher, "hooks": [{ "type": "command", "command": "$HOME/.config/tango/status-hook.sh" }] }
]),
);
}
assert!(!is_canonical(&hooks, &script, home));
}
#[test]
fn test_is_canonical_false_when_missing_event() {
let home = Path::new("/home/alice");
let script = home.join(".config/tango/status-hook.sh");
let mut hooks = Map::new();
hooks.insert(
"Stop".to_string(),
json!([
{ TANGO_MARKER: true, "matcher": "", "hooks": [{ "type": "command", "command": "$HOME/.config/tango/status-hook.sh" }] }
]),
);
assert!(!is_canonical(&hooks, &script, home));
}
#[test]
fn test_install_is_idempotent() {
let (_dir, home) = fake_home();
let script_path = hook_script_path_in(&home);
let settings_path = claude_settings_path_in(&home);
install_into(&home, &script_path, &settings_path).unwrap();
let first = fs::read_to_string(&settings_path).unwrap();
install_into(&home, &script_path, &settings_path).unwrap();
let second = fs::read_to_string(&settings_path).unwrap();
assert_eq!(first, second, "second install must not modify settings.json");
let settings: Value = serde_json::from_str(&second).unwrap();
let hooks = settings.get("hooks").unwrap().as_object().unwrap();
for (event, _) in EVENTS {
let arr = hooks.get(*event).unwrap().as_array().unwrap();
assert_eq!(arr.len(), 1, "event {} should have exactly one rule", event);
}
}
#[test]
fn test_install_migrates_legacy_duplicates() {
let (_dir, home) = fake_home();
let script_path = hook_script_path_in(&home);
let settings_path = claude_settings_path_in(&home);
let expanded = script_path.to_string_lossy().to_string();
let mut hooks = Map::new();
for (event, matcher) in EVENTS {
let dup = json!({
"matcher": matcher,
"hooks": [{ "type": "command", "command": expanded }]
});
let dup_home = json!({
"matcher": matcher,
"hooks": [{ "type": "command", "command": "$HOME/.config/tango/status-hook.sh" }]
});
let marked = json!({
TANGO_MARKER: true,
"matcher": matcher,
"hooks": [{ "type": "command", "command": expanded }]
});
hooks.insert(
event.to_string(),
json!([dup_home, dup.clone(), dup.clone(), dup.clone(), dup, marked]),
);
}
let stop = hooks.get_mut("Stop").unwrap().as_array_mut().unwrap();
stop.push(json!({
"matcher": "",
"hooks": [{ "type": "command", "command": "/usr/local/bin/my-custom-hook" }]
}));
let initial = json!({ "hooks": hooks });
fs::create_dir_all(settings_path.parent().unwrap()).unwrap();
write_settings(&settings_path, &initial).unwrap();
install_into(&home, &script_path, &settings_path).unwrap();
let after = read_settings(&settings_path).unwrap();
let hooks_after = after.get("hooks").unwrap().as_object().unwrap();
assert!(is_canonical(hooks_after, &script_path, &home));
let stop_after = hooks_after.get("Stop").unwrap().as_array().unwrap();
let custom_survived = stop_after.iter().any(|r| {
r.get("hooks")
.and_then(|h| h.as_array())
.map_or(false, |arr| {
arr.iter().any(|e| {
e.get("command").and_then(|c| c.as_str())
== Some("/usr/local/bin/my-custom-hook")
})
})
});
assert!(custom_survived, "unrelated user hook must survive install");
}
#[test]
fn test_read_settings_missing_file() {
let result = read_settings(Path::new("/tmp/nonexistent_tango_test_settings.json"));
assert!(result.is_ok());
assert_eq!(result.unwrap(), json!({}));
}
#[test]
fn test_read_settings_empty_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
fs::write(&path, "").unwrap();
let result = read_settings(&path);
assert!(result.is_ok());
assert_eq!(result.unwrap(), json!({}));
}
#[test]
fn test_read_write_roundtrip() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
let value = json!({"hooks": {"Stop": []}});
write_settings(&path, &value).unwrap();
let read_back = read_settings(&path).unwrap();
assert_eq!(read_back, value);
}
}