Skip to main content

vtcode_desktop_protocol/
live_events.rs

1//! Coalescing live-event channel from the service to desktop clients.
2use std::collections::VecDeque;
3
4use vtcode_exec_events::VersionedThreadEvent;
5
6/// Create the bounded live event channel that streams runtime events from the
7/// agent runloop to the desktop service pump.
8///
9/// Unlike a plain bounded channel, a full queue never fails the producer:
10/// `item.updated` snapshots replace the pending snapshot for the same item,
11/// consecutive `plan.delta` events for one item merge into one entry, and
12/// consecutive tool-output deltas for one item concatenate into one entry, so
13/// a slow consumer degrades the stream instead of failing a healthy turn.
14/// Ordered events are only dropped when the queue holds no coalescable entry,
15/// and every such drop is counted for consumer-side degradation reporting.
16pub fn live_event_channel(capacity: usize) -> (LiveEventSender, LiveEventReceiver) {
17    assert!(capacity > 0, "live event capacity must be positive");
18    let inner = std::sync::Arc::new(LiveEventQueueInner {
19        capacity,
20        queue: std::sync::Mutex::new(VecDeque::new()),
21        senders: std::sync::atomic::AtomicUsize::new(1),
22        receiver_alive: std::sync::atomic::AtomicBool::new(true),
23        dropped_ordered: std::sync::atomic::AtomicU64::new(0),
24        dropped_stale: std::sync::atomic::AtomicU64::new(0),
25        notify: tokio::sync::Notify::new(),
26    });
27    (LiveEventSender { inner: inner.clone() }, LiveEventReceiver { inner })
28}
29
30/// How a streaming event combines with the pending entry for the same key.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32enum CoalesceOp {
33    /// The new event is a full snapshot that supersedes the pending one.
34    Replace,
35    /// The new event carries incremental text appended to the pending one.
36    Merge,
37    /// The new event carries an output chunk appended to the pending one.
38    MergeOutput,
39}
40
41/// One queue entry: a coalescable streaming event keyed by item, or an
42/// ordered event that must keep its relative position.
43struct LiveEventSlot {
44    key: Option<String>,
45    op: CoalesceOp,
46    event: VersionedThreadEvent,
47}
48
49struct LiveEventQueueInner {
50    capacity: usize,
51    queue: std::sync::Mutex<VecDeque<LiveEventSlot>>,
52    senders: std::sync::atomic::AtomicUsize,
53    receiver_alive: std::sync::atomic::AtomicBool,
54    dropped_ordered: std::sync::atomic::AtomicU64,
55    dropped_stale: std::sync::atomic::AtomicU64,
56    notify: tokio::sync::Notify,
57}
58
59impl LiveEventQueueInner {
60    fn classify(event: &VersionedThreadEvent) -> Option<(String, CoalesceOp)> {
61        match event.event() {
62            vtcode_exec_events::ThreadEvent::ItemUpdated(update) => {
63                let op = match &update.item.details {
64                    vtcode_exec_events::ThreadItemDetails::ToolOutput(output) if output.is_delta == Some(true) => {
65                        CoalesceOp::MergeOutput
66                    }
67                    _ => CoalesceOp::Replace,
68                };
69                Some((update.item.id.clone(), op))
70            }
71            vtcode_exec_events::ThreadEvent::PlanDelta(delta) => Some((delta.item_id.clone(), CoalesceOp::Merge)),
72            _ => None,
73        }
74    }
75
76    /// Append an event, coalescing streaming updates and keeping the queue
77    /// bounded. Returns `Err(())` only when the consumer half was dropped.
78    fn publish(&self, event: VersionedThreadEvent) -> Result<(), ()> {
79        if !self.receiver_alive.load(std::sync::atomic::Ordering::Acquire) {
80            return Err(());
81        }
82        let mut queue = self.queue.lock().map_err(|_poisoned| ())?;
83        let classified = Self::classify(&event);
84        let slot_key = classified.as_ref().map(|(key, _)| key.clone());
85        let slot_op = classified.as_ref().map_or(CoalesceOp::Replace, |(_, op)| *op);
86        if let Some((key, op)) = classified {
87            // One slot per item, regardless of coalesce op. A delta and the
88            // terminal snapshot for the same long-running command must share
89            // a slot: with separate slots, saturation could evict the slot
90            // holding the accumulated output and the command's inline preview
91            // vanished until it settled.
92            let pending_slot = queue
93                .iter()
94                .position(|slot| slot.key.as_deref() == Some(key.as_str()))
95                .and_then(|index| queue.remove(index).map(|removed| (index, removed)));
96            if let Some((_index, pending)) = pending_slot {
97                let (merged, merged_op) = match (pending.op, op) {
98                    // A full snapshot supersedes the pending delta; once a
99                    // snapshot is queued a later delta is already included.
100                    (_, CoalesceOp::Replace) => (event, CoalesceOp::Replace),
101                    (CoalesceOp::Replace, _) => (pending.event, CoalesceOp::Replace),
102                    (_, CoalesceOp::Merge) => (Self::merge_plan_deltas(pending.event, event), pending.op),
103                    (_, CoalesceOp::MergeOutput) => (Self::merge_tool_output_deltas(pending.event, event), pending.op),
104                };
105                // Move an actively streaming item to the back so front_eviction
106                // prefers quiet items; its accumulated text survives bursts.
107                queue.push_back(LiveEventSlot { key: Some(key), op: merged_op, event: merged });
108                drop(queue);
109                self.notify.notify_waiters();
110                return Ok(());
111            }
112        }
113        if queue.len() >= self.capacity {
114            // Prefer displacing a stale streaming entry over dropping an
115            // ordered event. Active streams are at the back (see above), so a
116            // quiet item is the victim rather than a running command's tail.
117            let victim = queue.iter().position(|slot| slot.key.is_some());
118            match victim {
119                Some(index) => {
120                    drop(queue.remove(index));
121                    let _ = self.dropped_stale.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
122                }
123                None => {
124                    drop(queue.pop_front());
125                    let _ = self.dropped_ordered.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
126                }
127            }
128        }
129        queue.push_back(LiveEventSlot { key: slot_key, op: slot_op, event });
130        drop(queue);
131        self.notify.notify_waiters();
132        Ok(())
133    }
134
135    /// Concatenate two tool-output deltas for the same item, keeping the
136    /// newest metadata and the freshest non-empty optional fields.
137    fn merge_tool_output_deltas(pending: VersionedThreadEvent, next: VersionedThreadEvent) -> VersionedThreadEvent {
138        let (pending, next) = (pending.into_event(), next.into_event());
139        match (pending, next) {
140            (
141                vtcode_exec_events::ThreadEvent::ItemUpdated(older),
142                vtcode_exec_events::ThreadEvent::ItemUpdated(newer),
143            ) => {
144                let (
145                    vtcode_exec_events::ThreadItemDetails::ToolOutput(older_output),
146                    vtcode_exec_events::ThreadItemDetails::ToolOutput(newer_output),
147                ) = (&older.item.details, &newer.item.details)
148                else {
149                    return VersionedThreadEvent::new(vtcode_exec_events::ThreadEvent::ItemUpdated(newer));
150                };
151                let mut merged = newer.clone();
152                let mut output = older_output.output.clone();
153                output.push_str(&newer_output.output);
154                merged.item.details =
155                    vtcode_exec_events::ThreadItemDetails::ToolOutput(Box::new(vtcode_exec_events::ToolOutputItem {
156                        call_id: newer_output.call_id.clone(),
157                        tool_call_id: newer_output.tool_call_id.clone().or_else(|| older_output.tool_call_id.clone()),
158                        spool_path: newer_output.spool_path.clone().or_else(|| older_output.spool_path.clone()),
159                        output,
160                        is_delta: Some(true),
161                        exit_code: newer_output.exit_code.or(older_output.exit_code),
162                        status: newer_output.status.clone(),
163                        app_previews: if newer_output.app_previews.is_empty() {
164                            older_output.app_previews.clone()
165                        } else {
166                            newer_output.app_previews.clone()
167                        },
168                    }));
169                VersionedThreadEvent::new(vtcode_exec_events::ThreadEvent::ItemUpdated(merged))
170            }
171            (_, fallback) => VersionedThreadEvent::new(fallback),
172        }
173    }
174
175    /// Concatenate two `plan.delta` events for the same item, keeping the
176    /// newest metadata and the freshest non-empty recovery snapshot.
177    fn merge_plan_deltas(pending: VersionedThreadEvent, next: VersionedThreadEvent) -> VersionedThreadEvent {
178        let (pending, next) = (pending.into_event(), next.into_event());
179        match (pending, next) {
180            (vtcode_exec_events::ThreadEvent::PlanDelta(older), vtcode_exec_events::ThreadEvent::PlanDelta(newer)) => {
181                let mut merged = newer.clone();
182                let mut text = older.delta;
183                text.push_str(&newer.delta);
184                merged.delta = text;
185                if merged.recovery.is_none() {
186                    merged.recovery = older.recovery;
187                }
188                VersionedThreadEvent::new(vtcode_exec_events::ThreadEvent::PlanDelta(merged))
189            }
190            (_, fallback) => VersionedThreadEvent::new(fallback),
191        }
192    }
193}
194
195/// Producer half of the live event channel.
196pub struct LiveEventSender {
197    inner: std::sync::Arc<LiveEventQueueInner>,
198}
199
200impl Clone for LiveEventSender {
201    fn clone(&self) -> Self {
202        let _ = self.inner.senders.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
203        Self { inner: std::sync::Arc::clone(&self.inner) }
204    }
205}
206
207impl LiveEventSender {
208    /// Publish one event. Coalesces streaming updates when the queue is
209    /// saturated; fails only when the consumer half is gone.
210    pub fn publish(&self, event: VersionedThreadEvent) -> Result<(), LiveEventSendError> {
211        self.inner.publish(event).map_err(|()| LiveEventSendError(()))
212    }
213}
214
215impl Drop for LiveEventSender {
216    fn drop(&mut self) {
217        let _ = self.inner.senders.fetch_sub(1, std::sync::atomic::Ordering::Release);
218        self.inner.notify.notify_waiters();
219    }
220}
221
222/// Consumer half of the live event channel.
223pub struct LiveEventReceiver {
224    inner: std::sync::Arc<LiveEventQueueInner>,
225}
226
227impl LiveEventReceiver {
228    /// Receive the next event, waiting while the queue is empty.
229    ///
230    /// Returns `None` once every sender was dropped and the queue drained.
231    pub async fn recv(&self) -> Option<VersionedThreadEvent> {
232        loop {
233            {
234                let mut queue = self.inner.queue.lock().ok()?;
235                if let Some(slot) = queue.pop_front() {
236                    return Some(slot.event);
237                }
238                if self.inner.senders.load(std::sync::atomic::Ordering::Acquire) == 0 {
239                    return None;
240                }
241            }
242            let notified = self.inner.notify.notified();
243            {
244                let queue = self.inner.queue.lock().ok()?;
245                if !queue.is_empty() {
246                    continue;
247                }
248                if self.inner.senders.load(std::sync::atomic::Ordering::Acquire) == 0 {
249                    return None;
250                }
251            }
252            notified.await;
253        }
254    }
255
256    /// Take and reset the count of ordered events dropped under saturation.
257    pub fn take_dropped_ordered(&self) -> u64 {
258        self.inner.dropped_ordered.swap(0, std::sync::atomic::Ordering::Relaxed)
259    }
260
261    /// Take and reset the count of superseded streaming snapshots displaced
262    /// under saturation. These are best-effort previews, not stream gaps.
263    pub fn take_dropped_stale(&self) -> u64 {
264        self.inner.dropped_stale.swap(0, std::sync::atomic::Ordering::Relaxed)
265    }
266}
267
268impl Drop for LiveEventReceiver {
269    fn drop(&mut self) {
270        self.inner.receiver_alive.store(false, std::sync::atomic::Ordering::Release);
271        self.inner.notify.notify_waiters();
272    }
273}
274
275/// The consumer half of the live event channel is gone.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub struct LiveEventSendError(());
278
279impl std::fmt::Display for LiveEventSendError {
280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281        f.write_str("live event consumer disconnected")
282    }
283}
284
285impl std::error::Error for LiveEventSendError {}