cekanje 0.1.3

tmux notifier daemon for Claude Code sessions: track every active session, surface a native popup when one needs attention, jump to its pane via fzf
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
use crate::persist;
use crate::restore;
use crate::state::{self, Shared, State, TmuxLocation};
use crate::tmux;
use axum::{
    Json, Router,
    extract::State as AxumState,
    http::{HeaderMap, StatusCode},
    response::IntoResponse,
    routing::{get, post},
};
use serde::Deserialize;
use serde_json::Value;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tracing::{info, warn};

static PERSIST_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();

/// Atomic write of the current state to disk if a persist path is configured.
/// Errors are logged but never propagated — a failed persist must not block
/// processing of the hook event.
fn persist_now(shared: &Shared) {
    let Some(Some(path)) = PERSIST_PATH.get() else {
        return;
    };
    let snap = shared.read();
    if let Err(e) = persist::save(path, &snap) {
        warn!(path = %path.display(), error = %e, "persist failed");
    }
}

pub async fn run(port: u16, idle_secs: u64, rebuild_window_secs: u64) -> anyhow::Result<()> {
    let shared = state::new_shared();
    let persist_path = persist::default_path();
    let _ = PERSIST_PATH.set(persist_path.clone());

    restore::restore(
        &shared,
        persist_path.as_deref(),
        Duration::from_secs(rebuild_window_secs),
    );

    if idle_secs > 0 {
        let s = Arc::clone(&shared);
        let threshold = Duration::from_secs(idle_secs);
        tokio::spawn(async move {
            loop {
                tokio::time::sleep(Duration::from_secs(60)).await;
                if s.read().is_idle(threshold) {
                    info!(idle_secs, "idle timeout reached, exiting");
                    std::process::exit(0);
                }
            }
        });
    }

    let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await?;
    info!(addr = %listener.local_addr()?, idle_secs, "cekanje listening");
    axum::serve(listener, router(shared)).await?;
    Ok(())
}

pub(crate) fn router(shared: Shared) -> Router {
    Router::new()
        .route("/hooks/event", post(event))
        .route("/status", get(status))
        .route("/list", get(list))
        .route("/visit", post(visit))
        .with_state(shared)
}

/// Outcome of applying a hook event to in-memory state. The handler uses
/// `state_changed` to decide whether to persist, and `notify` to decide
/// whether to send a desktop notification.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct EventOutcome {
    pub state_changed: bool,
    pub notify: Option<NotifyPayload>,
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) struct NotifyPayload {
    pub session_id: String,
    pub cwd: Option<String>,
    pub message: Option<String>,
}

/// Apply a single hook event to state. Pure — no I/O, no logging side effects.
pub(crate) fn apply_event(
    s: &mut State,
    event_name: &str,
    session_id: String,
    cwd: Option<PathBuf>,
    tmux_loc: Option<TmuxLocation>,
    message: Option<String>,
    pane_focused: bool,
) -> EventOutcome {
    s.touch();
    match event_name {
        "SessionStart" | "UserPromptSubmit" => {
            s.upsert_working(session_id, cwd, tmux_loc);
            EventOutcome {
                state_changed: true,
                notify: None,
            }
        }
        "Notification" | "Stop" if pane_focused => {
            s.upsert_working(session_id, cwd, tmux_loc);
            EventOutcome {
                state_changed: true,
                notify: None,
            }
        }
        "Notification" | "Stop" => {
            let cwd_str = cwd.as_ref().map(|p| p.display().to_string());
            let payload = NotifyPayload {
                session_id: session_id.clone(),
                cwd: cwd_str,
                message: message.clone(),
            };
            s.mark_waiting(session_id, cwd, tmux_loc, message);
            EventOutcome {
                state_changed: true,
                notify: Some(payload),
            }
        }
        "SessionEnd" => {
            s.drop_session(&session_id);
            EventOutcome {
                state_changed: true,
                notify: None,
            }
        }
        _ => EventOutcome::default(),
    }
}

