Skip to main content

orch/channels/
capture.rs

1//! Capture service — polls tmux sessions for output and broadcasts to transport.
2//!
3//! This service:
4//! - Runs a background loop every 2 seconds
5//! - Captures pane output for registered sessions
6//! - Diffs against previous capture to find new content
7//! - Pushes new content as OutputChunk to transport
8//!
9//! Sessions are registered when tasks are dispatched and unregistered
10//! when they complete. In a cluster, a session on another node is read
11//! from that node over the cluster listener instead of tmux.
12
13use crate::channels::OutputChunk;
14use crate::channels::tmux;
15use crate::channels::transport::{Transport, session_key};
16use crate::sys::suspend;
17use async_trait::async_trait;
18use chrono::{DateTime, Utc};
19use sha2::{Digest, Sha256};
20use std::cmp::Ordering;
21use std::collections::HashMap;
22use std::fmt;
23use std::fmt::Debug;
24use std::fmt::Formatter;
25use std::sync::Arc;
26use std::time::Duration;
27use tokio::sync::RwLock;
28use tokio::time;
29
30pub(crate) const MAX_OUTPUT_BUFFER_BYTES: usize = 1024 * 1024;
31
32/// Buffer for tracking session output state.
33#[derive(Debug, Clone)]
34pub struct OutputBuffer {
35    /// Repo slug (owner/repo) that owns this session.
36    pub repo: String,
37    /// The tmux session name (e.g., "orch-myproject-42")
38    pub session: String,
39    /// The task ID this session belongs to
40    pub task_id: String,
41    /// Content from the last capture
42    pub last_content: String,
43    /// Byte length of the last capture
44    pub last_len: usize,
45    /// Hash of the last capture (for dedup)
46    pub last_hash: Option<[u8; 32]>,
47    /// When the last capture occurred
48    pub last_capture: DateTime<Utc>,
49    /// Whether the session has been seen alive at least once (i.e., `capture_pane`
50    /// succeeded at least once). Prevents firing "session ended" for sessions that
51    /// were registered before the tmux session was actually created.
52    /// Also used by silence detection: a seen-alive session with no output is only
53    /// treated as silent if the tmux session is currently dead (silent exit-0).
54    pub seen_alive: bool,
55    /// When this session was registered for capture.
56    pub registered_at: DateTime<Utc>,
57    /// Whether the agent has produced any meaningful output since session start.
58    /// Used for silence detection: only agents that never produced output are
59    /// considered silent. Agents that produced output then go quiet are NOT
60    /// killed (they may be running long tool calls with sparse output).
61    pub has_output: bool,
62    /// Generation counter incremented on each registration for this session_key.
63    /// Used to detect when a session has been re-registered (e.g., after retry)
64    /// so that stale snapshots from previous generations don't incorrectly
65    /// trigger final/unregister side effects.
66    pub generation: u64,
67}
68
69/// Service that captures tmux pane output and broadcasts to transport.
70pub struct CaptureService {
71    /// Session buffers keyed by session_key(repo, task_id)
72    buffers: Arc<RwLock<HashMap<String, OutputBuffer>>>,
73    /// Transport layer for broadcasting output
74    transport: Arc<Transport>,
75    /// Polling interval
76    interval: Duration,
77    /// Set on a cluster node, to read sessions other nodes run
78    remote: Option<Arc<dyn RemoteSessions>>,
79}
80
81/// New output of a session another node runs
82#[derive(Debug, Clone, Default)]
83pub struct RemoteRead {
84    pub content: String,
85    /// The run is over or its node is offline
86    pub is_final: bool,
87}
88
89/// Sessions that run on another cluster node, read over the cluster listener instead of tmux
90#[async_trait]
91pub trait RemoteSessions: Send + Sync {
92    /// None when the session runs on this node, or no node took the task yet
93    async fn read(
94        &self,
95        skey: &str,
96        repo: &str,
97        task_id: &str,
98        seen_alive: bool,
99    ) -> Option<RemoteRead>;
100
101    async fn forget(&self, skey: &str);
102}
103
104impl Debug for CaptureService {
105    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
106        f.debug_struct("CaptureService")
107            .field("interval", &self.interval)
108            .finish_non_exhaustive()
109    }
110}
111
112impl CaptureService {
113    /// Create a new CaptureService.
114    pub fn new(transport: Arc<Transport>) -> Self {
115        Self {
116            buffers: Arc::new(RwLock::new(HashMap::new())),
117            transport,
118            interval: Duration::from_secs(2),
119            remote: None,
120        }
121    }
122
123    /// Read sessions other cluster nodes run through `remote`
124    #[must_use]
125    pub fn with_remote(mut self, remote: Arc<dyn RemoteSessions>) -> Self {
126        self.remote = Some(remote);
127        self
128    }
129
130    /// Register a session to be tracked.
131    pub async fn register_session(&self, repo: &str, task_id: &str, session: &str) {
132        let now = Utc::now();
133        let skey = session_key(repo, task_id);
134
135        // Atomically read the current generation and insert the new buffer under
136        // a single write lock to prevent a TOCTOU race where two concurrent
137        // re-registrations both observe the same stale generation value.
138        let generation = {
139            let mut buffers = self.buffers.write().await;
140            let generation = buffers.get(&skey).map_or(0, |b| b.generation + 1);
141            let buffer = OutputBuffer {
142                repo: repo.to_string(),
143                session: session.to_string(),
144                task_id: task_id.to_string(),
145                last_content: String::new(),
146                last_len: 0,
147                last_hash: None,
148                last_capture: now,
149                seen_alive: false,
150                registered_at: now,
151                has_output: false,
152                generation,
153            };
154            buffers.insert(skey, buffer);
155            generation
156        };
157        tracing::debug!(
158            repo,
159            task_id,
160            session,
161            generation,
162            "session registered for capture"
163        );
164    }
165
166    /// Unregister a session (stop tracking).
167    pub async fn unregister_session(&self, repo: &str, task_id: &str) {
168        let skey = session_key(repo, task_id);
169        if let Some(remote) = &self.remote {
170            remote.forget(&skey).await;
171        }
172        if let Some(buffer) = self.buffers.write().await.remove(&skey) {
173            tracing::debug!(
174                repo = buffer.repo,
175                task_id = buffer.task_id,
176                session = buffer.session,
177                "session unregistered"
178            );
179        }
180        self.transport.unbind(repo, task_id).await;
181    }
182
183    /// Start the capture loop.
184    ///
185    /// This runs indefinitely, polling registered sessions for new output.
186    pub async fn start(&self) {
187        tracing::info!(
188            interval_secs = self.interval.as_secs(),
189            "capture service started"
190        );
191        let mut interval = time::interval(self.interval);
192
193        loop {
194            interval.tick().await;
195            self.tick().await;
196        }
197    }
198
199    /// Run the capture loop while there are registered sessions.
200    ///
201    /// This returns when no more sessions are registered, making it suitable
202    /// for CLI streaming where the capture should stop when the session ends.
203    pub async fn run(&self) {
204        let mut interval = time::interval(self.interval);
205
206        loop {
207            interval.tick().await;
208
209            // Check if there are any sessions to capture
210            let has_sessions = !self.buffers.read().await.is_empty();
211            if !has_sessions {
212                tracing::debug!("no sessions registered, capture loop exiting");
213                break;
214            }
215
216            self.tick().await;
217        }
218    }
219
220    /// Return task IDs of sessions that have been silent since registration.
221    ///
222    /// A session is "silent" when:
223    /// 1. It has been registered for longer than `grace_period`
224    /// 2. It has NEVER produced any meaningful output (`has_output == false`)
225    /// 3. Either it was NEVER confirmed alive, OR it was seen alive but the tmux
226    ///    session is now dead (silent exit-0 case)
227    ///
228    /// Condition (3) balances two cases:
229    /// - Session alive and working (tmux session exists, agent running, sparse output)
230    ///   → should NOT be killed; hard timeout will catch it if it runs too long (#2318)
231    /// - Session was alive but exited silently with no output (tmux session dead)
232    ///   → SHOULD trigger silence fallback within grace_period, not wait 30 min (#2573)
233    ///
234    /// Returns (task_id, session_name, age_secs) for silent sessions.
235    pub async fn get_silent_sessions_for_repo(
236        &self,
237        repo: &str,
238        grace_period: Duration,
239    ) -> Vec<(String, String, i64)> {
240        let now = Utc::now();
241        let buffers = self.buffers.read().await;
242        let mut candidates: Vec<OutputBuffer> = buffers
243            .values()
244            .filter(|buf| buf.repo == repo && !buf.has_output)
245            .cloned()
246            .collect();
247        drop(buffers);
248
249        let mut silent = Vec::new();
250        for buf in candidates.drain(..) {
251            if buf.seen_alive {
252                // Session was confirmed alive at least once. If the tmux session is
253                // still running, it's doing real work with sparse output — skip it
254                // (the hard stuck_timeout will catch runaway tasks). If the session
255                // is dead and produced no output, it's a silent exit — fall through
256                // to the grace period check so silence detection fires within 120s
257                // instead of waiting the full 30-minute stuck_timeout.
258                if !tmux::is_session_dead(&buf.session).await {
259                    continue;
260                }
261                tracing::debug!(
262                    task_id = buf.task_id,
263                    session = buf.session,
264                    "session seen-alive but now dead with no output, treating as silent exit"
265                );
266            }
267
268            // Re-check the current generation to avoid silencing sessions that were
269            // re-registered (e.g., after a retry/dispatch). If the generation has
270            // changed, the session was restarted and the old entry is stale.
271            let skey = session_key(&buf.repo, &buf.task_id);
272            let current_generation = {
273                let buffers = self.buffers.read().await;
274                buffers.get(&skey).map(|b| b.generation)
275            };
276            if current_generation != Some(buf.generation) {
277                tracing::debug!(
278                    task_id = buf.task_id,
279                    session = buf.session,
280                    old_gen = buf.generation,
281                    new_gen = current_generation,
282                    "session generation changed, skipping silence detection (was re-registered)"
283                );
284                continue;
285            }
286
287            let raw_age = now.signed_duration_since(buf.registered_at);
288            // Host suspend (laptop sleep) freezes the process just like it freezes
289            // the agent running inside it — suspended wall-clock time is not evidence
290            // of a hung agent. Discount any detected suspend/resume gaps that occurred
291            // since the session was registered, mirroring the watchdog fix in
292            // engine::tick (`stuck_task_timing_from_map`).
293            let suspended = suspend::suspended_duration_since(buf.registered_at);
294            let age = (raw_age - suspended).max(chrono::Duration::zero());
295            if age.num_seconds() > i64::try_from(grace_period.as_secs()).unwrap_or(i64::MAX) {
296                silent.push((buf.task_id.clone(), buf.session.clone(), age.num_seconds()));
297            }
298        }
299        silent
300    }
301
302    /// Run one tick of the capture loop.
303    ///
304    /// Acquires the read lock once and iterates over all buffers to avoid
305    /// the race condition of collecting keys, dropping the lock, then
306    /// re-acquiring to look up each buffer (which could result in missing
307    /// or stale entries).
308    async fn tick(&self) {
309        let buffers = self.buffers.read().await;
310        let sessions: Vec<(String, OutputBuffer)> = buffers
311            .iter()
312            .map(|(k, v)| (k.clone(), v.clone()))
313            .collect();
314        drop(buffers);
315
316        for (skey, buffer) in sessions {
317            if self.capture_remote(&skey, &buffer).await {
318                continue;
319            }
320
321            // Capture pane content directly via tmux
322            let current_content = match tmux::capture_pane(&buffer.session).await {
323                Ok(s) => s,
324                Err(e) => {
325                    // Validate current buffer still represents same session instance
326                    // before triggering final/unregister side effects. This prevents
327                    // stale snapshots from previous registration generations
328                    // (e.g., after retry/re-dispatch) from incorrectly terminating
329                    // a newly registered session.
330                    let current = {
331                        let buffers = self.buffers.read().await;
332                        buffers.get(&skey).cloned()
333                    };
334
335                    // Only fire "session ended" if:
336                    // 1. The session still exists in the map
337                    // 2. It has the same generation (not re-registered)
338                    // 3. It was seen alive before
339                    // 4. The tmux session is actually dead
340                    let should_finalize = current.as_ref().is_some_and(|c| {
341                        c.generation == buffer.generation
342                            && c.seen_alive
343                            && c.session == buffer.session
344                    });
345
346                    if should_finalize && tmux::is_session_dead(&buffer.session).await {
347                        tracing::info!(
348                            task_id = buffer.task_id,
349                            session = buffer.session,
350                            generation = buffer.generation,
351                            "session ended, sending final chunk"
352                        );
353                        let chunk = OutputChunk {
354                            content: String::new(),
355                            is_final: true,
356                        };
357                        self.transport
358                            .push_output(&buffer.repo, &buffer.task_id, chunk)
359                            .await;
360                        self.unregister_session(&buffer.repo, &buffer.task_id).await;
361                    } else if current.is_none() {
362                        tracing::trace!(
363                            task_id = buffer.task_id,
364                            session = buffer.session,
365                            "session already unregistered"
366                        );
367                    } else {
368                        tracing::trace!(
369                            task_id = buffer.task_id,
370                            session = buffer.session,
371                            ?e,
372                            "capture failed (transient)"
373                        );
374                    }
375                    continue;
376                }
377            };
378
379            let new_content = {
380                let mut buffers = self.buffers.write().await;
381                if let Some(buf) = buffers.get_mut(&skey) {
382                    buf.seen_alive = true;
383                    buf.diff_and_update(&current_content)
384                } else {
385                    None
386                }
387            };
388
389            if let Some(new_content) = new_content {
390                let chunk = OutputChunk {
391                    content: new_content,
392                    is_final: false,
393                };
394                self.transport
395                    .push_output(&buffer.repo, &buffer.task_id, chunk)
396                    .await;
397            }
398        }
399    }
400}
401
402impl CaptureService {
403    /// Push what a session on another node wrote. False when the session runs here
404    async fn capture_remote(&self, skey: &str, buffer: &OutputBuffer) -> bool {
405        let Some(remote) = &self.remote else {
406            return false;
407        };
408        let Some(read) = remote
409            .read(skey, &buffer.repo, &buffer.task_id, buffer.seen_alive)
410            .await
411        else {
412            return false;
413        };
414
415        if let Some(buf) = self.buffers.write().await.get_mut(skey) {
416            buf.seen_alive = true;
417            buf.has_output |= !read.content.is_empty();
418        }
419
420        if !read.content.is_empty() || read.is_final {
421            let chunk = OutputChunk {
422                content: read.content,
423                is_final: read.is_final,
424            };
425            self.transport
426                .push_output(&buffer.repo, &buffer.task_id, chunk)
427                .await;
428        }
429
430        if read.is_final {
431            self.unregister_session(&buffer.repo, &buffer.task_id).await;
432        }
433
434        true
435    }
436}
437
438impl OutputBuffer {
439    pub(crate) fn diff_and_update(&mut self, current_content: &str) -> Option<String> {
440        let current_bytes = current_content.as_bytes();
441        let current_len = current_bytes.len();
442        let current_hash = hash_bytes(current_bytes);
443
444        if self.last_len == current_len && self.last_hash == Some(current_hash) {
445            self.last_capture = Utc::now();
446            return None;
447        }
448
449        let new_content = match self.last_len.cmp(&current_len) {
450            // Content shrank (terminal cleared) — no incremental diff available.
451            // Emitting full current_content would duplicate already-broadcast output.
452            Ordering::Greater => String::new(),
453            Ordering::Equal => {
454                // Same-length overwrite (e.g. spinner/progress refresh).
455                // Find the longest common prefix and return only the changed suffix.
456                let common_prefix = self
457                    .last_content
458                    .as_bytes()
459                    .iter()
460                    .zip(current_content.as_bytes())
461                    .take_while(|(a, b)| a == b)
462                    .count();
463                let mut start = common_prefix;
464                while start < current_len && !current_content.is_char_boundary(start) {
465                    start += 1;
466                }
467                current_content[start..].to_string()
468            }
469            Ordering::Less => {
470                let mut offset = self.last_len;
471                while offset < current_len && !current_content.is_char_boundary(offset) {
472                    offset += 1;
473                }
474                String::from_utf8_lossy(&current_bytes[offset..]).to_string()
475            }
476        };
477
478        self.last_len = current_len;
479        self.last_hash = Some(current_hash);
480        self.last_content = cap_content(current_content);
481        self.last_capture = Utc::now();
482
483        if new_content.trim().is_empty() {
484            None
485        } else {
486            self.has_output = true;
487            Some(new_content)
488        }
489    }
490}
491
492fn hash_bytes(bytes: &[u8]) -> [u8; 32] {
493    let mut hasher = Sha256::new();
494    hasher.update(bytes);
495    hasher.finalize().into()
496}
497
498fn cap_content(content: &str) -> String {
499    if content.len() <= MAX_OUTPUT_BUFFER_BYTES {
500        return content.to_string();
501    }
502
503    let mut start = content.len() - MAX_OUTPUT_BUFFER_BYTES;
504    while start < content.len() && !content.is_char_boundary(start) {
505        start += 1;
506    }
507    content[start..].to_string()
508}
509
510impl CaptureService {
511    /// Test helper: mutate buffer fields for a registered session by task_id.
512    /// Panics if the session is not registered.
513    #[cfg(test)]
514    pub(crate) async fn set_buffer_state_for_test(
515        &self,
516        repo: &str,
517        task_id: &str,
518        seen_alive: bool,
519        has_output: bool,
520        registered_at: chrono::DateTime<Utc>,
521    ) {
522        let skey = session_key(repo, task_id);
523        let mut buffers = self.buffers.write().await;
524        let buf = buffers
525            .get_mut(&skey)
526            .unwrap_or_else(|| panic!("no buffer for {repo}/{task_id}"));
527        buf.seen_alive = seen_alive;
528        buf.has_output = has_output;
529        buf.registered_at = registered_at;
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use std::collections::HashSet;
536
537    use super::*;
538    use crate::channels::transport::Transport;
539
540    fn make_buffer() -> OutputBuffer {
541        OutputBuffer {
542            repo: "owner/repo".to_string(),
543            session: "test-session".to_string(),
544            task_id: "task-1".to_string(),
545            last_content: String::new(),
546            last_len: 0,
547            last_hash: None,
548            last_capture: Utc::now(),
549            seen_alive: false,
550            registered_at: Utc::now(),
551            has_output: false,
552            generation: 0,
553        }
554    }
555
556    #[test]
557    fn normal_append_returns_new_suffix() {
558        let mut buf = make_buffer();
559        // First capture
560        let result = buf.diff_and_update("hello");
561        assert_eq!(result.as_deref(), Some("hello"));
562        // Append more
563        let result = buf.diff_and_update("hello world");
564        assert_eq!(result.as_deref(), Some(" world"));
565    }
566
567    #[test]
568    fn no_change_returns_none() {
569        let mut buf = make_buffer();
570        buf.diff_and_update("hello");
571        // Same content → no diff
572        let result = buf.diff_and_update("hello");
573        assert_eq!(result, None);
574    }
575
576    #[test]
577    fn terminal_clear_shrink_returns_none_not_full_content() {
578        let mut buf = make_buffer();
579        // Simulate some prior output
580        buf.diff_and_update("line1\nline2\nline3\n");
581        // Terminal clears: pane now contains less content (e.g. after \033[2J)
582        let result = buf.diff_and_update("prompt$ ");
583        // Must NOT return the full current content as "new" — that would duplicate output.
584        assert_eq!(
585            result, None,
586            "shrinking pane content should produce no output, not a duplicate of visible screen"
587        );
588    }
589
590    #[test]
591    fn terminal_clear_to_empty_returns_none() {
592        let mut buf = make_buffer();
593        buf.diff_and_update("lots of output here\nmore output\n");
594        // Pane cleared to empty
595        let result = buf.diff_and_update("");
596        assert_eq!(result, None);
597    }
598
599    #[test]
600    fn same_length_content_change_is_broadcast() {
601        let mut buf = make_buffer();
602        buf.diff_and_update("aaaa");
603
604        let result = buf.diff_and_update("bbbb");
605
606        assert_eq!(result.as_deref(), Some("bbbb"));
607    }
608
609    #[test]
610    fn same_length_partial_change_broadcasts_only_changed_suffix() {
611        let mut buf = make_buffer();
612        // Simulate 200 lines of prior output followed by a spinner character.
613        let prior = format!("{}/", "line\n".repeat(50));
614        buf.diff_and_update(&prior);
615
616        // Spinner ticks: only last char changes, everything before is identical.
617        let updated = format!("{}-", "line\n".repeat(50));
618        assert_eq!(
619            prior.len(),
620            updated.len(),
621            "lengths must match for this test"
622        );
623
624        let result = buf.diff_and_update(&updated);
625
626        // Only the changed suffix ("-") should be returned, not the full content.
627        assert_eq!(
628            result.as_deref(),
629            Some("-"),
630            "should return only the changed suffix, not the full content"
631        );
632    }
633
634    #[test]
635    fn empty_initial_capture_returns_none() {
636        let mut buf = make_buffer();
637        let result = buf.diff_and_update("");
638        assert_eq!(result, None);
639    }
640
641    #[test]
642    fn has_output_set_on_meaningful_content() {
643        let mut buf = make_buffer();
644        assert!(!buf.has_output);
645        buf.diff_and_update("hello");
646        assert!(buf.has_output);
647    }
648
649    #[test]
650    fn has_output_not_set_on_empty_content() {
651        let mut buf = make_buffer();
652        buf.diff_and_update("");
653        assert!(!buf.has_output, "empty content should not set has_output");
654    }
655
656    #[test]
657    fn has_output_stays_true_after_silence() {
658        let mut buf = make_buffer();
659        buf.diff_and_update("hello");
660        assert!(buf.has_output);
661        // Same content (no new output) — has_output should remain true
662        buf.diff_and_update("hello");
663        assert!(buf.has_output, "has_output should not revert once set");
664    }
665
666    #[tokio::test]
667    async fn get_silent_sessions_returns_only_no_output_past_grace() {
668        let transport = Arc::new(Transport::new());
669        let svc = CaptureService::new(transport);
670        let repo = "owner/repo";
671
672        // Register a session and backdate it past the grace period.
673        // seen_alive=false (default) + has_output=false → IS silent.
674        svc.register_session(repo, "silent-task", "orch-test-silent")
675            .await;
676        svc.set_buffer_state_for_test(
677            repo,
678            "silent-task",
679            false,
680            false,
681            Utc::now() - chrono::Duration::seconds(200),
682        )
683        .await;
684
685        // Register a session that HAS produced output (should not be returned).
686        svc.register_session(repo, "active-task", "orch-test-active")
687            .await;
688        svc.set_buffer_state_for_test(
689            repo,
690            "active-task",
691            false,
692            true, // has_output
693            Utc::now() - chrono::Duration::seconds(200),
694        )
695        .await;
696
697        // Register a fresh session within grace period (should not be returned).
698        svc.register_session(repo, "new-task", "orch-test-new")
699            .await;
700
701        let grace = Duration::from_secs(120);
702        let silent = svc.get_silent_sessions_for_repo(repo, grace).await;
703        assert_eq!(silent.len(), 1);
704        assert_eq!(silent[0].0, "silent-task");
705    }
706
707    /// Regression test for issue #2318 and fix for issue #2573.
708    ///
709    /// A session confirmed alive (capture_pane succeeded at least once) with no
710    /// terminal output falls into two cases:
711    ///
712    /// - **Tmux session dead, no output** (silent exit-0, issue #2573): IS silent.
713    ///   The agent exited immediately without printing anything. Should be detected
714    ///   within the grace period, not wait 30 minutes for stuck_timeout.
715    ///
716    /// - **Tmux session alive, no output** (issue #2318): NOT silent.
717    ///   Claude agents doing complex refactoring can run 15+ minutes with sparse
718    ///   terminal output (writing files via Edit/Write tools). Hard timeout handles them.
719    ///
720    /// In tests, tmux sessions don't exist, so `is_session_dead` returns `true` for
721    /// both sessions below — both "never-seen" and "seen-but-dead" are correctly
722    /// classified as silent exits.
723    #[tokio::test]
724    async fn get_silent_sessions_seen_alive_dead_session_is_silent() {
725        let transport = Arc::new(Transport::new());
726        let svc = CaptureService::new(transport);
727        let repo = "owner/repo";
728
729        // Session past grace period, never seen alive → IS silent.
730        svc.register_session(repo, "never-seen-task", "orch-never-seen")
731            .await;
732        svc.set_buffer_state_for_test(
733            repo,
734            "never-seen-task",
735            false, // seen_alive = false (default)
736            false, // has_output = false
737            Utc::now() - chrono::Duration::seconds(500),
738        )
739        .await;
740
741        // Session past grace period, seen alive, no output, tmux session dead
742        // (simulates silent exit-0 from issue #2573) → IS silent.
743        // The session name ends with "-dead" to work with both the integration test
744        // mock (which returns `is_session_dead=true` for "-dead" names) and the unit
745        // test context (where no real tmux session by that name exists → dead).
746        svc.register_session(repo, "seen-but-dead-task", "orch-seen-dead")
747            .await;
748        svc.set_buffer_state_for_test(
749            repo,
750            "seen-but-dead-task",
751            true,  // seen_alive: capture_pane succeeded at least once
752            false, // has_output = false, tmux session no longer exists → silent exit
753            Utc::now() - chrono::Duration::seconds(500),
754        )
755        .await;
756
757        let grace = Duration::from_secs(120);
758        let silent = svc.get_silent_sessions_for_repo(repo, grace).await;
759        // Both sessions should be returned: "never-seen-task" was never alive, and
760        // "seen-but-dead-task" was alive but the tmux session is now dead with no output.
761        assert_eq!(
762            silent.len(),
763            2,
764            "both never-alive and dead-with-no-output sessions must be silenced"
765        );
766        let ids: HashSet<&str> = silent.iter().map(|(id, _, _)| id.as_str()).collect();
767        assert!(ids.contains("never-seen-task"));
768        assert!(ids.contains("seen-but-dead-task"));
769    }
770
771    #[tokio::test]
772    async fn get_silent_sessions_filters_by_repo() {
773        let transport = Arc::new(Transport::new());
774        let svc = CaptureService::new(transport);
775
776        svc.register_session("owner/repo-a", "task-a", "orch-a")
777            .await;
778        svc.register_session("owner/repo-b", "task-b", "orch-b")
779            .await;
780        svc.set_buffer_state_for_test(
781            "owner/repo-a",
782            "task-a",
783            false,
784            false,
785            Utc::now() - chrono::Duration::seconds(200),
786        )
787        .await;
788        svc.set_buffer_state_for_test(
789            "owner/repo-b",
790            "task-b",
791            false,
792            false,
793            Utc::now() - chrono::Duration::seconds(200),
794        )
795        .await;
796
797        let grace = Duration::from_secs(120);
798        let silent_a = svc
799            .get_silent_sessions_for_repo("owner/repo-a", grace)
800            .await;
801        assert_eq!(silent_a.len(), 1);
802        assert_eq!(silent_a[0].0, "task-a");
803
804        let silent_b = svc
805            .get_silent_sessions_for_repo("owner/repo-b", grace)
806            .await;
807        assert_eq!(silent_b.len(), 1);
808        assert_eq!(silent_b[0].0, "task-b");
809    }
810
811    /// Same external task ID in two repos must not collide in capture buffers.
812    #[tokio::test]
813    async fn same_task_id_different_repos_capture_buffers_isolated() {
814        let transport = Arc::new(Transport::new());
815        let svc = CaptureService::new(transport);
816
817        svc.register_session("owner/repo-a", "42", "orch-a-42")
818            .await;
819        svc.register_session("owner/repo-b", "42", "orch-b-42")
820            .await;
821
822        let skey_a = session_key("owner/repo-a", "42");
823        let skey_b = session_key("owner/repo-b", "42");
824
825        let buffers = svc.buffers.read().await;
826        let buf_a = buffers
827            .get(&skey_a)
828            .expect("buffer should exist for repo-a session");
829        let buf_b = buffers
830            .get(&skey_b)
831            .expect("buffer should exist for repo-b session");
832
833        assert_eq!(buf_a.session, "orch-a-42");
834        assert_eq!(buf_b.session, "orch-b-42");
835        assert_ne!(buf_a.session, buf_b.session);
836        assert_eq!(buf_a.repo, "owner/repo-a");
837        assert_eq!(buf_b.repo, "owner/repo-b");
838    }
839
840    #[test]
841    fn multibyte_boundary_no_bytes_dropped() {
842        // "Hello " is 6 bytes. Append a 3-byte CJK character (世, U+4E16).
843        // Simulate last_len landing in the middle of the 3-byte sequence.
844        let mut buf = make_buffer();
845        buf.diff_and_update("Hello ");
846        // Full string with CJK appended
847        let full = "Hello 世界";
848        let result = buf.diff_and_update(full);
849        // The new suffix must contain both CJK characters intact.
850        let s = result.expect("should return new content");
851        assert!(s.contains('世'), "first CJK char must not be dropped");
852        assert!(s.contains('界'), "second CJK char must not be dropped");
853    }
854
855    #[test]
856    fn whitespace_only_new_content_returns_none() {
857        let mut buf = make_buffer();
858        buf.diff_and_update("hello");
859        // New suffix is only whitespace
860        let result = buf.diff_and_update("hello   \n");
861        assert_eq!(result, None);
862    }
863
864    /// Regression test for issue #2932.
865    ///
866    /// When a session is re-registered (e.g., after retry/dispatch), the old
867    /// buffer entry has a stale generation. Silence detection must not kill the
868    /// NEW session just because an older entry with the same task_id was registered
869    /// before the grace period elapsed. The re-registered session should be
870    /// treated as fresh — it has a higher generation and different session name.
871    #[tokio::test]
872    async fn get_silent_sessions_skips_stale_generation() {
873        let transport = Arc::new(Transport::new());
874        let svc = CaptureService::new(transport);
875        let repo = "owner/repo";
876
877        // Register task once with a session, backdate it past grace period.
878        svc.register_session(repo, "task-42", "orch-old-session")
879            .await;
880        svc.set_buffer_state_for_test(
881            repo,
882            "task-42",
883            false,
884            false,
885            Utc::now() - chrono::Duration::seconds(500),
886        )
887        .await;
888
889        // Re-register the same task with a new session (generation incremented).
890        svc.register_session(repo, "task-42", "orch-new-session")
891            .await;
892
893        let grace = Duration::from_secs(120);
894        let silent = svc.get_silent_sessions_for_repo(repo, grace).await;
895
896        // The stale old-generation entry must be skipped.
897        // The re-registered session has generation=1 and is fresh (< 120s old),
898        // so it must NOT appear in the silent list.
899        assert!(
900            silent.is_empty(),
901            "re-registered session should not be silenced; stale entry should be skipped"
902        );
903    }
904}