crates/dinggerd/src/watcher.rs (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 |
//! Poll-and-detect loop: tmux pane capture → detection engine → herdr's
//! status model → notifications and pane-option write-back.
//!
//! Status model (herdr's, verbatim): five display statuses over two inputs,
//! the raw agent state (working/blocked/idle, from hooks or scraping) and a
//! `seen` flag:
//!
//! | raw | seen | display | priority |
//! |----------|--------|----------|----------|
//! | working | any | working | 2 |
//! | blocked | any | blocked | 4 |
//! | idle | false | done | 3 |
//! | idle | true | idle | 1 |
//! | none | any | unknown | 0 |
//!
//! `seen` follows herdr's `apply_pane_state_change` and
//! `mark_active_tab_seen` (src/app/actions.rs); see [`advance`].
//!
//! All per-pane state lives in tmux pane options, so a daemon restart picks
//! up exactly where it left off:
//!
//! - `@agent_state` display status (what every surface renders)
//! - `@dingger_since` unix ms the pane started needing the user (FIFO)
//! - `@dingger_hook` last state an agent extension reported
//! - `@dingger_ack` one-shot "the user jumped here" event from `dingger focus`
use std::collections::HashMap;
use detect_core::{detect_agent_with_osc, AgentState};
use tracing::{debug, info, warn};
use crate::hooks;
use crate::notify::{play_sound, send_notification, NotificationKind};
use crate::tmux;
/// herdr's display statuses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
Unknown,
Idle,
Working,
Done,
Blocked,
}
impl Status {
pub fn label(self) -> &'static str {
match self {
Status::Unknown => "unknown",
Status::Idle => "idle",
Status::Working => "working",
Status::Done => "done",
Status::Blocked => "blocked",
}
}
pub fn from_label(label: &str) -> Status {
match label {
"idle" => Status::Idle,
"working" => Status::Working,
"done" => Status::Done,
"blocked" => Status::Blocked,
_ => Status::Unknown,
}
}
/// herdr's priority: blocked > done > working > idle > unknown.
pub fn priority(self) -> u8 {
match self {
Status::Blocked => 4,
Status::Done => 3,
Status::Working => 2,
Status::Idle => 1,
Status::Unknown => 0,
}
}
}
/// herdr's notification policy (`notification_toast_for_state_change`),
/// driven by raw state transitions.
pub fn notification_kind_for_transition(
prev_state: AgentState,
new_state: AgentState,
) -> Option<NotificationKind> {
if new_state == prev_state {
return None;
}
match new_state {
AgentState::Blocked => Some(NotificationKind::NeedsAttention),
AgentState::Idle if matches!(prev_state, AgentState::Working | AgentState::Blocked) => {
Some(NotificationKind::Finished)
}
_ => None,
}
}
/// herdr's per-pane attendance record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PaneTrack {
pub state: AgentState,
pub seen: bool,
/// Unix millisecond the pane started needing the user (done or blocked);
/// orders the FIFO queue within a status.
pub since: Option<u64>,
}
impl PaneTrack {
/// A pane not observed yet. herdr: `PaneState::new` starts `seen = true`.
pub const NEW: PaneTrack = PaneTrack {
state: AgentState::Unknown,
seen: true,
since: None,
};
pub fn status(&self) -> Status {
match (self.state, self.seen) {
(AgentState::Working, _) => Status::Working,
(AgentState::Blocked, _) => Status::Blocked,
(AgentState::Idle, false) => Status::Done,
(AgentState::Idle, true) => Status::Idle,
(AgentState::Unknown, _) => Status::Unknown,
}
}
/// Rebuild a track from the pane options a previous daemon wrote.
fn restore(written_state: &str, written_since: &str) -> PaneTrack {
let since = written_since.trim().parse::<u64>().ok();
let (state, seen) = match written_state {
"done" => (AgentState::Idle, false),
"idle" => (AgentState::Idle, true),
"working" => (AgentState::Working, true),
"blocked" => (AgentState::Blocked, true),
_ => return PaneTrack::NEW,
};
let track = PaneTrack { state, seen, since };
let needs_user = matches!(track.status(), Status::Done | Status::Blocked);
PaneTrack {
since: if needs_user { since } else { None },
..track
}
}
}
/// One observation step for a pane: herdr's `apply_pane_state_change`
/// followed by `mark_active_tab_seen`, as a pure function.
///
/// - Transition to any non-idle state: seen.
/// - Completion (working/blocked to idle): seen only if the user is looking
/// at the pane's window; otherwise the pane is done.
/// - Any other transition to idle (first observation): seen unchanged.
/// - Looking at the pane's window, or jumping to it (`acked`): seen.
pub fn advance(
prev: PaneTrack,
observed: AgentState,
attended: bool,
acked: bool,
now: u64,
) -> PaneTrack {
let mut next = prev;
if observed != prev.state {
next.state = observed;
if observed != AgentState::Idle {
next.seen = true;
} else if matches!(prev.state, AgentState::Working | AgentState::Blocked) {
next.seen = attended;
}
next.since = None; // a new episode
}
if attended || acked {
next.seen = true;
}
let needs_user = matches!(next.status(), Status::Done | Status::Blocked);
next.since = match (needs_user, next.since) {
(true, Some(since)) => Some(since),
(true, None) => Some(now),
(false, _) => None,
};
next
}
pub struct Watcher {
tracks: HashMap<String, PaneTrack>,
/// Last published (queue, blocked, done, working); avoids rewriting the
/// global options every tick.
last_published: Option<(String, usize, usize, usize)>,
interval_secs: u64,
sounds: bool,
notifications: bool,
}
impl Watcher {
pub fn new(interval_secs: u64, sounds: bool, notifications: bool) -> Self {
Self {
tracks: HashMap::new(),
last_published: None,
interval_secs: interval_secs.max(1),
sounds,
notifications,
}
}
pub fn run(&mut self) -> Result<(), String> {
info!(interval = self.interval_secs, "watching tmux panes");
// dingger is a client of the tmux server, which may not exist yet:
// it starts when the first terminal opens one. Wait for it, then
// keep watching across server restarts.
let mut had_server = false;
loop {
let started = std::time::Instant::now();
match self.tick() {
Ok(()) => {
if !had_server {
info!("tmux server available");
had_server = true;
}
}
Err(err) => {
if had_server {
warn!(%err, "tmux server unavailable; waiting for it to return");
}
had_server = false;
}
}
debug!(ms = started.elapsed().as_millis() as u64, "tick");
hooks::wait_for_wake(std::time::Duration::from_secs(self.interval_secs));
}
}
fn tick(&mut self) -> Result<(), String> {
let panes = tmux::list_panes()?;
let now = unix_now();
// Forget panes that went away.
self.tracks
.retain(|pane_id, _| panes.iter().any(|pane| pane.pane_id == *pane_id));
hooks::forget(&panes.iter().map(|pane| pane.pane_id.clone()).collect::<Vec<_>>());
for pane in &panes {
let Some(observations) = observe(pane) else {
debug!(target = %pane.display_target, "observation skipped (viewer screen)");
continue;
};
// First sight of a pane in this process: resume from its options.
let restored = !self.tracks.contains_key(&pane.pane_id);
let mut track = self
.tracks
.get(&pane.pane_id)
.copied()
.unwrap_or_else(|| PaneTrack::restore(&pane.written_state, &pane.written_since));
let acked = pane.written_ack == "1";
// Apply every observation in order: a turn that started and
// finished between two ticks is still a completion.
let mut alerts = Vec::new();
for observed in observations {
let next = advance(track, observed, pane.attended(), acked, now);
if next.state != track.state {
info!(
target = %pane.display_target,
prev = track.status().label(),
next = next.status().label(),
"state change"
);
// Notify on transitions observed by this process, not
// when resuming from options written before a restart.
if !restored {
alerts.extend(notification_kind_for_transition(track.state, next.state));
}
}
track = next;
}
self.tracks.insert(pane.pane_id.clone(), track);
// Update what the user sees first, then alert.
if acked {
let _ = tmux::unset_pane_option(&pane.pane_id, "@dingger_ack");
}
self.write_pane_options(pane, track);
for kind in alerts {
self.notify(pane, kind);
}
}
self.publish(&panes);
Ok(())
}
fn write_pane_options(&self, pane: &tmux::Pane, track: PaneTrack) {
let label = track.status().label();
if pane.written_state != label {
if let Err(err) = tmux::set_pane_option(&pane.pane_id, "@agent_state", label) {
warn!(target = %pane.display_target, %err, "failed to write @agent_state");
}
}
let since = track.since.map(|s| s.to_string()).unwrap_or_default();
if pane.written_since != since {
let _ = if since.is_empty() {
tmux::unset_pane_option(&pane.pane_id, "@dingger_since")
} else {
tmux::set_pane_option(&pane.pane_id, "@dingger_since", &since)
};
}
let agent = pane.agent.map(detect_core::agent_label).unwrap_or("");
if pane.written_agent != agent {
let _ = tmux::set_pane_option(&pane.pane_id, "@agent", agent);
}
let name = crate::names::display_name(pane.agent, &pane.pane_title, &pane.cwd, host_name())
.unwrap_or_default();
if pane.written_name != name {
let _ = if name.is_empty() {
tmux::unset_pane_option(&pane.pane_id, "@agent_name")
} else {
tmux::set_pane_option(&pane.pane_id, "@agent_name", &name)
};
}
// Persist the authoritative hook state so a restart keeps it.
let hook = hooks::last_state(&pane.pane_id)
.map(state_label)
.unwrap_or_default();
if pane.agent.is_some() && !hook.is_empty() && pane.written_hook != hook {
let _ = tmux::set_pane_option(&pane.pane_id, "@dingger_hook", hook);
}
if pane.agent.is_none() && !pane.written_hook.is_empty() {
let _ = tmux::unset_pane_option(&pane.pane_id, "@dingger_hook");
}
}
fn notify(&self, pane: &tmux::Pane, kind: NotificationKind) {
// herdr: a blocked pane plays the alert even when the user is looking
// at it; a finished pane stays silent when they already are.
let watching = pane.attended();
if matches!(kind, NotificationKind::Finished) && watching {
return;
}
let agent = pane.agent.map(detect_core::agent_label).unwrap_or("agent");
if self.notifications && !watching {
send_notification(agent, &kind, &format!("{} ({agent})", pane.display_target));
}
if self.sounds {
play_sound(&kind);
}
}
/// Publish the ready queue and counts as server-global options for the
/// status line, menu bar, and focus. The queue is ordered like the menu:
/// herdr's priority (blocked before done), oldest first within it.
fn publish(&mut self, panes: &[tmux::Pane]) {
let mut queue: Vec<(std::cmp::Reverse<u8>, u64, &str)> = Vec::new();
let (mut blocked, mut done, mut working) = (0, 0, 0);
for pane in panes {
let Some(track) = self.tracks.get(&pane.pane_id) else {
continue;
};
match track.status() {
Status::Blocked => blocked += 1,
Status::Done => done += 1,
Status::Working => working += 1,
Status::Idle | Status::Unknown => {}
}
if let Some(since) = track.since {
queue.push((std::cmp::Reverse(track.status().priority()), since, pane.pane_id.as_str()));
}
}
queue.sort();
let queue = queue
.iter()
.map(|(_, _, pane_id)| *pane_id)
.collect::<Vec<_>>()
.join(",");
let next = (queue, blocked, done, working);
if self.last_published.as_ref() == Some(&next) {
return;
}
for (name, value) in [
("@dingger_queue", next.0.clone()),
("@dingger_blocked", next.1.to_string()),
("@dingger_done", next.2.to_string()),
("@dingger_working", next.3.to_string()),
] {
if let Err(err) = tmux::set_global(name, &value) {
warn!(%err, "failed to write {name}");
}
}
self.last_published = Some(next);
}
}
/// The pane's raw agent states this tick, in order, or `None` when the
/// screen is a viewer (transcript, picker) that says nothing about state.
fn observe(pane: &tmux::Pane) -> Option<Vec<AgentState>> {
if pane.dead {
return Some(vec![AgentState::Idle]);
}
let Some(agent) = pane.agent else {
// The agent is gone; its last hook report must not outlive it.
hooks::drop_reports(&pane.pane_id);
return Some(vec![AgentState::Unknown]);
};
// Agent-reported state is authoritative; it survives restarts through
// the `@dingger_hook` option until the extension reports again.
if let Some(states) = hooks::take_observations(&pane.pane_id) {
return Some(states);
}
if let Some(state) = parse_state(&pane.written_hook) {
return Some(vec![state]);
}
let screen = match tmux::capture_pane(&pane.pane_id) {
Ok(screen) => screen,
Err(err) => {
warn!(target = %pane.display_target, %err, "capture failed");
return None;
}
};
// tmux pane_title carries the last OSC title the application set; tmux
// does not re-expose OSC progress sequences.
let detection = detect_agent_with_osc(Some(agent), &screen, &pane.pane_title, "");
(!detection.skip_state_update).then(|| vec![detection.state])
}
/// The host name tmux uses as a pane's default title.
fn host_name() -> &'static str {
static HOST: std::sync::OnceLock<String> = std::sync::OnceLock::new();
HOST.get_or_init(|| {
std::process::Command::new("hostname")
.output()
.map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
.unwrap_or_default()
})
}
fn state_label(state: AgentState) -> &'static str {
match state {
AgentState::Idle => "idle",
AgentState::Working => "working",
AgentState::Blocked => "blocked",
AgentState::Unknown => "unknown",
}
}
fn parse_state(label: &str) -> Option<AgentState> {
match label {
"idle" => Some(AgentState::Idle),
"working" => Some(AgentState::Working),
"blocked" => Some(AgentState::Blocked),
_ => None,
}
}
fn unix_now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
use AgentState::{Blocked, Idle, Unknown, Working};
fn step(prev: PaneTrack, observed: AgentState, attended: bool) -> PaneTrack {
advance(prev, observed, attended, false, 100)
}
#[test]
fn notification_policy_matches_herdr() {
assert!(matches!(
notification_kind_for_transition(Working, Blocked),
Some(NotificationKind::NeedsAttention)
));
assert!(matches!(
notification_kind_for_transition(Unknown, Blocked),
Some(NotificationKind::NeedsAttention)
));
assert!(matches!(
notification_kind_for_transition(Working, Idle),
Some(NotificationKind::Finished)
));
assert!(matches!(
notification_kind_for_transition(Blocked, Idle),
Some(NotificationKind::Finished)
));
assert!(notification_kind_for_transition(Blocked, Blocked).is_none());
assert!(notification_kind_for_transition(Unknown, Idle).is_none());
assert!(notification_kind_for_transition(Idle, Working).is_none());
assert!(notification_kind_for_transition(Idle, Unknown).is_none());
}
// herdr: initial_idle_in_background_stays_seen
#[test]
fn first_observation_of_idle_is_idle() {
let track = step(PaneTrack::NEW, Idle, false);
assert_eq!(track.status(), Status::Idle);
assert_eq!(track.since, None);
}
// herdr: state_changed_idle_in_background_marks_unseen
#[test]
fn completion_away_from_the_window_is_done() {
let working = step(step(PaneTrack::NEW, Idle, false), Working, false);
assert_eq!(working.status(), Status::Working);
let done = step(working, Idle, false);
assert_eq!(done.status(), Status::Done);
assert_eq!(done.since, Some(100));
}
// herdr: active_tab_completion_marks_pane_seen
#[test]
fn completion_while_looking_is_idle() {
let working = step(PaneTrack::NEW, Working, true);
let idle = step(working, Idle, true);
assert_eq!(idle.status(), Status::Idle);
assert_eq!(idle.since, None);
}
// herdr: switch_workspace_marks_panes_seen (mark_active_tab_seen)
#[test]
fn looking_at_the_window_turns_done_into_idle() {
let done = step(step(PaneTrack::NEW, Working, false), Idle, false);
assert_eq!(done.status(), Status::Done);
let still_done = step(done, Idle, false);
assert_eq!(still_done.status(), Status::Done);
let seen = step(still_done, Idle, true);
assert_eq!(seen.status(), Status::Idle);
assert_eq!(seen.since, None);
}
// herdr: agent_focus_marks_already_focused_done_agent_seen
#[test]
fn jumping_to_a_pane_turns_done_into_idle() {
let done = step(step(PaneTrack::NEW, Working, false), Idle, false);
let seen = advance(done, Idle, false, true, 200);
assert_eq!(seen.status(), Status::Idle);
}
#[test]
fn working_again_clears_done_and_the_next_completion_is_done_again() {
let done = step(step(PaneTrack::NEW, Working, false), Idle, false);
let working = step(done, Working, false);
assert_eq!(working.status(), Status::Working);
assert_eq!(working.since, None);
let done_again = advance(working, Idle, false, false, 300);
assert_eq!(done_again.status(), Status::Done);
assert_eq!(done_again.since, Some(300));
}
#[test]
fn blocked_needs_the_user_even_while_looking() {
let blocked = step(step(PaneTrack::NEW, Working, false), Blocked, true);
assert_eq!(blocked.status(), Status::Blocked);
assert_eq!(blocked.since, Some(100));
// answering the prompt: back to work, then a completion away → done
let done = step(step(blocked, Working, false), Idle, false);
assert_eq!(done.status(), Status::Done);
}
#[test]
fn fifo_stamp_survives_unchanged_ticks() {
let done = advance(step(PaneTrack::NEW, Working, false), Idle, false, false, 50);
let later = advance(done, Idle, false, false, 999);
assert_eq!(later.since, Some(50));
}
#[test]
fn agent_exit_is_unknown() {
let done = step(step(PaneTrack::NEW, Working, false), Idle, false);
assert_eq!(step(done, Unknown, false).status(), Status::Unknown);
}
#[test]
fn restore_resumes_where_the_previous_daemon_left_off() {
let done = PaneTrack::restore("done", "42");
assert_eq!(done.status(), Status::Done);
assert_eq!(done.since, Some(42));
// the same observation after a restart keeps it done
assert_eq!(step(done, Idle, false).status(), Status::Done);
assert_eq!(PaneTrack::restore("idle", "").status(), Status::Idle);
assert_eq!(PaneTrack::restore("", "").status(), Status::Unknown);
assert_eq!(PaneTrack::restore("idle", "42").since, None);
}
#[test]
fn priority_matches_herdr() {
assert!(Status::Blocked.priority() > Status::Done.priority());
assert!(Status::Done.priority() > Status::Working.priority());
assert!(Status::Working.priority() > Status::Idle.priority());
assert!(Status::Idle.priority() > Status::Unknown.priority());
}
}
|