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