Skip to main content

muse_code_sdk/
fold.rs

1//! Ephemeral fold. Params stay as JSON so newer open values survive verbatim.
2
3use std::collections::{HashMap, HashSet};
4
5use serde_json::{Map, Value};
6
7use crate::msp::{Notification, ViewGapParams};
8
9mod approvals;
10mod items;
11mod requests;
12mod turns;
13mod types;
14
15pub use approvals::PendingApproval;
16pub use items::{ItemOutcome, Items};
17pub use types::{DeliveryGap, FoldOutcome, SessionState, Turn, TurnState};
18
19use approvals::Approvals;
20use requests::{Requests, in_observed_order, params_of, request, resolve};
21
22/// A fold must be bound to one server session at construction.
23///
24/// ```compile_fail
25/// use muse_code_sdk::fold::SessionFold;
26///
27/// let unbound = SessionFold::default();
28/// ```
29#[derive(Debug)]
30pub struct SessionFold {
31    session_id: String,
32    items: Items,
33    state: SessionState,
34    turns: HashMap<String, Turn>,
35    // Turn ids in first-seen order; turns are never removed.
36    turn_order: Vec<String>,
37    active_turn: Option<String>,
38    approvals: Approvals,
39    user_inputs: Requests,
40    gap: Option<DeliveryGap>,
41    // In a standalone fold, every `next` a `view/gap` named while `gap` is
42    // pending, as the `Session` walk keeps its targets: a repeated one is a
43    // stale frame, not a new target.
44    gap_targets: HashSet<String>,
45    // Set by the owning `Session` once an event was lost; nothing folds after.
46    lost: bool,
47    // Set once its id was opened again on the same client; only question
48    // events fold after.
49    reopened: bool,
50}
51
52impl SessionFold {
53    /// An empty fold bound to `session_id`: events for any other session are
54    /// ignored.
55    pub fn new(session_id: impl Into<String>) -> Self {
56        Self {
57            session_id: session_id.into(),
58            items: Items::default(),
59            state: SessionState::default(),
60            turns: HashMap::new(),
61            turn_order: Vec::new(),
62            active_turn: None,
63            approvals: Approvals::default(),
64            user_inputs: Requests::default(),
65            gap: None,
66            gap_targets: HashSet::new(),
67            lost: false,
68            reopened: false,
69        }
70    }
71    /// The items the fold holds.
72    pub const fn items(&self) -> &Items {
73        &self.items
74    }
75    /// The latest params of each session-state notification the fold applied.
76    pub const fn session_state(&self) -> &SessionState {
77        &self.state
78    }
79    /// The turn whose `turn/started` the fold applied last, until that turn
80    /// completes, is retracted or is unqueued.
81    pub fn active_turn_id(&self) -> Option<&str> {
82        self.active_turn.as_deref()
83    }
84    /// The record of turn `id`, or `None` when no turn event the fold applied
85    /// named it.
86    pub fn turn(&self, id: &str) -> Option<&Turn> {
87        self.turns.get(id)
88    }
89    pub(crate) fn turn_ids(&self) -> &[String] {
90        &self.turn_order
91    }
92    /// The delivery gap the fold has pending, or `None`. A stopped fold keeps
93    /// its last gap, which nothing fills.
94    pub const fn pending_gap(&self) -> Option<&DeliveryGap> {
95        self.gap.as_ref()
96    }
97    /// False while a delivery gap is pending, and for good once the owning
98    /// `Session` lost an event or its session id was opened again on the
99    /// same client.
100    pub const fn is_current(&self) -> bool {
101        self.gap.is_none() && !self.is_stopped()
102    }
103    /// Clears the pending gap when `next` is its `next` cursor and returns
104    /// true; any other cursor leaves the gap in place and returns false.
105    pub fn gap_filled(&mut self, next: &str) -> bool {
106        if self.gap.as_ref().map(|gap| gap.next.as_str()) != Some(next) {
107            return false;
108        }
109        self.gap = None;
110        self.gap_targets.clear();
111        true
112    }
113
114    /// The latest params seen for a pending approval: its `approval/updated`
115    /// refresh if any, else its request. `pending_approvals` keeps both.
116    pub fn pending_approval(&self, id: &str) -> Option<&Value> {
117        self.approvals.latest(id)
118    }
119
120    /// The first `approval/resolved` params of approval `id`; a later
121    /// terminal never replaces it.
122    pub fn resolved_approval(&self, id: &str) -> Option<&Value> {
123        self.approvals.resolved(id)
124    }
125
126    /// Approvals awaiting a durable terminal, in the order they were first
127    /// requested, each with its latest request and latest update.
128    pub fn pending_approvals(&self) -> Vec<&PendingApproval> {
129        self.approvals.pending_in_order()
130    }
131
132    /// The first durable terminal per approval, in the order those first
133    /// terminals arrived.
134    pub fn resolved_approvals(&self) -> Vec<&Value> {
135        self.approvals.resolved_in_order()
136    }
137
138    /// The latest `userInput/requested` params of question `id` while it
139    /// awaits its first settlement.
140    pub fn pending_user_input(&self, id: &str) -> Option<&Value> {
141        params_of(self.user_inputs.pending.get(id))
142    }
143
144    /// The first `userInput/settled` params of question `id`; a later
145    /// settlement never replaces it.
146    pub fn settled_user_input(&self, id: &str) -> Option<&Value> {
147        params_of(self.user_inputs.resolved.get(id))
148    }
149
150    /// Questions awaiting a durable settlement, in the order they were first
151    /// requested.
152    pub fn pending_user_inputs(&self) -> Vec<&Value> {
153        in_observed_order(&self.user_inputs.pending)
154    }
155
156    /// The first durable settlement per question, in the order those first
157    /// settlements arrived.
158    pub fn settled_user_inputs(&self) -> Vec<&Value> {
159        in_observed_order(&self.user_inputs.resolved)
160    }
161
162    /// Folds one event and reports what it changed. Events for another
163    /// session and malformed params change nothing. After the owning
164    /// `Session` stops the fold it applies nothing, or only question events
165    /// after a re-open.
166    pub fn apply(&mut self, event: &Notification) -> FoldOutcome {
167        if self.lost {
168            return FoldOutcome::Ignored;
169        }
170        let method = event.method.as_str();
171        // Question events are safe to see twice, and a turn that asks one
172        // must stay answerable, so a re-opened fold still takes them.
173        if self.reopened && !matches!(method, "userInput/requested" | "userInput/settled") {
174            return FoldOutcome::Ignored;
175        }
176        let Some(params) = event.params.as_ref() else {
177            return FoldOutcome::Ignored;
178        };
179        if string(params, "sessionId") != Some(self.session_id.as_str()) {
180            return FoldOutcome::Ignored;
181        }
182        match method {
183            "item/started" | "item/updated" | "item/completed" => self.item(method, params),
184            "item/delta" => self.delta(params),
185            "turn/started" | "turn/completed" | "turn/retracted" | "turn/unqueued" => {
186                self.turn_event(method, params)
187            }
188            "approval/requested" => applied(
189                string(params, "approvalId").is_some_and(|id| self.approvals.request(id, params)),
190            ),
191            "approval/updated" => applied(
192                string(params, "approvalId").is_some_and(|id| self.approvals.update(id, params)),
193            ),
194            "approval/resolved" => {
195                string(params, "approvalId").map_or(FoldOutcome::Ignored, |id| {
196                    FoldOutcome::Resolution {
197                        first: self.approvals.resolve(id, params),
198                    }
199                })
200            }
201            // A prompt for a turn this fold has already seen leave
202            // `Running` is an orphan: no answer can settle it, so listing
203            // it would pend forever. Guarded to KNOWN dead turns only — a
204            // prompt naming a turn the fold has never seen (a fresh resume
205            // re-sending a still-open question) still lists.
206            "userInput/requested" => {
207                let dead = string(params, "turnId").is_some_and(|turn_id| {
208                    self.turns
209                        .get(turn_id)
210                        .is_some_and(|turn| turn.state() != TurnState::Running)
211                });
212                if dead {
213                    FoldOutcome::Ignored
214                } else {
215                    request(&mut self.user_inputs, params, "userInputId")
216                }
217            }
218            "userInput/settled" => resolve(&mut self.user_inputs, params, "userInputId"),
219            "view/gap" => self.delivery_gap(params),
220            family if is_state_family(family) => {
221                self.state
222                    .0
223                    .insert(family.to_owned(), Value::Object(params.clone()));
224                FoldOutcome::Applied
225            }
226            _ => FoldOutcome::Ignored,
227        }
228    }
229
230    /// Seeds one raw resume-history item as of the resume cursor, keeping
231    /// members this SDK does not know; an `inProgress` item stays open to the
232    /// deltas that follow.
233    pub(crate) fn seed_history_item(&mut self, item: &Map<String, Value>) {
234        let method = if string(item, "status") == Some("inProgress") {
235            "item/updated"
236        } else {
237            "item/completed"
238        };
239        self.item(
240            method,
241            &Map::from_iter([("item".to_owned(), Value::Object(item.clone()))]),
242        );
243    }
244
245    /// Follows the owning session's gap fill: its pending hole is the one the
246    /// walk fills, so currency tracks the walk rather than this fold's own
247    /// `view/gap` coalescing. A stopped fold keeps its
248    /// last currency.
249    pub(crate) fn track_gap(&mut self, gap: Option<&ViewGapParams>) {
250        if self.is_stopped() {
251            return;
252        }
253        self.gap = gap.map(|gap| DeliveryGap {
254            after: gap.after.clone(),
255            next: gap.next.clone(),
256        });
257        // Only keeps the field consistent: a `Session`-owned fold never folds a
258        // `view/gap` itself, so nothing reads these targets.
259        self.gap_targets = gap.map(|gap| gap.next.clone()).into_iter().collect();
260    }
261
262    /// The owning session lost an event, or cannot prove it did not: stop
263    /// folding and stay not current, so the fold never passes for complete.
264    pub(crate) fn mark_lost(&mut self) {
265        self.lost = true;
266    }
267
268    /// The owning session's id was opened again on the same client, so an
269    /// event may reach it twice or reach another `Session` instead: stop
270    /// everything but question events and stay not current.
271    pub(crate) fn mark_reopened(&mut self) {
272        self.reopened = true;
273    }
274
275    pub(crate) const fn is_stopped(&self) -> bool {
276        self.lost || self.reopened
277    }
278
279    /// A pending hole that nothing can fill any more stops the fold.
280    pub(crate) fn stop_if_gap_pending(&mut self) {
281        if self.gap.is_some() {
282            self.lost = true;
283        }
284    }
285
286    fn delivery_gap(&mut self, params: &Map<String, Value>) -> FoldOutcome {
287        let (Some(after), Some(next)) = (string(params, "after"), string(params, "next")) else {
288            return FoldOutcome::Ignored;
289        };
290        match self.gap.as_mut() {
291            None => {
292                self.gap = Some(DeliveryGap {
293                    after: after.to_owned(),
294                    next: next.to_owned(),
295                });
296                self.gap_targets = HashSet::from([next.to_owned()]);
297                FoldOutcome::Applied
298            }
299            // A later gap while one is pending keeps the first `after` and takes
300            // the newest `next`, contiguous or not, as the `Session` gap walk
301            // and the TypeScript fold do. Keeping only the first range would
302            // report current while the later hole's events never arrived. A
303            // `next` already named while this gap is pending is a stale frame
304            // and changes nothing, as in the walk.
305            Some(gap) if self.gap_targets.insert(next.to_owned()) => {
306                gap.next = next.to_owned();
307                FoldOutcome::Applied
308            }
309            Some(_) => FoldOutcome::Ignored,
310        }
311    }
312}
313const fn applied(applied: bool) -> FoldOutcome {
314    if applied {
315        FoldOutcome::Applied
316    } else {
317        FoldOutcome::Ignored
318    }
319}
320fn string<'a>(params: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
321    params.get(key).and_then(Value::as_str)
322}
323
324fn is_state_family(method: &str) -> bool {
325    matches!(
326        method,
327        "session/modelChanged"
328            | "session/reasoningEffortChanged"
329            | "session/goalChanged"
330            | "session/todoListChanged"
331            | "session/branchChanged"
332            | "session/tokenUsage"
333            | "session/contextUsage"
334            | "session/approvalModeChanged"
335            | "session/nameChanged"
336    )
337}
338
339#[cfg(test)]
340mod tests {
341    use serde_json::json;
342
343    use super::*;
344
345    fn event(method: &str, params: Value) -> Notification {
346        Notification {
347            jsonrpc: crate::msp::JsonRpcVersion::V2,
348            method: method.to_owned(),
349            params: params.as_object().cloned(),
350            emitted_at_ms: None,
351        }
352    }
353
354    /// A lost fold applies
355    /// nothing, question events included, even after a re-open, so a frame
356    /// that races past the router's failure check still cannot fold.
357    #[test]
358    fn a_lost_fold_applies_nothing_even_after_a_reopen() {
359        let question = |id: &str| {
360            event(
361                "userInput/requested",
362                json!({"sessionId": "session-1", "userInputId": id}),
363            )
364        };
365        let mut fold = SessionFold::new("session-1");
366        fold.mark_reopened();
367        assert_ne!(fold.apply(&question("input-before")), FoldOutcome::Ignored);
368        fold.mark_lost();
369        assert_eq!(fold.apply(&question("input-after")), FoldOutcome::Ignored);
370        assert_eq!(
371            fold.apply(&event(
372                "item/completed",
373                json!({"sessionId": "session-1", "item": {"itemId": "item-1", "revision": 1}})
374            )),
375            FoldOutcome::Ignored
376        );
377        assert_eq!(fold.pending_user_inputs().len(), 1);
378        assert!(fold.items().is_empty());
379    }
380
381    #[test]
382    fn a_question_for_a_known_dead_turn_is_not_listed_but_an_unseen_turn_still_lists() {
383        let question = |id: &str| {
384            event(
385                "userInput/requested",
386                json!({"sessionId": "session-1", "userInputId": id, "turnId": "turn-1"}),
387            )
388        };
389        let mut fold = SessionFold::new("session-1");
390        fold.apply(&event(
391            "turn/started",
392            json!({"sessionId": "session-1", "turnId": "turn-1", "commandId": "cmd-1"}),
393        ));
394        fold.apply(&event(
395            "turn/completed",
396            json!({"sessionId": "session-1", "turnId": "turn-1", "terminal": "completed"}),
397        ));
398        assert_eq!(fold.apply(&question("input-dead")), FoldOutcome::Ignored);
399        assert!(fold.pending_user_inputs().is_empty());
400
401        let mut fresh = SessionFold::new("session-1");
402        assert_ne!(fresh.apply(&question("input-fresh")), FoldOutcome::Ignored);
403        assert_eq!(fresh.pending_user_inputs().len(), 1);
404    }
405
406    #[test]
407    fn dead_turn_questions_and_listed_prompt_retirement_cover_every_turn_end() {
408        let question = |id: &str| {
409            event(
410                "userInput/requested",
411                json!({"sessionId": "session-1", "userInputId": id, "turnId": "turn-1"}),
412            )
413        };
414        let started = || {
415            event(
416                "turn/started",
417                json!({"sessionId": "session-1", "turnId": "turn-1", "commandId": "cmd-1"}),
418            )
419        };
420        let ends: [(&str, Notification); 3] = [
421            (
422                "completed",
423                event(
424                    "turn/completed",
425                    json!({"sessionId": "session-1", "turnId": "turn-1", "terminal": "completed"}),
426                ),
427            ),
428            (
429                "retracted",
430                event(
431                    "turn/retracted",
432                    json!({"sessionId": "session-1", "turnId": "turn-1", "commandId": "cmd-1"}),
433                ),
434            ),
435            (
436                "unqueued",
437                event(
438                    "turn/unqueued",
439                    json!({"sessionId": "session-1", "turnId": "turn-1", "commandId": "cmd-1"}),
440                ),
441            ),
442        ];
443        for (_, end) in &ends {
444            // Arrival guard: a question first seen after the end never lists.
445            let mut fold = SessionFold::new("session-1");
446            fold.apply(&started());
447            fold.apply(end);
448            assert_eq!(fold.apply(&question("input-late")), FoldOutcome::Ignored);
449            assert!(fold.pending_user_inputs().is_empty());
450
451            // Reported order: listed while running, retired by the end,
452            // with no settlement recorded.
453            let mut fold = SessionFold::new("session-1");
454            fold.apply(&started());
455            assert_ne!(fold.apply(&question("input-1")), FoldOutcome::Ignored);
456            assert_eq!(fold.pending_user_inputs().len(), 1);
457            fold.apply(end);
458            assert!(fold.pending_user_inputs().is_empty());
459            assert!(fold.settled_user_inputs().is_empty());
460        }
461
462        // A declined retract leaves the turn running, so its prompt stays.
463        let mut fold = SessionFold::new("session-1");
464        fold.apply(&started());
465        fold.apply(&question("input-1"));
466        fold.apply(&event(
467            "turn/retracted",
468            json!({"sessionId": "session-1", "turnId": "turn-1", "commandId": "cmd-1", "outcome": "declined"}),
469        ));
470        assert_eq!(fold.pending_user_inputs().len(), 1);
471
472        // Another turn ending retires only its own prompts.
473        let question2 = event(
474            "userInput/requested",
475            json!({"sessionId": "session-1", "userInputId": "input-2", "turnId": "turn-2"}),
476        );
477        let mut fold = SessionFold::new("session-1");
478        fold.apply(&started());
479        fold.apply(&event(
480            "turn/started",
481            json!({"sessionId": "session-1", "turnId": "turn-2", "commandId": "cmd-2"}),
482        ));
483        fold.apply(&question("input-1"));
484        fold.apply(&question2);
485        fold.apply(&event(
486            "turn/completed",
487            json!({"sessionId": "session-1", "turnId": "turn-2", "terminal": "completed"}),
488        ));
489        assert_eq!(fold.pending_user_inputs().len(), 1);
490
491        // Unseen turn: the prompt lists, then its end frame retires it
492        // with no settlement recorded.
493        let mut fold = SessionFold::new("session-1");
494        fold.apply(&question("input-1"));
495        assert_eq!(fold.pending_user_inputs().len(), 1);
496        fold.apply(&event(
497            "turn/completed",
498            json!({"sessionId": "session-1", "turnId": "turn-1", "terminal": "completed"}),
499        ));
500        assert!(fold.pending_user_inputs().is_empty());
501        assert!(fold.settled_user_inputs().is_empty());
502    }
503
504    /// A re-opened fold keeps applying question
505    /// events only, so approvals stay stopped with items, turns and state: an
506    /// approval pending at the re-open neither updates nor resolves.
507    #[test]
508    fn a_reopened_fold_ignores_approval_events() {
509        let approval = |method: &str, id: &str| {
510            event(method, json!({"sessionId": "session-1", "approvalId": id}))
511        };
512        let mut fold = SessionFold::new("session-1");
513        assert_eq!(
514            fold.apply(&approval("approval/requested", "approval-held")),
515            FoldOutcome::Applied
516        );
517        fold.mark_reopened();
518        for method in [
519            "approval/requested",
520            "approval/updated",
521            "approval/resolved",
522        ] {
523            assert_eq!(
524                fold.apply(&approval(method, "approval-new")),
525                FoldOutcome::Ignored,
526                "{method} for a new approval"
527            );
528        }
529        assert_eq!(
530            fold.apply(&approval("approval/updated", "approval-held")),
531            FoldOutcome::Ignored
532        );
533        assert_eq!(
534            fold.apply(&approval("approval/resolved", "approval-held")),
535            FoldOutcome::Ignored
536        );
537        let pending = fold.pending_approvals();
538        assert_eq!(pending.len(), 1);
539        assert_eq!(pending[0].approval_id, "approval-held");
540        assert!(pending[0].latest_update.is_none());
541        assert!(fold.resolved_approvals().is_empty());
542    }
543}