async fn event(
    AxumState(shared): AxumState<Shared>,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> StatusCode {
    let event_name = body
        .get("hook_event_name")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let Some(session_id) = body
        .get("session_id")
        .and_then(|v| v.as_str())
        .map(String::from)
    else {
        warn!(event_name, "event missing session_id");
        return StatusCode::BAD_REQUEST;
    };

    let cwd = body.get("cwd").and_then(|v| v.as_str()).map(PathBuf::from);
    let message = body
        .get("message")
        .and_then(|v| v.as_str())
        .map(String::from);

    let pane = header_value(&headers, "x-tmux-pane");
    let socket = header_value(&headers, "x-tmux-socket").map(|s| tmux::parse_socket(&s));
    let tmux_loc = pane.map(|pane| TmuxLocation {
        pane,
        socket: socket.clone(),
    });

    let pane_focused = tmux_loc
        .as_ref()
        .map(|t| tmux::is_pane_focused(t.socket.as_deref(), &t.pane))
        .unwrap_or(false);

    info!(event_name, %session_id, ?tmux_loc, pane_focused, "event");

    let outcome = {
        let mut s = shared.write();
        apply_event(
            &mut s,
            event_name,
            session_id,
            cwd,
            tmux_loc,
            message,
            pane_focused,
        )
    };
    if outcome.state_changed {
        persist_now(&shared);
    }
    if let Some(n) = outcome.notify {
        crate::notify::waiting(&n.session_id, n.cwd.as_deref(), n.message.as_deref());
    }
    StatusCode::OK
}

async fn status(AxumState(shared): AxumState<Shared>) -> String {
    let n = shared.read().waiting_count();
    if n == 0 {
        String::new()
    } else {
        format!("{n}")
    }
}

async fn list(AxumState(shared): AxumState<Shared>) -> impl IntoResponse {
    let snapshot = shared.read().snapshot();
    Json(snapshot)
}

#[derive(Deserialize)]
struct VisitBody {
    pane: String,
}

async fn visit(AxumState(shared): AxumState<Shared>, Json(b): Json<VisitBody>) -> StatusCode {
    let cleared = {
        let mut s = shared.write();
        s.touch();
        s.visit_pane(&b.pane)
    };
    if cleared {
        info!(pane = %b.pane, "cleared");
        persist_now(&shared);
    }
    StatusCode::OK
}

fn header_value(h: &HeaderMap, name: &str) -> Option<String> {
    h.get(name)
        .and_then(|v| v.to_str().ok())
        .filter(|s| !s.is_empty())
        .map(String::from)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client;

    fn pane(p: &str) -> Option<TmuxLocation> {
        Some(TmuxLocation {
            pane: p.into(),
            socket: None,
        })
    }

    // ── apply_event (pure) ──────────────────────────────────────────────

    #[test]
    fn apply_event_session_start_upserts_working() {
        let mut s = State::default();
        let out = apply_event(
            &mut s,
            "SessionStart",
            "S1".into(),
            Some("/tmp/a".into()),
            pane("%1"),
            None,
            false,
        );
        assert!(out.state_changed);
        assert!(out.notify.is_none());
        assert_eq!(s.sessions["S1"].status, crate::state::Status::Working);
        assert_eq!(s.by_pane["%1"], "S1");
    }

    #[test]
    fn apply_event_user_prompt_submit_upserts_working() {
        let mut s = State::default();
        let out = apply_event(
            &mut s,
            "UserPromptSubmit",
            "S1".into(),
            None,
            pane("%1"),
            None,
            false,
        );
        assert!(out.state_changed);
        assert!(out.notify.is_none());
        assert_eq!(s.sessions["S1"].status, crate::state::Status::Working);
    }

    #[test]
    fn apply_event_notification_when_focused_does_not_notify() {
        let mut s = State::default();
        let out = apply_event(
            &mut s,
            "Notification",
            "S1".into(),
            Some("/tmp/a".into()),
            pane("%1"),
            Some("hi".into()),
            true,
        );
        assert!(out.state_changed);
        assert!(out.notify.is_none());
        assert_eq!(s.sessions["S1"].status, crate::state::Status::Working);
    }

    #[test]
    fn apply_event_notification_unfocused_marks_waiting_and_notifies() {
        let mut s = State::default();
        let out = apply_event(
            &mut s,
            "Notification",
            "S1".into(),
            Some("/tmp/a".into()),
            pane("%1"),
            Some("permission?".into()),
            false,
        );
        assert!(out.state_changed);
        let n = out.notify.expect("notify payload");
        assert_eq!(n.session_id, "S1");
        assert_eq!(n.cwd.as_deref(), Some("/tmp/a"));
        assert_eq!(n.message.as_deref(), Some("permission?"));
        assert_eq!(s.sessions["S1"].status, crate::state::Status::Waiting);
    }

    #[test]
    fn apply_event_stop_unfocused_mirrors_notification() {
        let mut s = State::default();
        let out = apply_event(&mut s, "Stop", "S1".into(), None, pane("%1"), None, false);
        assert!(out.notify.is_some());
        assert_eq!(s.sessions["S1"].status, crate::state::Status::Waiting);
    }

    #[test]
    fn apply_event_session_end_drops_session() {
        let mut s = State::default();
        s.upsert_working("S1".into(), None, pane("%1"));
        let out = apply_event(&mut s, "SessionEnd", "S1".into(), None, None, None, false);
        assert!(out.state_changed);
        assert!(out.notify.is_none());
        assert!(s.sessions.is_empty());
        assert!(s.by_pane.is_empty());
    }

    #[test]
    fn apply_event_unknown_event_is_noop() {
        let mut s = State::default();
        let out = apply_event(
            &mut s,
            "PreToolUse",
            "S1".into(),
            None,
            pane("%1"),
            None,
            false,
        );
        assert!(!out.state_changed);
        assert!(out.notify.is_none());
        assert!(s.sessions.is_empty());
    }

    // ── HTTP integration via real TCP listener ──────────────────────────

    async fn spawn() -> u16 {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let shared = state::new_shared();
        let app = router(shared);
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        port
    }

    #[tokio::test]
    async fn status_endpoint_empty_when_no_waiting() {
        let port = spawn().await;
        let body = client::http_get(port, "/status").await.unwrap();
        assert_eq!(body, "");
    }

    #[tokio::test]
    async fn status_endpoint_returns_badge_when_waiting() {
        let port = spawn().await;
        let evt = serde_json::json!({
            "hook_event_name": "Notification",
            "session_id": "S1",
            "cwd": "/tmp/a",
            "message": "permission?",
        })
        .to_string();
        client::http_post_json(port, "/hooks/event", &evt)
            .await
            .unwrap();
        let body = client::http_get(port, "/status").await.unwrap();
        assert_eq!(body, "⏳1");
    }

    #[tokio::test]
    async fn list_endpoint_returns_json_snapshot() {
        let port = spawn().await;
        let evt = serde_json::json!({
            "hook_event_name": "SessionStart",
            "session_id": "S1",
            "cwd": "/tmp/a",
        })
        .to_string();
        client::http_post_json(port, "/hooks/event", &evt)
            .await
            .unwrap();
        let body = client::http_get(port, "/list").await.unwrap();
        let arr: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["session_id"], "S1");
        assert_eq!(arr[0]["status"], "working");
    }

    #[tokio::test]
    async fn visit_endpoint_clears_waiting_for_pane() {
        let port = spawn().await;
        // Seed a waiting session bound to pane %42.
        // (We can't easily set headers via our minimalist client, so we use
        // the SessionStart path to register pane via headers — instead we
        // just register without a pane and visit with no pane; we want to
        // test the round-trip, so send a Notification with a header.)
        // Simpler: use a raw TCP request with the x-tmux-pane header.
        let evt_body = serde_json::json!({
            "hook_event_name": "Notification",
            "session_id": "S1",
            "cwd": "/tmp/a",
        })
        .to_string();
        send_with_pane_header(port, "/hooks/event", &evt_body, "%42")
            .await
            .unwrap();
        // Confirm waiting.
        assert_eq!(client::http_get(port, "/status").await.unwrap(), "⏳1");

        // Visit clears.
        let visit = serde_json::json!({ "pane": "%42" }).to_string();
        client::http_post_json(port, "/visit", &visit)
            .await
            .unwrap();
        assert_eq!(client::http_get(port, "/status").await.unwrap(), "");
    }

    #[tokio::test]
    async fn event_endpoint_400_when_session_id_missing() {
        let port = spawn().await;
        let evt = serde_json::json!({
            "hook_event_name": "SessionStart",
            "cwd": "/tmp/a",
        })
        .to_string();
        let raw = raw_post(port, "/hooks/event", &evt, &[]).await.unwrap();
        assert!(
            raw.starts_with("HTTP/1.1 400"),
            "expected 400, got: {}",
            raw.lines().next().unwrap_or("")
        );
    }

    /// Minimal raw POST helper that lets us attach extra headers (the
    /// production `client::http_post_json` doesn't).
    async fn raw_post(
        port: u16,
        path: &str,
        body: &str,
        extra_headers: &[(&str, &str)],
    ) -> std::io::Result<String> {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port)).await?;
        let mut req = format!(
            "POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n",
            body.len()
        );
        for (k, v) in extra_headers {
            req.push_str(&format!("{k}: {v}\r\n"));
        }
        req.push_str("\r\n");
        req.push_str(body);
        stream.write_all(req.as_bytes()).await?;
        let mut buf = String::new();
        stream.read_to_string(&mut buf).await?;
        Ok(buf)
    }

    async fn send_with_pane_header(
        port: u16,
        path: &str,
        body: &str,
        pane: &str,
    ) -> std::io::Result<String> {
        raw_post(port, path, body, &[("x-tmux-pane", pane)]).await
    }
}