Skip to main content

ag_ui/server/
state.rs

1//! Publishing shared state as snapshots or patches.
2//!
3//! The client keeps a copy of the agent's state. Sending the whole thing on
4//! every change is wasteful for a large document that gained one field, and
5//! sending a patch is wasteful for a small document that changed completely.
6//! [`StateManager`] keeps the last published snapshot and picks per publish:
7//!
8//! 1. the first publish is always a `STATE_SNAPSHOT` — the client's copy may
9//!    have drifted, and a patch against an unknown base is inapplicable;
10//! 2. afterwards it diffs against the last snapshot with [RFC 6902] and emits
11//!    `STATE_DELTA`;
12//! 3. unless the serialized patch is no smaller than the serialized snapshot,
13//!    in which case it snapshots instead.
14//!
15//! [RFC 6902]: https://datatracker.ietf.org/doc/html/rfc6902
16
17use crate::{Event, JsonPatch, PatchOperation};
18use serde_json::Value;
19
20use crate::server::agent::AgentState;
21use crate::server::emit::EventSink;
22use crate::server::error::Result;
23
24/// What a publish decided to send.
25#[derive(Clone, Debug, PartialEq)]
26pub enum StatePublish {
27    /// The whole state — the first publish, or a change too large to patch.
28    Snapshot(Value),
29    /// A patch against the previously published snapshot.
30    Delta(JsonPatch),
31    /// The state is byte-identical to the last publish; nothing to send.
32    Unchanged,
33}
34
35impl StatePublish {
36    /// The event to emit, or `None` for [`StatePublish::Unchanged`].
37    pub fn into_event(self) -> Option<Event> {
38        match self {
39            Self::Snapshot(value) => Some(Event::state_snapshot(value)),
40            Self::Delta(patch) => Some(Event::state_delta(patch)),
41            Self::Unchanged => None,
42        }
43    }
44}
45
46/// Tracks the last published state so changes can go out as patches.
47///
48/// ```
49/// # use ag_ui::PatchOperation;
50/// # use ag_ui::server::{StateManager, StatePublish};
51/// # use serde_json::json;
52/// let mut states = StateManager::new();
53/// let notes = "the document the user is editing, at some length";
54///
55/// // First publish: a snapshot, whatever the size.
56/// let first = states.publish(json!({"step": 1, "notes": notes}))?;
57/// assert!(matches!(first, StatePublish::Snapshot(_)));
58///
59/// // One field of a large document: a patch, because it is smaller.
60/// let second = states.publish(json!({"step": 2, "notes": notes}))?;
61/// assert_eq!(
62///     second,
63///     StatePublish::Delta(vec![PatchOperation::replace("/step", 2)])
64/// );
65///
66/// // A small document changing wholesale: back to a snapshot, because the
67/// // patch would be bigger than the state it describes.
68/// let mut small = StateManager::new();
69/// small.publish(json!({"a": 1}))?;
70/// assert_eq!(
71///     small.publish(json!({"b": 2}))?,
72///     StatePublish::Snapshot(json!({"b": 2}))
73/// );
74/// # Ok::<(), ag_ui::server::Error>(())
75/// ```
76#[derive(Clone, Debug, Default)]
77pub struct StateManager {
78    published: Option<Value>,
79}
80
81impl StateManager {
82    /// A manager that has published nothing yet.
83    pub fn new() -> Self {
84        Self::default()
85    }
86
87    /// The last published state, or `None` before the first publish.
88    pub fn published(&self) -> Option<&Value> {
89        self.published.as_ref()
90    }
91
92    /// Forgets the last publish, so the next one is a snapshot again.
93    ///
94    /// Call this after emitting a `STATE_SNAPSHOT` by hand, or after a
95    /// reconnect where the client's copy is no longer known.
96    pub fn reset(&mut self) {
97        self.published = None;
98    }
99
100    /// Decides how to publish `next` and records it as the new baseline.
101    ///
102    /// Returns [`StatePublish::Unchanged`] when nothing moved, so callers can
103    /// skip emitting entirely.
104    pub fn publish(&mut self, next: Value) -> Result<StatePublish> {
105        let decision = self.decide(&next)?;
106        if decision != StatePublish::Unchanged {
107            self.published = Some(next);
108        }
109        Ok(decision)
110    }
111
112    /// Previews a publish without advancing the baseline. The event sink uses
113    /// this so only events that survive transformers and enter its queue count
114    /// as published.
115    pub(crate) fn decide(&self, next: &Value) -> Result<StatePublish> {
116        let Some(previous) = self.published.as_ref() else {
117            return Ok(StatePublish::Snapshot(next.clone()));
118        };
119
120        if previous == next {
121            return Ok(StatePublish::Unchanged);
122        }
123
124        let patch = diff(previous, next)?;
125        // A no-op patch against a different value would not update a client.
126        if patch.is_empty() {
127            return Ok(StatePublish::Snapshot(next.clone()));
128        }
129
130        let patch_size = serde_json::to_vec(&patch)?.len();
131        let snapshot_size = serde_json::to_vec(&next)?.len();
132        if patch_size < snapshot_size {
133            Ok(StatePublish::Delta(patch))
134        } else {
135            Ok(StatePublish::Snapshot(next.clone()))
136        }
137    }
138
139    /// Computes the state a queued `STATE_DELTA` will produce. If no snapshot
140    /// has reached the queue yet, the client may have an input state we cannot
141    /// know here; a later automatic publish must use a snapshot.
142    pub(crate) fn after_delta(&self, operations: &[PatchOperation]) -> Result<Option<Value>> {
143        let Some(mut next) = self.published.clone() else {
144            return Ok(None);
145        };
146        let patch: json_patch::Patch = serde_json::from_value(serde_json::to_value(operations)?)?;
147        // A well-formed patch can fail against this particular state. The
148        // client reports that as a diagnostic and keeps its previous value.
149        // Forget the baseline here so the next automatic publish is a full
150        // snapshot; retaining an assumed value would corrupt later deltas.
151        if json_patch::patch(&mut next, &patch).is_err() {
152            return Ok(None);
153        }
154        Ok(Some(next))
155    }
156
157    pub(crate) fn set_published(&mut self, state: Option<Value>) {
158        self.published = state;
159    }
160}
161
162/// A run's typed state.
163///
164/// An open handle borrows it beside the event sink, allowing a tool call to
165/// mutate and publish the state without borrowing its context twice. The sink
166/// owns the publish history because it sees the events after transformation.
167#[derive(Debug)]
168pub(crate) struct RunState<S> {
169    value: S,
170}
171
172impl<S> RunState<S> {
173    /// Wraps a decoded state, with nothing published yet.
174    pub(crate) fn new(value: S) -> Self {
175        Self { value }
176    }
177
178    pub(crate) fn get(&self) -> &S {
179        &self.value
180    }
181
182    pub(crate) fn get_mut(&mut self) -> &mut S {
183        &mut self.value
184    }
185}
186
187impl<S: AgentState> RunState<S> {
188    /// Publishes whatever [`get_mut`](Self::get_mut) left behind.
189    pub(crate) fn publish(&mut self, sink: &mut EventSink) -> Result<()> {
190        let value = serde_json::to_value(&self.value)?;
191        self.publish_value(sink, value)
192    }
193
194    /// Replaces the value and publishes the change.
195    pub(crate) fn replace(&mut self, sink: &mut EventSink, value: &S) -> Result<()> {
196        let json = serde_json::to_value(value)?;
197        // Round-tripping keeps the typed view and the published snapshot in
198        // step without asking `S` to be `Clone`.
199        self.value = serde_json::from_value(json.clone())?;
200        self.publish_value(sink, json)
201    }
202
203    fn publish_value(&mut self, sink: &mut EventSink, value: Value) -> Result<()> {
204        sink.publish_state(value)
205    }
206}
207
208/// Computes an RFC 6902 patch and re-reads it as the protocol's own operation
209/// type.
210///
211/// `json-patch` has its own `PatchOperation` with `jsonptr` paths; the wire
212/// format is identical, so the round trip through `serde_json::Value` is the
213/// conversion.
214fn diff(previous: &Value, next: &Value) -> Result<JsonPatch> {
215    let patch = json_patch::diff(previous, next);
216    let operations: Vec<PatchOperation> = serde_json::from_value(serde_json::to_value(patch)?)?;
217    Ok(operations)
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use serde_json::json;
224
225    #[test]
226    fn first_publish_is_a_snapshot_even_when_tiny() {
227        let mut states = StateManager::new();
228        let published = states.publish(json!({"a": 1})).expect("publish failed");
229        assert_eq!(published, StatePublish::Snapshot(json!({"a": 1})));
230    }
231
232    #[test]
233    fn identical_state_publishes_nothing() {
234        let mut states = StateManager::new();
235        states.publish(json!({"a": 1})).expect("publish failed");
236        let second = states.publish(json!({"a": 1})).expect("publish failed");
237        assert_eq!(second, StatePublish::Unchanged);
238    }
239
240    #[test]
241    fn small_change_to_large_state_is_a_delta() {
242        let mut states = StateManager::new();
243        let big = json!({"notes": ["a".repeat(200)], "step": 1});
244        states.publish(big).expect("publish failed");
245        let published = states
246            .publish(json!({"notes": ["a".repeat(200)], "step": 2}))
247            .expect("publish failed");
248        assert_eq!(
249            published,
250            StatePublish::Delta(vec![PatchOperation::replace("/step", 2)])
251        );
252    }
253
254    #[test]
255    fn wholesale_change_falls_back_to_a_snapshot() {
256        let mut states = StateManager::new();
257        states.publish(json!({"a": 1})).expect("publish failed");
258        let next = json!({"b": 2});
259        let published = states.publish(next.clone()).expect("publish failed");
260        assert_eq!(published, StatePublish::Snapshot(next));
261    }
262
263    #[test]
264    fn reset_forces_the_next_publish_to_snapshot() {
265        let mut states = StateManager::new();
266        states
267            .publish(json!({"notes": ["a".repeat(200)], "step": 1}))
268            .expect("publish failed");
269        states.reset();
270        let next = json!({"notes": ["a".repeat(200)], "step": 2});
271        let published = states.publish(next.clone()).expect("publish failed");
272        assert_eq!(published, StatePublish::Snapshot(next));
273    }
274}