Skip to main content

omni_dev/sessions/
stream.rs

1//! The stream-json tracker (Feed 4): the pure state machine behind
2//! `omni-dev claude-wrap`, turning Claude's `--output-format stream-json` stdio
3//! into [`ObserveRequest`]s for the [`SessionsRegistry`].
4//!
5//! Unlike the other three feeds this one is **authoritative**. Hooks and the
6//! transcript watcher observe a session from the outside and infer what it is
7//! doing; the wrapper sits *in* the stream the Claude VS Code extension itself
8//! reads, so it sees the exact protocol events — including `can_use_tool`, the
9//! permission prompt that never reaches a transcript and is therefore invisible
10//! to Feeds 1–3 unless the user has the `Notification` hook installed. See
11//! ADR-0057.
12//!
13//! Both directions matter. A permission request travels **CLI → editor** on the
14//! child's stdout as a `control_request`; its resolution travels **editor → CLI**
15//! on the child's stdin as a `control_response`. Correlating the two by
16//! `request_id` is what makes `waiting_for_permission` exact rather than a guess,
17//! so [`StreamTracker::observe_line`] takes the [`Direction`] a line was seen in.
18//! A model switch can be the same shape the other way around: `set_model` is a
19//! `control_request` an SDK-driven caller can send **to** the CLI, over a
20//! *live* process's stdin, to switch models without waiting for the next
21//! turn's `system`/`init` line (#1448 follow-up). In practice this rarely
22//! fires for the Claude VS Code extension itself: its in-chat `/model` command
23//! is a local UI action that never sends `set_model` at all (it mutates local
24//! state and persists to the user's settings file instead), and the extension
25//! respawns a fresh wrapped process per turn rather than keeping one alive —
26//! so for that caller, a switch is still only observed via the next turn's
27//! `system`/`init` line, same as every other identity field here.
28//!
29//! Nothing here does I/O and nothing here retains conversation content: only the
30//! message `type`/`subtype`, the identity fields (`session_id`, `cwd`, `model`)
31//! and outstanding permission ids are ever read out of a line. Every parse is
32//! best-effort — an unparseable or unrecognized line is ignored, never fatal,
33//! because the wrapper must fail open (see [`crate::cli::claude_wrap`]).
34//!
35//! [`SessionsRegistry`]: super::SessionsRegistry
36
37use std::collections::HashSet;
38use std::path::PathBuf;
39
40use serde::Deserialize;
41
42use super::{ObserveRequest, SessionEvent, SessionState};
43
44/// Ceiling on simultaneously-outstanding permission requests tracked at once.
45///
46/// Claude asks about one tool at a time in practice, so this only bounds memory
47/// against a malformed or adversarial stream; ids past the cap are dropped,
48/// which can only ever make the tracker return to `working` early.
49const MAX_PENDING_PERMISSIONS: usize = 64;
50
51/// Which side of the wrapped process's stdio a line was observed on.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Direction {
54    /// A line the wrapped `claude` wrote to its **stdout** (CLI → editor).
55    FromClaude,
56    /// A line the editor wrote to the wrapped `claude`'s **stdin** (editor → CLI).
57    ToClaude,
58}
59
60/// The subset of a stream-json line this tracker reads.
61///
62/// Deliberately minimal and fully optional: the stream schema is Claude Code's
63/// internal protocol, so anything unrecognized must deserialize successfully and
64/// be ignored rather than break the feed. Conversation content (`message`,
65/// tool inputs, results) is never named here, so it is never even materialized.
66#[derive(Debug, Default, Deserialize)]
67struct StreamLine {
68    /// The message kind: `system`, `assistant`, `user`, `result`, `stream_event`,
69    /// `control_request`, `control_response`, …
70    #[serde(rename = "type", default)]
71    kind: Option<String>,
72    /// The `system` message's discriminator, notably `init`.
73    #[serde(default)]
74    subtype: Option<String>,
75    /// The Claude session id, carried on most messages.
76    #[serde(default)]
77    session_id: Option<String>,
78    /// The session's working directory, carried on `system`/`init`.
79    #[serde(default)]
80    cwd: Option<PathBuf>,
81    /// The model id, carried on `system`/`init`.
82    #[serde(default)]
83    model: Option<String>,
84    /// A control message's correlation id, when carried at the top level.
85    #[serde(default)]
86    request_id: Option<String>,
87    /// A `control_request`'s body.
88    #[serde(default)]
89    request: Option<ControlBody>,
90    /// A `control_response`'s body.
91    #[serde(default)]
92    response: Option<ControlBody>,
93}
94
95/// The shared shape of a `control_request` / `control_response` body.
96#[derive(Debug, Default, Deserialize)]
97struct ControlBody {
98    /// The control kind, e.g. `can_use_tool`, `initialize`, `hook_callback`,
99    /// `set_model`.
100    #[serde(default)]
101    subtype: Option<String>,
102    /// The correlation id, when carried inside the body rather than at the top
103    /// level (a `control_response` echoes it here).
104    #[serde(default)]
105    request_id: Option<String>,
106    /// A `set_model` request's target model id. Per Claude Code's own schema
107    /// this field is optional and simply **absent** when the editor asks to
108    /// reset to the account/session default (a value only the CLI itself can
109    /// resolve) — that case is left for the next `system`/`init` line to
110    /// settle. The literal string `"default"` is guarded against too, purely
111    /// defensively: nothing in the documented protocol sends it, but nothing
112    /// rules out a caller that does.
113    #[serde(default)]
114    model: Option<String>,
115}
116
117/// The authoritative session-state machine over one wrapped `claude` process.
118///
119/// Feed it every line of both stdio directions; it returns an [`ObserveRequest`]
120/// exactly when the session's effective state *changes*, so a long turn costs one
121/// report at its start and one at its end rather than one per streamed token.
122#[derive(Debug)]
123pub struct StreamTracker {
124    /// The session id, learned from the first line that carries one.
125    session_id: Option<String>,
126    /// The session's working directory, learned from `system`/`init`.
127    cwd: Option<PathBuf>,
128    /// The model currently in use: from the most recent `system`/`init` line,
129    /// or — sooner — a `set_model` `control_request` the editor sent. Unlike
130    /// `session_id`/`cwd`, this is **not** fill-once: Claude Code re-emits
131    /// `system`/`init` — model included — at the start of every turn (not just
132    /// session start), and a `set_model` request updates it immediately, at
133    /// the moment of the switch rather than the next turn (#1448 follow-up).
134    model: Option<String>,
135    /// The state implied by the most recent content message, before the
136    /// permission overlay is applied.
137    base: SessionState,
138    /// The `request_id`s of permission prompts asked but not yet answered.
139    pending: HashSet<String>,
140    /// The (state, model) pair most recently returned to the caller, for
141    /// change detection. Both dimensions are tracked because they change
142    /// independently: an ordinary turn changes state without the model, while
143    /// a mid-turn `set_model` changes the model without the state.
144    reported: Option<(SessionState, Option<String>)>,
145}
146
147impl StreamTracker {
148    /// Creates a tracker for one wrapped process, before any line is seen.
149    #[must_use]
150    pub fn new() -> Self {
151        Self {
152            session_id: None,
153            cwd: None,
154            model: None,
155            // A `claude` that has started but has not been prompted is sitting at
156            // the prompt: idle, not "starting". `Starting` stays the hook feed's
157            // (very brief) `SessionStart` state, so both feeds agree that a tab
158            // the user opened and has not typed into is not doing work.
159            base: SessionState::Idle,
160            pending: HashSet::new(),
161            reported: None,
162        }
163    }
164
165    /// The session id, once a line has carried one.
166    #[must_use]
167    pub fn session_id(&self) -> Option<&str> {
168        self.session_id.as_deref()
169    }
170
171    /// Feeds one stdio line and returns a sighting when the effective state
172    /// changed as a result.
173    ///
174    /// Returns `None` for every line that is unparseable, unrecognized, seen
175    /// before the session id is known, or that leaves the state unchanged.
176    pub fn observe_line(&mut self, direction: Direction, line: &str) -> Option<ObserveRequest> {
177        let line = line.trim();
178        if line.is_empty() {
179            return None;
180        }
181        let parsed: StreamLine = serde_json::from_str(line).ok()?;
182        self.absorb_identity(direction, &parsed);
183        self.apply(direction, &parsed);
184        self.emit_if_changed()
185    }
186
187    /// Re-reports the current state, so a session that has been silent for a
188    /// while does not age out of the registry on its TTL.
189    ///
190    /// The wrapper lives exactly as long as the `claude` process does, so this
191    /// is real liveness rather than the activity-based approximation the hook and
192    /// transcript feeds are limited to.
193    #[must_use]
194    pub fn keepalive(&self) -> Option<ObserveRequest> {
195        self.request(self.state())
196    }
197
198    /// Records the identity fields carried on a line: `session_id`/`cwd` are
199    /// fill-once (never overwriting a value already learned with a later
200    /// absent one), but `model` always takes the latest non-empty value seen,
201    /// from either of two shapes — see the field doc on [`Self::model`] for
202    /// why.
203    fn absorb_identity(&mut self, direction: Direction, parsed: &StreamLine) {
204        if self.session_id.is_none() {
205            if let Some(id) = parsed.session_id.as_deref() {
206                if !id.trim().is_empty() {
207                    self.session_id = Some(id.to_string());
208                }
209            }
210        }
211        if self.cwd.is_none() {
212            self.cwd.clone_from(&parsed.cwd);
213        }
214        // The top-level `model`, carried on a `system`/`init` line.
215        if let Some(model) = parsed.model.as_deref() {
216            if !model.trim().is_empty() {
217                self.model = Some(model.to_string());
218            }
219        }
220        // A `set_model` control_request, which — unlike every other identity
221        // signal here — travels editor → CLI, so it is only ever trusted on
222        // that direction (the same rule `close_permission` applies to a
223        // permission answer). An unresolved target — the field absent per the
224        // documented schema, or (defensively) the literal string "default" —
225        // cannot be resolved without the CLI's own account/session settings,
226        // so it is left alone rather than guessed; the next `system`/`init`
227        // line settles it instead.
228        //
229        // Note this path is only reachable while a wrapped process is alive:
230        // Claude Code's own in-chat `/model` command does not send this
231        // control_request at all (it mutates local state and persists to the
232        // user's settings file instead), and the VS Code extension respawns a
233        // fresh wrapped process per turn rather than keeping one alive across
234        // a whole conversation. So in practice, a model switch is still only
235        // observed at the start of the *next* turn's `system`/`init` line
236        // (handled above) — this block is a correctness improvement for
237        // whatever caller does send `set_model` to a live process (e.g. an
238        // external SDK-driven consumer), not a guaranteed instant path for
239        // this extension's own in-chat command.
240        if direction == Direction::ToClaude && parsed.kind.as_deref() == Some("control_request") {
241            if let Some(model) = parsed
242                .request
243                .as_ref()
244                .filter(|body| body.subtype.as_deref() == Some("set_model"))
245                .and_then(|body| body.model.as_deref())
246            {
247                if !model.trim().is_empty() && model != "default" {
248                    self.model = Some(model.to_string());
249                }
250            }
251        }
252    }
253
254    /// Applies a line's state effect: content messages move [`Self::base`],
255    /// control messages open and close permission prompts.
256    fn apply(&mut self, direction: Direction, parsed: &StreamLine) {
257        match parsed.kind.as_deref() {
258            // The session announced itself but has not been prompted yet.
259            Some("system") if parsed.subtype.as_deref() == Some("init") => {
260                self.base = SessionState::Idle;
261            }
262            // A replayed user prompt, a streamed assistant reply, or a tool
263            // result: the turn is running.
264            Some("assistant" | "user" | "stream_event") => self.base = SessionState::Working,
265            // The turn finished. Also the drift backstop: if the stream ever
266            // stops answering a permission request in a shape this tracker
267            // recognizes, a completed turn unwedges it rather than pinning the
268            // session on `waiting_for_permission` forever.
269            Some("result") => {
270                self.base = SessionState::Idle;
271                self.pending.clear();
272            }
273            Some("control_request") if direction == Direction::FromClaude => {
274                self.open_permission(parsed);
275            }
276            Some("control_response") if direction == Direction::ToClaude => {
277                self.close_permission(parsed);
278            }
279            _ => {}
280        }
281    }
282
283    /// Records a `can_use_tool` request as outstanding; every other control
284    /// subtype (`initialize`, `hook_callback`, `mcp_message`, …) carries no
285    /// state signal and is ignored.
286    fn open_permission(&mut self, parsed: &StreamLine) {
287        let body = parsed.request.as_ref();
288        if body.and_then(|b| b.subtype.as_deref()) != Some("can_use_tool") {
289            return;
290        }
291        let Some(id) = correlation_id(parsed, body) else {
292            return;
293        };
294        if self.pending.len() < MAX_PENDING_PERMISSIONS {
295            self.pending.insert(id);
296        }
297    }
298
299    /// Clears the permission request a `control_response` answers.
300    fn close_permission(&mut self, parsed: &StreamLine) {
301        let body = parsed.response.as_ref();
302        if let Some(id) = correlation_id(parsed, body) {
303            self.pending.remove(&id);
304        }
305    }
306
307    /// The effective state: an outstanding permission prompt outranks whatever
308    /// the content messages last implied, so a reply that keeps streaming while
309    /// the user is being asked to approve a tool cannot mask the prompt.
310    fn state(&self) -> SessionState {
311        if self.pending.is_empty() {
312            self.base
313        } else {
314            SessionState::WaitingForPermission
315        }
316    }
317
318    /// Returns a sighting when the effective state or the model differs from
319    /// what was last reported, and records the new pair as reported. Emitting
320    /// on a model-only change (no state change) is what makes a `set_model`
321    /// control_request reach the daemon immediately rather than waiting for
322    /// the next state transition to carry it along.
323    fn emit_if_changed(&mut self) -> Option<ObserveRequest> {
324        let state = self.state();
325        let signature = (state, self.model.clone());
326        if self.reported.as_ref() == Some(&signature) {
327            return None;
328        }
329        let request = self.request(state)?;
330        self.reported = Some(signature);
331        Some(request)
332    }
333
334    /// Builds the sighting for `state`, or `None` while the session id is still
335    /// unknown (nothing can be keyed without it).
336    fn request(&self, state: SessionState) -> Option<ObserveRequest> {
337        Some(ObserveRequest {
338            session_id: self.session_id.clone()?,
339            cwd: self.cwd.clone(),
340            transcript_path: None,
341            event: SessionEvent::StreamState(state),
342            repo: None,
343            model: self.model.clone(),
344        })
345    }
346}
347
348impl Default for StreamTracker {
349    fn default() -> Self {
350        Self::new()
351    }
352}
353
354/// A control message's correlation id, from the body when present (where a
355/// `control_response` echoes it) and otherwise from the top level.
356fn correlation_id(parsed: &StreamLine, body: Option<&ControlBody>) -> Option<String> {
357    body.and_then(|b| b.request_id.clone())
358        .or_else(|| parsed.request_id.clone())
359}
360
361#[cfg(test)]
362#[allow(clippy::unwrap_used, clippy::expect_used)]
363mod tests {
364    use super::*;
365
366    const INIT: &str = r#"{"type":"system","subtype":"init","session_id":"sess-1","cwd":"/w/repo","model":"claude-opus-5","tools":["Read"]}"#;
367
368    fn tracker_after_init() -> StreamTracker {
369        let mut tracker = StreamTracker::new();
370        let first = tracker
371            .observe_line(Direction::FromClaude, INIT)
372            .expect("init announces the session");
373        assert_eq!(first.session_id, "sess-1");
374        tracker
375    }
376
377    fn state_of(request: &ObserveRequest) -> SessionState {
378        match request.event {
379            SessionEvent::StreamState(state) => state,
380            other => panic!("expected a stream state, got {other:?}"),
381        }
382    }
383
384    #[test]
385    fn init_announces_the_session_as_idle_with_its_identity() {
386        let mut tracker = StreamTracker::new();
387        let request = tracker.observe_line(Direction::FromClaude, INIT).unwrap();
388        assert_eq!(request.session_id, "sess-1");
389        assert_eq!(
390            request.cwd.as_deref(),
391            Some(std::path::Path::new("/w/repo"))
392        );
393        assert_eq!(request.model.as_deref(), Some("claude-opus-5"));
394        // A started-but-unprompted session sits at the prompt.
395        assert_eq!(state_of(&request), SessionState::Idle);
396        assert_eq!(tracker.session_id(), Some("sess-1"));
397    }
398
399    #[test]
400    fn nothing_is_reported_before_a_session_id_is_known() {
401        let mut tracker = StreamTracker::new();
402        // A content message with no session id moves the state but cannot be keyed.
403        assert!(tracker
404            .observe_line(Direction::FromClaude, r#"{"type":"assistant"}"#)
405            .is_none());
406        assert!(tracker.keepalive().is_none());
407        // …and the state it moved to is reported as soon as an id arrives.
408        let request = tracker
409            .observe_line(
410                Direction::FromClaude,
411                r#"{"type":"assistant","session_id":"sess-1"}"#,
412            )
413            .unwrap();
414        assert_eq!(state_of(&request), SessionState::Working);
415    }
416
417    #[test]
418    fn a_turn_reports_working_then_idle_once_each() {
419        let mut tracker = tracker_after_init();
420        let working = tracker
421            .observe_line(
422                Direction::FromClaude,
423                r#"{"type":"user","session_id":"sess-1"}"#,
424            )
425            .unwrap();
426        assert_eq!(state_of(&working), SessionState::Working);
427        // Streaming does not re-report: the state has not changed.
428        assert!(tracker
429            .observe_line(Direction::FromClaude, r#"{"type":"stream_event"}"#)
430            .is_none());
431        assert!(tracker
432            .observe_line(Direction::FromClaude, r#"{"type":"assistant"}"#)
433            .is_none());
434        let idle = tracker
435            .observe_line(
436                Direction::FromClaude,
437                r#"{"type":"result","subtype":"success"}"#,
438            )
439            .unwrap();
440        assert_eq!(state_of(&idle), SessionState::Idle);
441    }
442
443    #[test]
444    fn a_set_model_request_updates_and_reports_the_model_immediately() {
445        // `set_model` travels editor -> CLI at the exact moment the user
446        // switches models — no turn required to observe it (#1448 follow-up).
447        let mut tracker = tracker_after_init(); // model = claude-opus-5
448        let switched = tracker
449            .observe_line(
450                Direction::ToClaude,
451                r#"{"type":"control_request","request_id":"c1","request":{"subtype":"set_model","model":"claude-sonnet-5"}}"#,
452            )
453            .unwrap();
454        assert_eq!(switched.model.as_deref(), Some("claude-sonnet-5"));
455        // The state itself did not change — this session is still idle.
456        assert_eq!(state_of(&switched), SessionState::Idle);
457    }
458
459    #[test]
460    fn a_set_model_with_no_model_field_is_left_for_the_next_init_to_settle() {
461        // Per the documented schema, "reset to the account/session default" is
462        // signaled by omitting `model` entirely, not by a literal value — that
463        // cannot be resolved without the CLI's own settings, so it is not
464        // taken at face value...
465        let mut tracker = tracker_after_init(); // model = claude-opus-5
466        assert!(tracker
467            .observe_line(
468                Direction::ToClaude,
469                r#"{"type":"control_request","request_id":"c1","request":{"subtype":"set_model"}}"#,
470            )
471            .is_none());
472        // ...and the model is unchanged until the next turn's init resolves it.
473        let switched_init = r#"{"type":"system","subtype":"init","session_id":"sess-1","cwd":"/w/repo","model":"claude-haiku-4-5","tools":["Read"]}"#;
474        let resolved = tracker
475            .observe_line(Direction::FromClaude, switched_init)
476            .unwrap();
477        assert_eq!(resolved.model.as_deref(), Some("claude-haiku-4-5"));
478    }
479
480    #[test]
481    fn a_set_model_literal_default_string_is_also_left_unresolved() {
482        // Defensive only: nothing in the documented schema sends the literal
483        // string "default" (the field is simply omitted instead — see the
484        // previous test), but a hypothetical caller that did should not have
485        // that string taken as a real model id either.
486        let mut tracker = tracker_after_init(); // model = claude-opus-5
487        assert!(tracker
488            .observe_line(
489                Direction::ToClaude,
490                r#"{"type":"control_request","request_id":"c1","request":{"subtype":"set_model","model":"default"}}"#,
491            )
492            .is_none());
493        assert_eq!(
494            tracker.keepalive().unwrap().model.as_deref(),
495            Some("claude-opus-5")
496        );
497    }
498
499    #[test]
500    fn a_set_model_request_is_only_honored_from_the_editor() {
501        // The same line seen on the wrong direction (as if Claude itself sent
502        // it) is not trusted, mirroring the permission-response direction rule.
503        let mut tracker = tracker_after_init(); // model = claude-opus-5
504        assert!(tracker
505            .observe_line(
506                Direction::FromClaude,
507                r#"{"type":"control_request","request_id":"c1","request":{"subtype":"set_model","model":"claude-sonnet-5"}}"#,
508            )
509            .is_none());
510        assert_eq!(
511            tracker.keepalive().unwrap().model.as_deref(),
512            Some("claude-opus-5")
513        );
514    }
515
516    #[test]
517    fn a_later_init_confirming_the_already_set_model_does_not_re_emit() {
518        // Claude Code re-announces itself via `system`/`init` at the start of
519        // every turn, not just session start. Once `set_model` has already
520        // moved the tracker to the new model, that turn's init line — which
521        // confirms the same model — is a no-op rather than a redundant report.
522        let mut tracker = tracker_after_init(); // model = claude-opus-5
523        tracker.observe_line(
524            Direction::ToClaude,
525            r#"{"type":"control_request","request_id":"c1","request":{"subtype":"set_model","model":"claude-sonnet-5"}}"#,
526        );
527        let confirming_init = r#"{"type":"system","subtype":"init","session_id":"sess-1","cwd":"/w/repo","model":"claude-sonnet-5","tools":["Read"]}"#;
528        assert!(tracker
529            .observe_line(Direction::FromClaude, confirming_init)
530            .is_none());
531    }
532
533    #[test]
534    fn a_permission_prompt_reports_waiting_until_it_is_answered() {
535        let mut tracker = tracker_after_init();
536        tracker.observe_line(Direction::FromClaude, r#"{"type":"assistant"}"#);
537        let waiting = tracker
538            .observe_line(
539                Direction::FromClaude,
540                r#"{"type":"control_request","request_id":"req-1","request":{"subtype":"can_use_tool","tool_name":"Bash"}}"#,
541            )
542            .unwrap();
543        assert_eq!(state_of(&waiting), SessionState::WaitingForPermission);
544        // Content still streaming while the user is asked must not mask the prompt.
545        assert!(tracker
546            .observe_line(Direction::FromClaude, r#"{"type":"assistant"}"#)
547            .is_none());
548        // The answer arrives on the *other* direction, echoing the id in its body.
549        let resumed = tracker
550            .observe_line(
551                Direction::ToClaude,
552                r#"{"type":"control_response","response":{"subtype":"success","request_id":"req-1"}}"#,
553            )
554            .unwrap();
555        assert_eq!(state_of(&resumed), SessionState::Working);
556    }
557
558    #[test]
559    fn a_permission_response_is_only_honored_from_the_editor() {
560        let mut tracker = tracker_after_init();
561        tracker.observe_line(
562            Direction::FromClaude,
563            r#"{"type":"control_request","request_id":"req-1","request":{"subtype":"can_use_tool"}}"#,
564        );
565        // The same line seen on the wrong direction is not the answer.
566        assert!(tracker
567            .observe_line(
568                Direction::FromClaude,
569                r#"{"type":"control_response","response":{"request_id":"req-1"}}"#,
570            )
571            .is_none());
572        assert_eq!(
573            state_of(&tracker.keepalive().unwrap()),
574            SessionState::WaitingForPermission
575        );
576    }
577
578    #[test]
579    fn other_control_subtypes_carry_no_state_signal() {
580        let mut tracker = tracker_after_init();
581        for subtype in ["initialize", "hook_callback", "mcp_message", "interrupt"] {
582            let line = format!(
583                r#"{{"type":"control_request","request_id":"c","request":{{"subtype":"{subtype}"}}}}"#
584            );
585            assert!(tracker.observe_line(Direction::FromClaude, &line).is_none());
586        }
587        assert_eq!(state_of(&tracker.keepalive().unwrap()), SessionState::Idle);
588    }
589
590    #[test]
591    fn a_finished_turn_unwedges_a_stranded_permission() {
592        let mut tracker = tracker_after_init();
593        tracker.observe_line(
594            Direction::FromClaude,
595            r#"{"type":"control_request","request_id":"req-1","request":{"subtype":"can_use_tool"}}"#,
596        );
597        // No matching response ever arrives (protocol drift); `result` still ends
598        // the turn rather than pinning the session on `waiting_for_permission`.
599        let idle = tracker
600            .observe_line(Direction::FromClaude, r#"{"type":"result"}"#)
601            .unwrap();
602        assert_eq!(state_of(&idle), SessionState::Idle);
603    }
604
605    #[test]
606    fn outstanding_permissions_are_capped() {
607        let mut tracker = tracker_after_init();
608        for i in 0..(MAX_PENDING_PERMISSIONS + 10) {
609            let line = format!(
610                r#"{{"type":"control_request","request_id":"req-{i}","request":{{"subtype":"can_use_tool"}}}}"#
611            );
612            tracker.observe_line(Direction::FromClaude, &line);
613        }
614        assert_eq!(tracker.pending.len(), MAX_PENDING_PERMISSIONS);
615    }
616
617    #[test]
618    fn a_blank_session_id_is_not_taken_as_identity() {
619        let mut tracker = StreamTracker::new();
620        assert!(tracker
621            .observe_line(
622                Direction::FromClaude,
623                r#"{"type":"assistant","session_id":"   "}"#,
624            )
625            .is_none());
626        assert_eq!(tracker.session_id(), None);
627        // …and a real id later still lands.
628        tracker.observe_line(Direction::FromClaude, INIT);
629        assert_eq!(tracker.session_id(), Some("sess-1"));
630    }
631
632    #[test]
633    fn control_messages_with_no_correlation_id_are_ignored() {
634        let mut tracker = tracker_after_init();
635        // A permission request that cannot be correlated is not tracked, rather
636        // than pinning the session on a prompt nothing can ever answer.
637        assert!(tracker
638            .observe_line(
639                Direction::FromClaude,
640                r#"{"type":"control_request","request":{"subtype":"can_use_tool"}}"#,
641            )
642            .is_none());
643        assert_eq!(state_of(&tracker.keepalive().unwrap()), SessionState::Idle);
644        // Likewise an answer that names no request clears nothing.
645        tracker.observe_line(
646            Direction::FromClaude,
647            r#"{"type":"control_request","request_id":"r1","request":{"subtype":"can_use_tool"}}"#,
648        );
649        assert!(tracker
650            .observe_line(Direction::ToClaude, r#"{"type":"control_response"}"#)
651            .is_none());
652        assert_eq!(
653            state_of(&tracker.keepalive().unwrap()),
654            SessionState::WaitingForPermission
655        );
656    }
657
658    #[test]
659    fn default_matches_a_fresh_tracker() {
660        let tracker = StreamTracker::default();
661        assert_eq!(tracker.session_id(), None);
662        assert!(tracker.keepalive().is_none());
663    }
664
665    #[test]
666    fn unparseable_and_unknown_lines_are_ignored() {
667        let mut tracker = tracker_after_init();
668        for line in [
669            "",
670            "   ",
671            "not json at all",
672            "{",
673            "[]",
674            r#"{"type":"nonsense"}"#,
675            r#"{"no_type":true}"#,
676        ] {
677            assert!(tracker.observe_line(Direction::FromClaude, line).is_none());
678        }
679        assert_eq!(state_of(&tracker.keepalive().unwrap()), SessionState::Idle);
680    }
681
682    #[test]
683    fn keepalive_re_reports_the_current_state_without_a_change() {
684        let mut tracker = tracker_after_init();
685        tracker.observe_line(Direction::FromClaude, r#"{"type":"assistant"}"#);
686        let first = tracker.keepalive().unwrap();
687        let second = tracker.keepalive().unwrap();
688        assert_eq!(state_of(&first), SessionState::Working);
689        assert_eq!(state_of(&second), SessionState::Working);
690        assert_eq!(first.session_id, "sess-1");
691    }
692}