//! Applies event batches and refreshes reads invalidated by events or reconnection. use std::sync::atomic::Ordering; use futures_util::StreamExt; use futures_util::stream::BoxStream; use opencode_api::client::Client; use opencode_api::events::{self, Activity, Connection, Source, Status}; use opencode_api::generated::*; use opencode_api::transport::BoxFuture; use tokio::sync::{mpsc, watch}; use tokio::task::JoinHandle; use crate::changes::Touched; use crate::location::{Catalog, Location}; use crate::sessions::Outcome; use crate::state::{Data, Error, SessionStatus, State}; /// A read an event leaves for after the store lock is released. #[derive(Debug, Clone)] pub(crate) enum Follow { /// Session info (already invalidated). Session(SessionID), /// The newest message page (already invalidated). Messages(SessionID), /// One projected message. Message(SessionID, SessionMessageID), /// A live title to apply after the session reads. Renamed(SessionID, String), /// The `session.active` snapshot of connection `token`. Active(u64), /// The default location's info, its VCS, and the projects, after `server.connected`. Rehydrate, /// Catalogs of a location, read together (already invalidated). Catalogs(Vec, Location), /// A catalog read once a burst of events that ask for it goes quiet (already invalidated). Settle(Catalog, Location), /// The web search providers of a location. Websearch(Location), /// The running jobs of a synced tree (already invalidated). Jobs(SessionID), } impl Data { /// Applies one batch of events under one flush. pub fn apply(&self, events: &[V2Event]) { let (follows, kept) = { let mut state = self.lock(); state.batch += 1; let follows: Vec = events.iter().flat_map(|event| state.apply_event(event)).collect(); state.batch -= 1; // The batch's deltas, the hot path, are kept only while someone takes them, and all before the revision // that has them, so a sync it wakes takes them all. let kept = self.keep_deltas(events.iter().filter(|event| is_delta(event))); self.flush(&mut state); (follows, kept) }; for follow in follows { self.follow(follow); } // Each other event of a type someone listens to: of its kind, and of its name for a named kind. for event in events.iter().filter(|event| !is_delta(event)) { let kind = event.kind(); if self.inner.listened[kind as usize].load(std::sync::atomic::Ordering::SeqCst) > 0 && (!kind.named() || opencode_util::lock(&self.inner.named).contains_key(event.tag())) { // No receiver is not an error: views subscribe when they need to. let _ = self.inner.signals.send(std::sync::Arc::new(event.clone())); } } // A delta of a session whose messages are not loaded changes nothing, and is kept all the same. if kept { self.wake_deltas(); } } /// Every read goes through `refresh`, which checks the connection before building it. A /// settle timer checks when it fires. fn follow(&self, follow: Follow) { match follow { Follow::Session(id) => self.refresh(move |data| data.session_sync(&id, false)), Follow::Messages(id) => self.refresh(move |data| data.message_sync(&id)), Follow::Message(session, message) => self.fetch_message(session, message), Follow::Renamed(session, title) => self.renamed(session, title), Follow::Active(token) => self.rehydrate(token), Follow::Rehydrate => { self.rehydrate_location(); let default = self.read(|state| state.default_location().clone()); self.refresh_catalogs(vec![Catalog::Vcs], default); self.refresh(|data| data.project_sync()); } Follow::Catalogs(catalogs, location) => self.refresh_catalogs(catalogs, location), Follow::Settle(catalog, location) => self.settle(catalog, location), Follow::Websearch(location) => self.refresh(move |data| data.websearch_refresh(Some(&location))), Follow::Jobs(root) => self.refresh(move |data| data.job_sync(&root)), } } /// Reconciles session status with `session.active`. Status events received during the read /// supersede the snapshot; a snapshot of an older connection is ignored. fn rehydrate(&self, token: u64) { self.refresh(move |data| async move { let result = data.client().session_active().await; let active = match result { Ok(active) => active, Err(error) => { data.write(|state| { if state.active_updates.as_ref().is_some_and(|(current, _)| *current == token) { state.active_updates = None; } }); return Err(Error::new(error)); } }; let unknown = data.write(|state| { let Some((current, updates)) = state.active_updates.take() else { return Vec::new() }; if current != token { state.active_updates = Some((current, updates)); return Vec::new(); } let mut snapshot: std::collections::HashMap = active.into_keys().map(|id| (SessionID(id), SessionStatus::Running)).collect(); for (id, status) in updates { match status { Some(status) => snapshot.insert(id, status), None => snapshot.remove(&id), }; } for (key, session) in state.sessions.entries_mut() { let status = snapshot.remove(&session.id); if session.status != status { session.status = status; state.log.touch(session, key, Touched::STATUS); } } // What is left names sessions the store holds nothing of. for (id, status) in snapshot { let key = state.sessions.entry(&id); state.sessions[key].status = Some(status); state.touch_key(key, Touched::STATUS); } // Sessions created before this connection never delivered `session.created`; // without their info a running child never joins its root's family. state .sessions .iter() .filter(|session| session.status == Some(SessionStatus::Running) && session.info.is_none()) .map(|session| session.id.clone()) .collect() }); for id in unknown { data.refresh(move |data| data.session_sync(&id, false)); } Ok(()) }); } /// Marks the connection up or down. Going down invalidates every cached read; the UI decides /// what to read again. pub fn set_online(&self, online: bool) { let was = self.inner.online.swap(online, Ordering::SeqCst); if was && !online { self.write(State::invalidate_all); } } } impl State { /// One `handleEvent` arm; returns the reads it leaves for after the lock. pub(crate) fn apply_event(&mut self, event: &V2Event) -> Vec { self.event_seq = event.durable_seq(); self.record_edit(event); match event { V2Event::ServerConnected(_) => { // Every connection after the first is a reconnect, also one the status watch // coalesced (`resync`, a queue-full drop): what the old stream left cached is // stale, and every view must look again. if self.connected { self.invalidate_all(); } else { // The first stream opens after the route reads, and the server does not replay what it sent // before the subscription: a catalog read in that window can have missed the update that // followed it, and a model list is empty until its providers settle. Only the catalogs are // invalidated, since nothing else can be stale without a disconnect; the views look again. self.invalidate_catalogs(); } self.log.everything(); self.connected = true; let token = self.token(); self.active_updates = Some((token, Default::default())); let jobs = self.job_roots().into_iter().map(Follow::Jobs); return [Follow::Active(token), Follow::Rehydrate].into_iter().chain(jobs).collect(); } V2Event::SessionCreated(event) => return self.on_session_created(&event.data), V2Event::SessionDeleted(event) => self.mark_deleted(&event.data.session_id), V2Event::SessionUsageUpdated(event) => self.on_usage_updated(&event.data), V2Event::SessionAgentSelected(event) => self.on_agent_selected(event), V2Event::SessionModelSelected(event) => return self.on_model_selected(event), V2Event::SessionRenamed(event) => { return vec![Follow::Renamed(event.data.session_id.clone(), event.data.title.clone())]; } V2Event::SessionPermissions(event) => self.on_permissions(&event.data), V2Event::SessionMetadataUpdated(event) => self.on_metadata(&event.data), V2Event::SessionArchived(event) => self.on_archived(&event.data.session_id, Some(event.created)), V2Event::SessionUnarchived(event) => self.on_archived(&event.data.session_id, None), V2Event::SessionMoved(event) => self.on_moved(event), V2Event::SessionInboxDelivered(event) => return self.on_inbox_delivered(event), V2Event::SessionInboxDeliveryChanged(event) => self.on_inbox_delivery_changed(&event.data), V2Event::SessionInboxCancelled(event) => self.on_inbox_cancelled(&event.data), V2Event::SessionInboxEnqueued(event) => self.on_inbox_enqueued(event), V2Event::SessionInstructionsUpdated(event) => { // The initial baseline and empty deltas carry no text and project no message. if let Some(text) = &event.data.text { let keys: Vec<&str> = event.data.delta.keys().map(String::as_str).collect(); let row = SessionMessageSystem { id: crate::messages::from_event(&event.id), r#type: tag::System, text: text.clone(), description: Some(format!("Instructions updated: {}", keys.join(", "))), metadata: event.metadata.clone(), time: SessionInboxUserTime { created: event.created }, }; self.insert_message(&event.data.session_id, SessionMessageInfo::System(row)); } } V2Event::SessionSynthetic(event) => { let row = SessionMessageSynthetic { id: crate::messages::from_event(&event.id), r#type: tag::Synthetic, text: event.data.text.clone(), description: event.data.description.clone(), metadata: event.data.metadata.clone(), time: SessionInboxUserTime { created: event.created }, }; self.insert_message(&event.data.session_id, SessionMessageInfo::Synthetic(row)); } V2Event::SessionShellStarted(event) => self.on_shell_started(event), V2Event::SessionShellEnded(event) => self.on_shell_ended(event), V2Event::SessionStepStarted(event) => self.on_step_started(event), V2Event::SessionStepFirstToken(event) => self.on_step_first_token(event), V2Event::SessionStepStreamed(event) => self.on_step_streamed(event), V2Event::SessionStepEnded(event) => self.on_step_ended(event), V2Event::SessionStepFailed(event) => { self.on_step_failed(event); // A budget refusal means the cached usage limits are out of date, which is what // the refusal sends people to. let budget = matches!(event.data.error.r#type.as_str(), "provider.budget-limit" | "provider.model-budget-limit"); if let Some(location) = event.location.as_ref().filter(|_| budget) { return self.refresh_catalog(Catalog::UsageLimits, &Location::from(location)); } } V2Event::SessionTextStarted(event) => { self.on_text_started(&event.data.session_id, &event.data.assistant_message_id, event.data.ordinal) } V2Event::SessionTextDelta(event) => self.on_text_delta(&event.data), V2Event::SessionTextEnded(event) => self.on_text_ended(&event.data), V2Event::SessionToolInputStarted(event) => self.on_tool_input_started(event), V2Event::SessionToolInputDelta(event) => self.on_tool_input_delta(&event.data), V2Event::SessionToolInputEnded(event) => self.on_tool_input_ended(&event.data), V2Event::SessionToolCalled(event) => self.on_tool_called(event), V2Event::SessionToolProgress(event) => self.on_tool_progress(&event.data), V2Event::SessionToolSuccess(event) => self.on_tool_success(event), V2Event::SessionToolFailed(event) => self.on_tool_failed(event), V2Event::SessionReasoningStarted(event) => self.on_reasoning_started(event), V2Event::SessionReasoningDelta(event) => self.on_reasoning_delta(&event.data), V2Event::SessionReasoningEnded(event) => self.on_reasoning_ended(event), V2Event::SessionRetryScheduled(event) => self.on_retry_scheduled(&event.data), V2Event::SessionExecutionStarted(event) => { return self.on_execution_started(&event.data.session_id); } V2Event::SessionCompactionStarted(event) => self.on_compaction_started(event), V2Event::SessionExecutionSucceeded(event) => { return self.on_execution_ended( &event.id, event.created, &event.data.session_id, Outcome::Succeeded, None, false, ); } V2Event::SessionExecutionFailed(event) => { return self.on_execution_ended( &event.id, event.created, &event.data.session_id, Outcome::Failed, Some(&event.data.error), false, ); } V2Event::SessionExecutionInterrupted(event) => { return self.on_execution_ended( &event.id, event.created, &event.data.session_id, Outcome::Interrupted, None, event.data.reason == SessionExecutionInterruptedDataReason::Shutdown, ); } V2Event::SessionViewed(event) => return self.on_viewed(&event.data.session_id), V2Event::SessionRevertStaged(event) => self.on_revert_staged(&event.data), V2Event::SessionRevertCleared(event) => self.on_revert_cleared(&event.data.session_id), V2Event::SessionRevertCommitted(event) => self.on_revert_committed(&event.data), V2Event::SessionCompactionDelta(event) => self.on_compaction_delta(&event.data), V2Event::SessionCompactionEnded(event) => self.on_compaction_ended(event), V2Event::SessionCompactionFailed(event) => self.on_compaction_failed_inbox(event), V2Event::PermissionAsked(event) => self.on_permission_asked(&event.data), V2Event::PermissionReplied(event) => self.remove_permission(&event.data.session_id, &event.data.request_id), V2Event::ProjectUpdated(event) => self.on_project_updated(&event.data), V2Event::WorktreeResolved(event) => return self.on_worktree_resolved(&event.data), V2Event::FormReplied(event) => { let location = event.location.as_ref().map(Location::from); self.remove_form(&event.data.session_id, &event.data.id, location.as_ref()); } V2Event::FormCancelled(event) => { let location = event.location.as_ref().map(Location::from); self.remove_form(&event.data.session_id, &event.data.id, location.as_ref()); } V2Event::ExperimentalJobUpdated(event) => self.on_job_updated(&event.data.info), _ => return self.on_catalog_event(event), } Vec::new() } } /// Drives the store from a connection: applies its batches and tracks whether it is connected. /// Returns when the batch receiver closes. pub async fn run(data: Data, mut state: watch::Receiver, mut batches: mpsc::Receiver>) { let mut watching = true; loop { tokio::select! { biased; changed = state.changed(), if watching => { if changed.is_err() { watching = false; continue; } let online = state.borrow_and_update().status == Status::Connected; // Apply the final queued batch while still online so disconnect invalidation covers it. if !online { while let Ok(batch) = batches.try_recv() { data.apply(&batch); } } data.set_online(online); } batch = batches.recv() => { let Some(batch) = batch else { return }; data.set_online(state.borrow().status == Status::Connected); data.apply(&batch); } } } } fn is_delta(event: &V2Event) -> bool { matches!( event, V2Event::SessionTextDelta(_) | V2Event::SessionReasoningDelta(_) | V2Event::SessionToolInputDelta(_) | V2Event::SessionCompactionDelta(_) ) } pub struct Events { pub client: Client, } impl Source for Events { /// The error as TS's connection records it: a declared error's message, else the client error's text. type Error = String; fn open(&mut self, activity: Activity) -> BoxStream<'static, Result> { let client = self.client.clone(); futures_util::stream::once(async move { client .event_subscribe(&EventSubscribeInput::default()) .await .map(|response| response.events(move || activity()).boxed()) }) .flat_map(|opened| match opened { Ok(stream) => stream, Err(error) => futures_util::stream::once(async move { Err(error) }).boxed(), }) .map(|item| item.map_err(|error| error.error_message())) .boxed() } fn reconnect(&mut self) -> BoxFuture<'_, bool> { self.client.transport().reconnect() } } /// Connects the store to its client's event stream on the store's runtime, so the UI thread can /// call it without a runtime context. Drop the connection to stop. pub fn connect(data: &Data, options: events::Options) -> (Connection, JoinHandle<()>) { let _runtime = data.runtime().enter(); data.set_online(false); let (connection, batches) = events::connect(Events { client: data.client().clone() }, options); let task = data.runtime().spawn(run(data.clone(), connection.watch(), batches)); (connection, task) }