refactor(cli-rs): begin and complete store requests over plain data (#65607)

This commit is contained in:
Simon Klee 2026-11-22 20:15:59 +01:00 • committed by GitHub
parent 9aaa33013b
commit 44ef8cec2f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 2893 additions and 2254 deletions

View file

@ -6,12 +6,13 @@ use std::ops::BitOr;
use opencode_api::generated::{AgentID, ModelRef, SessionID};
use crate::driver::Data;
use crate::forms::GLOBAL;
use crate::location::Location;
use crate::messages::MessageKey;
use crate::reads::LocationKey;
use crate::sessions::{Session, SessionKey};
use crate::state::{Data, State};
use crate::state::State;
/// A session's agent and model.
pub type Selected = (Option<AgentID>, Option<ModelRef>);
@ -309,7 +310,11 @@ impl State {
}
/// Records message `message` of `session` as changed in place.
pub(crate) fn message_changed(&mut self, session: &SessionID, message: &(impl AsRef<str> + ?Sized)) {
pub(crate) fn message_changed(
&mut self,
session: &(impl AsRef<str> + ?Sized),
message: &(impl AsRef<str> + ?Sized),
) {
let Some(key) = self.sessions.key(session) else { return };
let transcript = self.sessions[key].transcript.as_ref();
if let Some(message) = transcript.and_then(|transcript| transcript.key(message.as_ref())) {
@ -362,12 +367,3 @@ impl State {
}
}
}
impl Data {
/// Hands what changed since the last take to the one consumer, in `into`, and returns the revision of the last
/// flush. `into`'s earlier changes go: the consumer is done with them. The records the changes name stay marked
/// until the take, so the sweep before it frees none the consumer reads.
pub fn take_changes(&self, into: &mut Dirty) -> u64 {
self.lock().take(into)
}
}

View file

@ -11,55 +11,30 @@ 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<Catalog>, 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),
}
use crate::core::Delta;
use crate::driver::Data;
use crate::state::State;
impl Data {
/// Applies one batch of events under one flush.
pub fn apply(&self, events: &[V2Event]) {
let (follows, kept) = {
let mut effects = Vec::new();
let kept = {
let mut state = self.lock();
state.batch += 1;
let follows: Vec<Follow> = events.iter().flat_map(|event| state.apply_event(event)).collect();
for event in events {
state.apply(event, &mut effects);
}
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)));
let kept = self.keep_deltas(events.iter().filter(|event| Delta::of(event).is_some()));
self.flush(&mut state);
(follows, kept)
kept
};
for follow in follows {
self.follow(follow);
}
self.run(effects);
// 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)) {
for event in events.iter().filter(|event| Delta::of(event).is_none()) {
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()))
@ -74,87 +49,6 @@ impl Data {
}
}
/// 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<SessionID, SessionStatus> =
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) {
@ -165,167 +59,6 @@ impl Data {
}
}
impl State {
/// One `handleEvent` arm; returns the reads it leaves for after the lock.
pub(crate) fn apply_event(&mut self, event: &V2Event) -> Vec<Follow> {
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<events::State>, mut batches: mpsc::Receiver<Vec<V2Event>>) {
@ -356,16 +89,6 @@ pub async fn run(data: Data, mut state: watch::Receiver<events::State>, mut batc
}
}
fn is_delta(event: &V2Event) -> bool {
matches!(
event,
V2Event::SessionTextDelta(_)
| V2Event::SessionReasoningDelta(_)
| V2Event::SessionToolInputDelta(_)
| V2Event::SessionCompactionDelta(_)
)
}
pub struct Events {
pub client: Client,
}

View file

@ -0,0 +1,522 @@
//! The store's two entry points over plain data: [`State::apply`] takes an event and [`State::complete`] the answer to
//! a request; both say what to read next as [`Effect`]s. A request begins under the store's owner, where a
//! `State::begin_*` registers what may overtake it and returns what to fetch; whoever runs the store fetches it and
//! hands the answer back as a [`Completion`]. Nothing here waits, locks or fetches.
use opencode_api::generated::*;
use crate::forms::{Form, FormRead};
use crate::location::{Catalog, Loaded, Location};
use crate::messages::Page;
use crate::reads::ReadKey;
use crate::sessions::{Outcome, SessionKey};
use crate::state::{Error, State};
/// A keyed load in flight: the read, and the token of its load.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Ticket {
pub(crate) key: ReadKey,
pub(crate) token: u64,
}
/// The answer to a request, or to a mutation the driver ran. A keyed read's request comes back with its answer: its
/// `read` is the token of the overtake log or overlay that collected what overtook it, and its `started` the deletion
/// epoch it began at.
pub(crate) enum Completion {
/// A failure of the session's own read (`evicts`), not its children's, may find it missing.
Session(Info, Result<(SessionInfo, Vec<SessionInfo>), Error>, bool),
/// This client's creation of session `id`, which admitted it when `fresh`.
Created {
id: SessionID,
token: u64,
fresh: bool,
result: Result<SessionInfo, Error>,
},
/// A live title, once the session's reads that could overwrite it settled.
Renamed {
session: SessionID,
title: String,
},
/// The `session.active` snapshot of connection `token`.
Active(u64, Result<SessionActiveOutput, Error>),
/// A follow-up read found the session missing.
Missing(SessionID),
Messages(Head, Result<SessionMessagesResponse, Error>),
Message {
session: SessionID,
incarnation: u64,
result: Result<SessionMessageInfo, Error>,
},
Restored {
session: SessionID,
message: SessionMessageID,
result: Result<SessionMessageInfo, Error>,
},
/// Older messages, oldest last, read from `page`, and the cursor after them.
Older {
session: SessionID,
page: Page,
fetched: Vec<SessionMessageInfo>,
next: Option<String>,
},
/// The older-page load `token` ended.
OlderEnded {
session: SessionID,
token: u64,
},
Pending(List, Result<Vec<SessionInboxInfo>, Error>),
/// The prompt admission `token`, which rendered the row `id` when `fresh`.
Prompted {
session: SessionID,
token: u64,
id: SessionMessageID,
fresh: bool,
failed: bool,
},
/// The compaction admission `token`, which proposed `proposed`.
Compacted {
session: SessionID,
token: u64,
proposed: SessionMessageID,
result: Result<SessionInboxCompaction, Error>,
},
Permissions(List, Result<Vec<PermissionRequest>, Error>),
/// A permission request this client replied to, or found settled.
PermissionReplied {
session: SessionID,
request: PermissionID,
},
/// Forms, and for global ones the location the server read them at.
Forms(Forms, Result<(Vec<Form>, Option<Location>), Error>),
/// A form this client answered or cancelled, or found settled.
FormReplied {
owner: String,
id: FormID,
location: Option<Location>,
},
Jobs(Jobs, Result<Vec<JobInfo>, Error>),
/// A catalog, and the location the server answered with.
Catalog(CatalogRead, Result<(Location, Loaded), Error>),
Shells(Shells, Result<ShellListOutput, Error>),
Location(LocationRead, Result<LocationPublicInfo, Error>),
Websearch(Result<WebsearchProvidersOutput, Error>),
/// The trailing refetch `token` of `catalog` at `location` fired.
Settled {
key: ReadKey,
token: u64,
catalog: Catalog,
location: Location,
},
Projects(Projects, Result<Vec<Project>, Error>),
}
// The requests: what a `State::begin_*` says to fetch, with what its completion needs back. Each is its own type, so
// the task that fetches one holds only that request's I/O.
/// A read of a session's info, and of every direct child for `children`.
pub(crate) struct Info {
pub(crate) ticket: Ticket,
pub(crate) id: SessionID,
pub(crate) children: bool,
pub(crate) started: u64,
}
/// A read of the newest transcript page, in the transcript window `incarnation`.
pub(crate) struct Head {
pub(crate) ticket: Ticket,
pub(crate) session: SessionID,
pub(crate) read: u64,
pub(crate) incarnation: u64,
}
/// A read of a list of a session that events change while it is read.
pub(crate) struct List {
pub(crate) ticket: Ticket,
pub(crate) session: SessionID,
pub(crate) read: u64,
pub(crate) started: u64,
}
/// A read of the forms of a session, or the global forms of a location.
pub(crate) struct Forms {
pub(crate) ticket: Ticket,
pub(crate) form: FormRead,
pub(crate) read: u64,
pub(crate) started: u64,
}
/// A read of the running jobs of the tree under `root`.
pub(crate) struct Jobs {
pub(crate) ticket: Ticket,
pub(crate) root: SessionID,
pub(crate) read: u64,
}
pub(crate) struct CatalogRead {
pub(crate) ticket: Ticket,
pub(crate) catalog: Catalog,
pub(crate) location: Location,
}
/// A read of the running shells of a location.
pub(crate) struct Shells {
pub(crate) ticket: Ticket,
pub(crate) location: Location,
pub(crate) read: u64,
}
/// A read of location info, keyed or not; one of the default location `adopt`s the server's directory.
pub(crate) struct LocationRead {
pub(crate) ticket: Option<Ticket>,
pub(crate) location: Location,
pub(crate) adopt: bool,
}
pub(crate) struct Projects {
pub(crate) ticket: Ticket,
}
/// A read of one projected message, in the transcript window `incarnation`.
pub(crate) struct MessageRead {
pub(crate) session: SessionID,
pub(crate) message: SessionMessageID,
pub(crate) incarnation: u64,
}
/// A read of one message whose tool file data was dropped.
pub(crate) struct Restore {
pub(crate) session: SessionID,
pub(crate) message: SessionMessageID,
}
impl Ticket {
/// The session of a session read.
pub(crate) fn session(self) -> SessionKey {
let ReadKey::Session(key, _) = self.key else { unreachable!("a session read") };
key
}
}
/// A read an event or a completion asks for, started after the store's owner lets go of the state.
#[derive(Debug, Clone)]
pub(crate) enum Effect {
/// 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<Catalog>, 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),
/// Pending permission requests, after an overflowed read (already invalidated).
Permissions(SessionID),
/// Forms of an owner, after an overflowed read (already invalidated).
Forms(String, Option<Location>),
/// The other forms of an owner one of whose forms this client settled (already invalidated): read at once, also
/// offline, and a failure goes unreported.
FormsReplied(String, Location),
}
/// A streaming delta, borrowed from its event, so it applies without an owned event. Deltas are not durable, and no
/// head read replays them.
#[derive(Clone, Copy)]
pub(crate) enum Delta<'a> {
Text { session: &'a str, message: &'a str, delta: &'a str },
Reasoning { session: &'a str, message: &'a str, delta: &'a str },
ToolInput { session: &'a str, message: &'a str, tool: &'a str, delta: &'a str },
Compaction { session: &'a str, text: &'a str },
}
impl<'a> Delta<'a> {
/// The delta `event` is, if it is one.
pub(crate) fn of(event: &'a V2Event) -> Option<Self> {
Some(match event {
V2Event::SessionTextDelta(event) => {
let data = &event.data;
Delta::Text {
session: data.session_id.as_str(),
message: data.assistant_message_id.as_str(),
delta: &data.delta,
}
}
V2Event::SessionReasoningDelta(event) => {
let data = &event.data;
Delta::Reasoning {
session: data.session_id.as_str(),
message: data.assistant_message_id.as_str(),
delta: &data.delta,
}
}
V2Event::SessionToolInputDelta(event) => {
let data = &event.data;
Delta::ToolInput {
session: data.session_id.as_str(),
message: data.assistant_message_id.as_str(),
tool: &data.id,
delta: &data.delta,
}
}
V2Event::SessionCompactionDelta(event) => {
Delta::Compaction { session: event.data.session_id.as_str(), text: &event.data.text }
}
_ => return None,
})
}
}
impl Completion {
/// The keyed load it settles.
fn ticket(&self) -> Option<Ticket> {
Some(match self {
Self::Session(read, ..) => read.ticket,
Self::Messages(read, _) => read.ticket,
Self::Pending(read, _) | Self::Permissions(read, _) => read.ticket,
Self::Forms(read, _) => read.ticket,
Self::Jobs(read, _) => read.ticket,
Self::Catalog(read, _) => read.ticket,
Self::Shells(read, _) => read.ticket,
Self::Location(read, _) => return read.ticket,
Self::Projects(read, _) => read.ticket,
_ => return None,
})
}
/// The error the request failed with.
pub(crate) fn error(&self) -> Option<&Error> {
match self {
Self::Session(_, result, _) => result.as_ref().err(),
Self::Created { result, .. } => result.as_ref().err(),
Self::Active(_, result) => result.as_ref().err(),
Self::Messages(_, result) => result.as_ref().err(),
Self::Message { result, .. } | Self::Restored { result, .. } => result.as_ref().err(),
Self::Pending(_, result) => result.as_ref().err(),
Self::Compacted { result, .. } => result.as_ref().err(),
Self::Permissions(_, result) => result.as_ref().err(),
Self::Forms(_, result) => result.as_ref().err(),
Self::Jobs(_, result) => result.as_ref().err(),
Self::Catalog(_, result) => result.as_ref().err(),
Self::Shells(_, result) => result.as_ref().err(),
Self::Location(_, result) => result.as_ref().err(),
Self::Websearch(result) => result.as_ref().err(),
Self::Projects(_, result) => result.as_ref().err(),
Self::Renamed { .. }
| Self::Missing(_)
| Self::Older { .. }
| Self::OlderEnded { .. }
| Self::Prompted { .. }
| Self::PermissionReplied { .. }
| Self::FormReplied { .. }
| Self::Settled { .. } => None,
}
}
}
impl State {
/// Applies the answer to a request, then settles the keyed load it ends.
pub(crate) fn complete(&mut self, completion: Completion, effects: &mut Vec<Effect>) {
let settles = completion.ticket().map(|ticket| (ticket, completion.error().is_none()));
match completion {
Completion::Session(read, result, evicts) => self.complete_session_read(read, result, evicts),
Completion::Created { id, token, fresh, result } => self.complete_creation(&id, token, fresh, result),
Completion::Renamed { session, title } => self.rename(&session, title),
Completion::Active(token, result) => self.complete_active(token, result, effects),
Completion::Missing(id) => self.mark_deleted(&id),
Completion::Messages(read, result) => self.complete_messages(read, result, effects),
Completion::Message { session, incarnation, result: Ok(item) } => {
self.complete_message(&session, incarnation, item)
}
Completion::Restored { session, message, result: Ok(item) } => self.restore_files(&session, &message, item),
Completion::Older { session, page, fetched, next } => self.complete_older(&session, &page, fetched, next),
Completion::OlderEnded { session, token } => self.end_older(&session, token),
Completion::Pending(read, result) => self.complete_pending(read, result, effects),
Completion::Prompted { session, token, id, fresh, failed } => {
self.complete_prompt(&session, token, &id, fresh, failed)
}
Completion::Compacted { session, token, proposed, result } => {
self.complete_compaction(&session, token, &proposed, result)
}
Completion::Permissions(read, result) => self.complete_permissions(read, result, effects),
Completion::PermissionReplied { session, request } => self.remove_permission(&session, &request),
Completion::Forms(read, result) => self.complete_forms(read, result, effects),
Completion::FormReplied { owner, id, location } => self.complete_form_reply(owner, &id, location, effects),
Completion::Jobs(read, result) => self.complete_jobs(read, result, effects),
Completion::Catalog(read, Ok((at, loaded))) => self.complete_catalog(read, at, loaded),
Completion::Shells(read, Ok(response)) => self.complete_shells(read, response, effects),
Completion::Location(read, Ok(info)) => self.complete_location(read.adopt, info),
Completion::Websearch(Ok(providers)) => {
self.location_mut(&Location::from(&providers.location)).websearch = Some(providers.data);
}
Completion::Settled { key, token, catalog, location } => {
self.complete_settle(key, token, catalog, location, effects)
}
Completion::Projects(_, Ok(projects)) => self.replace_projects(projects),
// A failed read of these changes nothing but its keyed load.
Completion::Message { .. }
| Completion::Restored { .. }
| Completion::Catalog(..)
| Completion::Shells(..)
| Completion::Location(..)
| Completion::Websearch(_)
| Completion::Projects(..) => {}
}
if let Some((ticket, ok)) = settles {
self.settle_read(ticket.key, ticket.token, ok);
}
}
}
impl State {
/// Applies one event (a `handleEvent` arm), and pushes the reads it asks for to `effects`.
pub(crate) fn apply(&mut self, event: &V2Event, effects: &mut Vec<Effect>) {
if let Some(delta) = Delta::of(event) {
return self.apply_delta(delta);
}
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()));
effects.extend([Effect::Active(token), Effect::Rehydrate]);
self.job_roots(effects);
}
V2Event::SessionCreated(event) => self.on_session_created(&event.data, effects),
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) => self.on_model_selected(event, effects),
V2Event::SessionRenamed(event) => {
effects.push(Effect::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) => self.on_inbox_delivered(event, effects),
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) {
self.refresh_catalog(Catalog::UsageLimits, &Location::from(location), effects);
}
}
V2Event::SessionTextStarted(event) => {
self.on_text_started(&event.data.session_id, &event.data.assistant_message_id, event.data.ordinal)
}
V2Event::SessionTextEnded(event) => self.on_text_ended(&event.data),
V2Event::SessionToolInputStarted(event) => self.on_tool_input_started(event),
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::SessionReasoningEnded(event) => self.on_reasoning_ended(event),
V2Event::SessionRetryScheduled(event) => self.on_retry_scheduled(&event.data),
V2Event::SessionExecutionStarted(event) => self.on_execution_started(&event.data.session_id, effects),
V2Event::SessionCompactionStarted(event) => self.on_compaction_started(event),
V2Event::SessionExecutionSucceeded(event) => {
self.on_execution_ended(&event.id, event.created, &event.data.session_id, Outcome::Succeeded, effects)
}
V2Event::SessionExecutionFailed(event) => self.on_execution_ended(
&event.id,
event.created,
&event.data.session_id,
Outcome::Failed(&event.data.error),
effects,
),
V2Event::SessionExecutionInterrupted(event) => self.on_execution_ended(
&event.id,
event.created,
&event.data.session_id,
Outcome::Interrupted { shutdown: event.data.reason == SessionExecutionInterruptedDataReason::Shutdown },
effects,
),
V2Event::SessionViewed(event) => self.revalidate(&event.data.session_id, effects),
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::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) => self.on_worktree_resolved(&event.data, effects),
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),
_ => self.on_catalog_event(event, effects),
}
}
}

View file

@ -0,0 +1,555 @@
//! [`Data`] runs the store: it owns the [`State`] behind a lock, with the tasks its requests run as, and shares both
//! across handles. The lock never crosses an `.await`; requests run on the runtime captured at construction, including
//! those issued on the UI thread.
use std::collections::HashMap;
use std::future::Future;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use futures_util::FutureExt;
use futures_util::future::{BoxFuture, Shared};
use opencode_api::client::Client;
use opencode_api::generated::{SessionInboxCompaction, V2Event};
use opencode_api::kinds::EventKinds;
use opencode_util::lock;
use tokio::runtime::Handle;
use tokio::sync::{broadcast, watch};
use tokio::task::AbortHandle;
use crate::changes::Dirty;
use crate::core::{Completion, Ticket};
use crate::reads::{Read, Start};
use crate::state::{Error, Options, State, is_tag, session_not_found};
mod requests;
use requests::Fetch;
pub use requests::{Gate, LoadMore, Prompt};
/// How many [`Data::signals`] events a slow receiver may fall behind. One batch may hold hundreds of a listened type
/// (a burst of `filesystem.changed`).
const SIGNALS: usize = 1024;
/// The most streaming deltas kept for the [`DeltaListening`]s; past that, the oldest go.
pub const DELTAS: usize = 4096;
/// A spawned request any number of callers can await.
pub type Task<T> = Shared<BoxFuture<'static, Result<T, Error>>>;
type ErrorHandler = Arc<dyn Fn(&Error) + Send + Sync>;
/// The store handle. Cheap to clone.
#[derive(Clone)]
pub struct Data {
pub(crate) inner: Arc<Inner>,
}
pub(crate) struct Inner {
pub(crate) client: Client,
pub(crate) options: Options,
runtime: Handle,
store: Mutex<Store>,
revision: watch::Sender<u64>,
/// The events views act on themselves, sent after their batch is applied.
pub(crate) signals: broadcast::Sender<Arc<V2Event>>,
/// How many [`Listening`]s want each event kind on [`Data::signals`], by `kind as usize`.
pub(crate) listened: [AtomicUsize; opencode_api::generated::EventKind::COUNT],
/// How many [`Listening`]s want each name of the kinds a listener names (`EventKind::named`).
pub(crate) named: Mutex<HashMap<String, usize>>,
/// The streaming deltas kept for the [`DeltaListening`]s.
pub(crate) deltas: Mutex<Deltas>,
/// How many [`DeltaListening`]s live, as `deltas` counts them: a hint the hot path reads without the lock.
pub(crate) delta_listeners: AtomicUsize,
/// False while the event connection is not connected; follow-up reads are skipped then.
pub(crate) online: AtomicBool,
disposed: AtomicBool,
on_error: Mutex<Option<ErrorHandler>>,
}
impl Data {
/// A store on `client`. Must be called inside a tokio runtime, which runs its requests.
pub fn new(client: Client, options: Options) -> Self {
Self::with_runtime(client, options, Handle::current())
}
pub fn with_runtime(client: Client, options: Options, runtime: Handle) -> Self {
let state = State::new(&options);
Self {
inner: Arc::new(Inner {
client,
options,
runtime,
store: Mutex::new(Store { state, tasks: Tasks::default() }),
revision: watch::channel(0).0,
signals: broadcast::channel(SIGNALS).0,
listened: std::array::from_fn(|_| AtomicUsize::new(0)),
named: Mutex::default(),
deltas: Mutex::default(),
delta_listeners: AtomicUsize::new(0),
online: AtomicBool::new(true),
disposed: AtomicBool::new(false),
on_error: Mutex::new(None),
}),
}
}
pub fn client(&self) -> &Client {
&self.inner.client
}
/// Receives failed event-driven reads (`onError`). Without it they are logged.
pub fn on_error(&self, handler: impl Fn(&Error) + Send + Sync + 'static) {
*lock(&self.inner.on_error) = Some(Arc::new(handler));
}
/// Stops follow-up reads, as disposing the TS owner does.
pub fn dispose(&self) {
self.inner.disposed.store(true, Ordering::SeqCst);
self.write_tasks(|state, tasks| {
for (_, token) in state.settling.drain() {
if let Some(timer) = tasks.timers.remove(&token) {
timer.abort();
}
}
});
}
/// Reads the state. Keep `f` short: it holds the store lock. A `read` inside `f` on the same thread reuses the
/// outer guard, so code that runs under a read (a keymap condition during a row render) may read again.
pub fn read<R>(&self, f: impl FnOnce(&State) -> R) -> R {
self.read_tasks(|state, _| f(state))
}
/// [`Data::read`] with the tasks.
#[allow(unsafe_code)]
pub(crate) fn read_tasks<R>(&self, f: impl FnOnce(&State, &Tasks) -> R) -> R {
let key = self.key();
if let Some(store) = held(key) {
assert!(!store.is_null(), "store read inside a store write on this thread");
// SAFETY: the outer `read` on this thread holds the guard until this call returns, and lends only `&Store`.
let store = unsafe { &*store };
return f(&store.state, &store.tasks);
}
let guard = lock(&self.inner.store);
let _held = Held::enter(key, &*guard);
f(&guard.state, &guard.tasks)
}
/// The revision of the last flush.
pub fn revision(&self) -> u64 {
*self.inner.revision.borrow()
}
/// Wakes on every flush with its revision.
pub fn subscribe(&self) -> watch::Receiver<u64> {
self.inner.revision.subscribe()
}
/// Receives the events of each type a [`Listening`] wants, for the views that handle one themselves (`tui.*`,
/// `session.deleted`) and the plugins' `on_event`, after the store applied their batch. Streaming deltas are never
/// sent ([`DeltaListening::take`] has them). A receiver that falls behind skips the oldest.
pub fn signals(&self) -> broadcast::Receiver<Arc<V2Event>> {
self.inner.signals.subscribe()
}
/// Sends the events of each type in `kinds` on [`Data::signals`] until the returned guard drops.
pub fn listen(&self, kinds: impl Into<EventKinds>) -> Listening {
let kinds = kinds.into();
let mut named = lock(&self.inner.named);
for name in kinds.names() {
*named.entry(name.clone()).or_default() += 1;
}
for index in kinds.indices() {
self.inner.listened[index].fetch_add(1, Ordering::SeqCst);
}
Listening { inner: Arc::downgrade(&self.inner), kinds }
}
/// Keeps the streaming deltas (`session.*.delta`), which [`Data::signals`] never sends, for
/// [`DeltaListening::take`] from now until the returned guard drops: at most [`DELTAS`] it has not taken, the
/// oldest dropped past that. A batch that kept one wakes [`Data::subscribe`] also when it changed nothing.
pub fn listen_deltas(&self) -> DeltaListening {
let mut deltas = lock(&self.inner.deltas);
let id = deltas.ids;
deltas.ids += 1;
let next = deltas.next;
deltas.cursors.insert(id, next);
self.inner.delta_listeners.store(deltas.cursors.len(), Ordering::SeqCst);
DeltaListening { inner: Arc::downgrade(&self.inner), id }
}
/// Keeps `events`, one batch, for the [`DeltaListening`]s, all under one lock so a take gets all or none of
/// them; whether it kept any.
pub(crate) fn keep_deltas<'a>(&self, events: impl Iterator<Item = &'a V2Event>) -> bool {
let mut events = events.peekable();
if self.inner.delta_listeners.load(Ordering::SeqCst) == 0 || events.peek().is_none() {
return false;
}
let mut deltas = lock(&self.inner.deltas);
// Checked again under the lock: the last listener may have gone since.
if deltas.cursors.is_empty() {
return false;
}
for event in events {
if deltas.kept.len() == DELTAS {
deltas.kept.pop_front();
}
deltas.kept.push_back(event.clone());
deltas.next += 1;
}
true
}
/// Wakes [`Data::subscribe`] with the revision it has, for deltas kept without a change.
pub(crate) fn wake_deltas(&self) {
self.inner.revision.send_modify(|_| {});
}
/// Hands what changed since the last take to the one consumer, in `into`, and returns the revision of the last
/// flush. `into`'s earlier changes go: the consumer is done with them. The records the changes name stay marked
/// until the take, so the sweep before it frees none the consumer reads.
pub fn take_changes(&self, into: &mut Dirty) -> u64 {
self.lock().take(into)
}
/// Mutates the state and flushes its changes unless a batch is open.
pub(crate) fn write<R>(&self, f: impl FnOnce(&mut State) -> R) -> R {
let mut state = self.lock();
let result = f(&mut state);
self.flush(&mut state);
result
}
/// [`Data::write`] with the tasks.
pub(crate) fn write_tasks<R>(&self, f: impl FnOnce(&mut State, &mut Tasks) -> R) -> R {
let mut store = self.lock();
let Store { state, tasks } = &mut *store.guard;
let result = f(state, tasks);
self.flush(state);
result
}
/// Locks the state for a write. Locking it while this thread reads or writes it panics instead of deadlocking.
pub(crate) fn lock(&self) -> Locked<'_> {
let key = self.key();
assert!(held(key).is_none(), "store write inside a store read or write on this thread");
let guard = lock(&self.inner.store);
Locked { _held: Held::enter(key, std::ptr::null()), guard }
}
fn key(&self) -> usize {
Arc::as_ptr(&self.inner) as usize
}
pub(crate) fn flush(&self, state: &mut State) {
if state.batch > 0 {
return;
}
if let Some(revision) = state.log.flush() {
self.inner.revision.send_replace(revision);
}
}
pub(crate) fn runtime(&self) -> &Handle {
&self.inner.runtime
}
pub(crate) fn live(&self) -> bool {
!self.inner.disposed.load(Ordering::SeqCst) && self.inner.online.load(Ordering::SeqCst)
}
/// Spawns `future` at once and shares its result.
pub(crate) fn spawn<T: Clone + Send + Sync + 'static>(
&self,
future: impl Future<Output = Result<T, Error>> + Send + 'static,
) -> Task<T> {
let handle = self.inner.runtime.spawn(future);
async move {
handle.await.unwrap_or_else(|error| {
Err(Arc::new(opencode_api::error::Error::Transport(format!("store task failed: {error}"))))
})
}
.boxed()
.shared()
}
/// Runs a follow-up read unless offline or disposed (`refresh`). A `SessionNotFoundError`
/// marks the session deleted; other failures go to [`Data::on_error`].
///
/// Store reads start when they are built, so `load` builds the read only after the check, as
/// the TS `refresh` calls its `load` only when connected.
pub(crate) fn refresh<F>(&self, load: impl FnOnce(Data) -> F)
where
F: Future<Output = Result<(), Error>> + Send + 'static,
{
if !self.live() {
return;
}
let future = load(self.clone());
let data = self.clone();
self.inner.runtime.spawn(async move {
if let Err(error) = future.await {
data.refresh_failed(&error);
}
});
}
/// Handles a failed follow-up read (`refreshFailed`).
pub(crate) fn refresh_failed(&self, error: &Error) {
if !self.live() {
return;
}
if let Some(id) = session_not_found(error) {
self.complete(Completion::Missing(id), |_| {});
return;
}
if is_tag(error, "MessageNotFoundError") {
return;
}
let handler = lock(&self.inner.on_error).clone();
match handler {
Some(handler) => handler(error),
None => log::error!("failed to refresh client data: {error}"),
}
}
/// Runs the keyed read `read` once per invalidation (`sync.run`): a caller joins the load in flight, or begins one.
/// `begin` runs under the store lock before this returns, or, for a reload that waits for the load it replaces,
/// under the lock right after that wait. So no event after the call can miss what it registers (an overtake log,
/// the deletion epoch). The fetch runs outside the lock, and its completion settles the load.
fn sync<R: Fetch>(&self, read: Read, begin: impl FnOnce(&mut State, Ticket) -> R + Send + 'static) -> Task<()> {
let mut store = self.lock();
let key = store.read_key(read);
let (token, wait) = match store.start_read(key) {
Start::Done => return futures_util::future::ready(Ok(())).boxed().shared(),
Start::Join(token) => return store.tasks().reads[&token].clone(),
Start::Run(token) => (token, None),
Start::After(token, stale) => (token, Some(store.tasks().reads[&stale].clone())),
};
let ticket = Ticket { key, token };
let start = match wait {
None => Begin::Begun(begin(&mut store, ticket)),
Some(wait) => Begin::After(wait, begin),
};
store.load_read(key, token, matches!(start, Begin::After(..)));
let data = self.clone();
// Spawned under the lock, so its settlement cannot run before its state exists.
let task = self.spawn(async move {
let request = match start {
Begin::Begun(request) => request,
Begin::After(wait, begin) => {
let _ = wait.await;
data.write(|state| {
state.resume_read(key, token);
begin(state, ticket)
})
}
};
let completion = request.fetch(&data).await;
data.finish(completion, |tasks| {
tasks.reads.remove(&token);
})
});
store.tasks().reads.insert(token, task.clone());
task
}
/// Completes `completion` under the lock, where `release` drops the task it ends, then runs the effects it asks
/// for.
pub(crate) fn complete(&self, completion: Completion, release: impl FnOnce(&mut Tasks)) {
let mut effects = Vec::new();
self.write_tasks(|state, tasks| {
state.complete(completion, &mut effects);
release(tasks);
});
self.run(effects);
}
/// [`Data::complete`], passing on the error the request failed with.
fn finish(&self, completion: Completion, release: impl FnOnce(&mut Tasks)) -> Result<(), Error> {
let result = completion.error().cloned().map_or(Ok(()), Err);
self.complete(completion, release);
result
}
}
/// How a keyed load starts: begun under the caller's lock, or after the load it replaces.
enum Begin<R, B> {
Begun(R),
After(Task<()>, B),
}
thread_local! {
/// The stores whose state this thread holds locked, innermost last: the store a read lends, or null for a write.
static HOLDING: std::cell::RefCell<Vec<(usize, *const Store)>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// What this thread holds of the store `key`.
fn held(key: usize) -> Option<*const Store> {
HOLDING.with_borrow(|holding| holding.iter().rev().find(|(held, _)| *held == key).map(|(_, state)| *state))
}
/// One entry of [`HOLDING`], removed on drop.
struct Held(usize);
impl Held {
fn enter(key: usize, store: *const Store) -> Self {
HOLDING.with_borrow_mut(|holding| holding.push((key, store)));
Held(key)
}
}
impl Drop for Held {
fn drop(&mut self) {
HOLDING.with_borrow_mut(|holding| {
if let Some(index) = holding.iter().rposition(|(key, _)| *key == self.0) {
holding.remove(index);
}
});
}
}
/// What the lock guards: the state, and the tasks its requests run as.
pub(crate) struct Store {
state: State,
tasks: Tasks,
}
/// The tasks callers await, by the token the state keeps of their work. A task removes its entry when it settles, under
/// the lock that settles its work in the state, so a token the state holds always finds its task.
#[derive(Default)]
pub(crate) struct Tasks {
/// Keyed loads.
pub(crate) reads: HashMap<u64, Task<()>>,
/// Optimistic creations: what admissions to the session wait for.
pub(crate) creations: HashMap<u64, Task<()>>,
/// Admissions: what the next admission of the session waits for.
pub(crate) sends: HashMap<u64, Task<()>>,
/// Older-page loads.
pub(crate) loads: HashMap<u64, Task<bool>>,
/// Compactions: a second gesture returns the same request.
pub(crate) compactions: HashMap<u64, Task<SessionInboxCompaction>>,
/// Trailing refetch timers.
pub(crate) timers: HashMap<u64, AbortHandle>,
}
/// The locked [`Store`]; it derefs to the state.
pub(crate) struct Locked<'a> {
_held: Held,
guard: MutexGuard<'a, Store>,
}
impl Locked<'_> {
pub(crate) fn tasks(&mut self) -> &mut Tasks {
&mut self.guard.tasks
}
}
impl std::ops::Deref for Locked<'_> {
type Target = State;
fn deref(&self) -> &State {
&self.guard.state
}
}
impl std::ops::DerefMut for Locked<'_> {
fn deref_mut(&mut self) -> &mut State {
&mut self.guard.state
}
}
/// Event types [`Data::signals`] sends while it lives; see [`Data::listen`].
#[must_use = "the types stop being sent when this drops"]
pub struct Listening {
inner: std::sync::Weak<Inner>,
kinds: EventKinds,
}
impl Drop for Listening {
fn drop(&mut self) {
let Some(inner) = self.inner.upgrade() else { return };
let mut named = lock(&inner.named);
for index in self.kinds.indices() {
inner.listened[index].fetch_sub(1, Ordering::SeqCst);
}
for name in self.kinds.names() {
if let Some(count) = named.get_mut(name) {
*count -= 1;
}
}
named.retain(|_, count| *count > 0);
}
}
/// The streaming deltas kept for the [`DeltaListening`]s, numbered in the order kept.
#[derive(Default)]
pub(crate) struct Deltas {
/// The number the next delta kept gets.
next: u64,
/// The deltas some listener has not taken, the last numbered `next - 1`.
kept: std::collections::VecDeque<V2Event>,
/// Each listener's first delta not taken, by its ID.
cursors: HashMap<u64, u64>,
/// The ID of the next listener.
ids: u64,
}
impl Deltas {
/// Drops the deltas every listener has taken.
fn trim(&mut self) {
let first = self.next - self.kept.len() as u64;
let taken = self.cursors.values().min().copied().unwrap_or(self.next);
self.kept.drain(..taken.saturating_sub(first) as usize);
}
}
/// The streaming deltas kept for [`Self::take`] while it lives; see [`Data::listen_deltas`].
#[must_use = "the deltas stop being kept when this drops"]
pub struct DeltaListening {
inner: std::sync::Weak<Inner>,
id: u64,
}
impl DeltaListening {
/// The streaming deltas the store applied since this listener last took them, or since it started, oldest first.
pub fn take(&self) -> Vec<V2Event> {
let Some(inner) = self.inner.upgrade() else { return Vec::new() };
let mut deltas = lock(&inner.deltas);
let first = deltas.next - deltas.kept.len() as u64;
let next = deltas.next;
let Some(cursor) = deltas.cursors.insert(self.id, next) else { return Vec::new() };
let events = deltas.kept.iter().skip(cursor.saturating_sub(first) as usize).cloned().collect();
deltas.trim();
events
}
}
impl Drop for DeltaListening {
fn drop(&mut self) {
let Some(inner) = self.inner.upgrade() else { return };
let mut deltas = lock(&inner.deltas);
deltas.cursors.remove(&self.id);
inner.delta_listeners.store(deltas.cursors.len(), Ordering::SeqCst);
deltas.trim();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn data() -> (tokio::runtime::Runtime, Data) {
let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
let client = Client::new("http://opencode.local").unwrap();
let data = Data::with_runtime(client, Options::default(), runtime.handle().clone());
(runtime, data)
}
#[test]
#[should_panic(expected = "store read inside a store write")]
fn a_read_inside_a_write_panics() {
let (_runtime, data) = data();
data.write(|_| data.read(|_| ()));
}
}

View file

@ -0,0 +1,868 @@
//! The store's requests: how each is fetched, what each effect starts, and the public methods that begin them.
use std::future::Future;
use std::sync::Arc;
use futures_util::FutureExt;
use futures_util::future::{BoxFuture, try_join_all};
use opencode_api::client::Client;
use opencode_api::generated::*;
use tokio_util::sync::CancellationToken;
use super::{Data, Task, Tasks};
use crate::core::{
CatalogRead, Completion, Effect, Forms, Head, Info, Jobs, List, LocationRead, MessageRead, Projects, Restore,
Shells,
};
use crate::forms::{Form, GLOBAL, form_read};
use crate::inbox::Admission;
use crate::location::{Catalog, Loaded, Location, SETTLE};
use crate::messages::Page;
use crate::reads::{Read, ReadKey, SessionRead};
use crate::sessions::{CreateSession, Creation};
use crate::state::{Error, MESSAGE_PAGE, SessionStatus, State, is_tag};
/// Children per page of a family read (`CHILD_PAGE`).
const CHILD_PAGE: i64 = 200;
impl Data {
/// Runs what an event or a completion asks for. Every read goes through `refresh`, which checks the connection
/// before building it. A settle timer checks when it fires.
pub(crate) fn run(&self, effects: Vec<Effect>) {
for effect in effects {
match effect {
Effect::Session(id) => self.refresh(move |data| data.session_sync(&id, false)),
Effect::Messages(id) => self.refresh(move |data| data.message_sync(&id)),
Effect::Message(session, message) => self.fetch_message(session, message),
Effect::Renamed(session, title) => self.renamed(session, title),
Effect::Active(token) => self.rehydrate(token),
Effect::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());
}
Effect::Catalogs(catalogs, location) => self.refresh_catalogs(catalogs, location),
Effect::Settle(catalog, location) => self.settle(catalog, location),
Effect::Websearch(location) => self.refresh(move |data| data.websearch_refresh(Some(&location))),
Effect::Jobs(root) => self.refresh(move |data| data.job_sync(&root)),
Effect::Permissions(session) => self.refresh(move |data| data.permission_sync(&session)),
Effect::Forms(owner, location) => self.refresh(move |data| data.form_sync(&owner, location.as_ref())),
Effect::FormsReplied(owner, location) => drop(self.form_sync(&owner, Some(&location))),
}
}
}
/// Fetches `request` as a follow-up read, and completes it.
fn follow(&self, request: impl Fetch) {
self.refresh(|data| async move {
let completion = request.fetch(&data).await;
data.finish(completion, |_| {})
});
}
}
/// A request the driver fetches: its I/O, and the completion its answer makes, failed or not.
pub(super) trait Fetch: Send + 'static {
fn fetch(self, data: &Data) -> impl Future<Output = Completion> + Send;
}
impl Fetch for Info {
async fn fetch(self, data: &Data) -> Completion {
let info = async {
let info = data.client().session_get(&SessionGetInput { session_id: self.id.clone() }).await;
info.map_err(|error| (Arc::new(error), true))
};
let family = async {
if !self.children {
return Ok(Vec::new());
}
list_children(data.client(), &self.id).await.map_err(|error| (error, false))
};
match futures_util::future::try_join(info, family).await {
Ok(found) => Completion::Session(self, Ok(found), false),
Err((error, evicts)) => Completion::Session(self, Err(error), evicts),
}
}
}
impl Fetch for Head {
async fn fetch(self, data: &Data) -> Completion {
let input = MessageListInput {
session_id: self.session.clone(),
limit: Some(data.inner.options.initial_message_limit.unwrap_or(MESSAGE_PAGE)),
order: Some(MessageListInputOrder::Desc),
..Default::default()
};
Completion::Messages(self, data.client().message_list(&input).await.map_err(Error::new))
}
}
impl Fetch for MessageRead {
async fn fetch(self, data: &Data) -> Completion {
let input = SessionMessageGetInput { session_id: self.session.clone(), message_id: self.message };
let result = data.client().session_message_get(&input).await.map_err(Error::new);
Completion::Message { session: self.session, incarnation: self.incarnation, result }
}
}
impl Fetch for Restore {
async fn fetch(self, data: &Data) -> Completion {
let input = SessionMessageGetInput { session_id: self.session.clone(), message_id: self.message.clone() };
let result = data.client().session_message_get(&input).await.map_err(Error::new);
Completion::Restored { session: self.session, message: self.message, result }
}
}
/// Pending inbox items, or pending permission requests, as its key says.
impl Fetch for List {
async fn fetch(self, data: &Data) -> Completion {
let session_id = self.session.clone();
if matches!(self.ticket.key, ReadKey::Session(_, SessionRead::Pending)) {
let result = data.client().session_inbox_list(&SessionInboxListInput { session_id }).await;
return Completion::Pending(self, result.map_err(Error::new));
}
let result = data.client().permission_list(&PermissionListInput { session_id }).await;
Completion::Permissions(self, result.map_err(Error::new))
}
}
impl Fetch for Forms {
async fn fetch(self, data: &Data) -> Completion {
let result = match &self.form {
(owner, location) if owner == GLOBAL => {
let input = FormListInput { location: location.as_ref().and_then(Location::query) };
data.client().form_list(&input).await.map(|response| {
let at = Location::from(&response.location);
let list = response
.data
.into_iter()
.filter(|form| form.session_id == GLOBAL)
.map(|info| Form { info, location: Some(at.clone()) });
(list.collect(), Some(at))
})
}
(owner, _) => {
let input = SessionFormListInput { session_id: owner.clone() };
let list = data.client().session_form_list(&input).await;
list.map(|list| (list.into_iter().map(|info| Form { info, location: None }).collect(), None))
}
};
Completion::Forms(self, result.map_err(Error::new))
}
}
impl Fetch for Jobs {
async fn fetch(self, data: &Data) -> Completion {
let input = ExperimentalJobListInput {
session_id: Some(self.root.clone()),
status: Some(JobStatus::Running),
descendants: Some(true),
..ExperimentalJobListInput::default()
};
Completion::Jobs(self, data.client().experimental_job_list(&input).await.map_err(Error::new))
}
}
impl Fetch for CatalogRead {
async fn fetch(self, data: &Data) -> Completion {
let result = load(data.client(), self.catalog, &self.location).await.map_err(Error::new);
Completion::Catalog(self, result)
}
}
impl Fetch for Shells {
async fn fetch(self, data: &Data) -> Completion {
let input = ShellListInput { location: self.location.query() };
Completion::Shells(self, data.client().shell_list(&input).await.map_err(Error::new))
}
}
impl Fetch for LocationRead {
async fn fetch(self, data: &Data) -> Completion {
let input = LocationGetInput { location: self.location.query() };
Completion::Location(self, data.client().location_get(&input).await.map_err(Error::new))
}
}
impl Fetch for Projects {
async fn fetch(self, data: &Data) -> Completion {
let result = data.client().project_list(&ProjectListInput::default()).await.map_err(Error::new);
Completion::Projects(self, result)
}
}
/// Sessions.
impl Data {
/// Reads a session once per invalidation (`session.sync`); with `children`, also every direct
/// child, under its own key.
pub fn session_sync(&self, id: &SessionID, children: bool) -> Task<()> {
let read = if children { SessionRead::Family } else { SessionRead::Info };
self.sync(Read::Session(id.as_str(), read), State::begin_session_read)
}
pub fn session_invalidate(&self, id: &SessionID) {
self.write(|state| state.invalidate(Read::Session(id.as_str(), SessionRead::Info)));
}
/// Stores fetched info, as a list read does.
pub fn remember(&self, info: SessionInfo) {
self.write(|state| state.remember(info));
}
pub fn set_status(&self, id: &SessionID, status: SessionStatus) {
self.write(|state| state.set_status(id, status));
}
/// Forgets a session as deleted.
pub fn forget(&self, id: &SessionID) {
self.write(|state| state.mark_deleted(id));
}
/// Clears heavy cached data of the family of `id`.
pub fn evict(&self, id: &SessionID) {
self.write(|state| state.evict(id));
}
/// Optimistic creation: admits a local record under a client-minted ID so a session view can
/// open at once, then creates the session. Prompts to it wait for the request; a failure
/// removes the record unless the server acknowledged it.
pub fn session_create(&self, input: CreateSession) -> (SessionID, Task<SessionInfo>) {
let mut store = self.lock();
let Creation { id, token, fresh, input } = store.begin_creation(input);
let data = self.clone();
let session = id.clone();
let task = self.spawn(async move {
let result = data.client().session_create(&input).await.map_err(Error::new);
let completion = Completion::Created { id: session, token, fresh, result: result.clone() };
data.complete(completion, |tasks| {
tasks.creations.remove(&token);
});
result
});
if fresh {
store.tasks().creations.insert(token, task.clone().map(|result| result.map(|_| ())).boxed().shared());
}
self.flush(&mut store);
(id, task)
}
/// Applies a live title after the session's reads, so a racing read cannot overwrite it.
fn renamed(&self, session: SessionID, title: String) {
self.refresh(|data| async move {
let family = data.read(|state| state.family_loading(&session));
let own = data.session_sync(&session, false);
if family {
futures_util::future::try_join(own, data.session_sync(&session, true)).await?;
} else {
own.await?;
}
data.complete(Completion::Renamed { session, title }, |_| {});
Ok(())
});
}
/// Reads the `session.active` snapshot of connection `token`.
fn rehydrate(&self, token: u64) {
self.refresh(move |data| async move {
let result = data.client().session_active().await.map_err(Error::new);
let failed = result.as_ref().err().cloned();
data.complete(Completion::Active(token, result), |_| {});
failed.map_or(Ok(()), Err)
});
}
}
/// Every direct child, newest first, through every page (`listChildren`).
async fn list_children(client: &Client, parent: &SessionID) -> Result<Vec<SessionInfo>, Error> {
let mut input = SessionListInput {
parent_id: Some(Some(parent.clone())),
order: Some(SessionListInputOrder::Desc),
limit: Some(CHILD_PAGE),
..Default::default()
};
let mut children = Vec::new();
loop {
let page = client.session_list(&input).await.map_err(Error::new)?;
let full = page.data.len() as i64 >= CHILD_PAGE;
children.extend(page.data);
let Some(next) = page.cursor.next.flatten().filter(|_| full) else { return Ok(children) };
// Later pages carry only the cursor and the size, as in TS.
input = SessionListInput { cursor: Some(next), limit: Some(CHILD_PAGE), ..Default::default() };
}
}
/// Messages.
impl Data {
/// Reads the newest transcript page once per invalidation. Merge concurrent events by `durable.seq`; see
/// `State::publish_head`.
pub fn message_sync(&self, session: &SessionID) -> Task<()> {
self.sync(Read::Session(session.as_str(), SessionRead::Messages), State::begin_messages)
}
pub fn message_invalidate(&self, session: &SessionID) {
self.write(|state| state.invalidate(Read::Session(session.as_str(), SessionRead::Messages)));
}
/// Follows a setting that changes while the client runs (`omitToolFileData` as a function): it applies to messages
/// and events stored from now on. Turning it off does not bring back dropped payloads; see [`Data::restore_files`].
pub fn set_omit_tool_file_data(&self, omit: bool) {
self.lock().omit_file_data = omit;
}
/// Re-reads every loaded message whose tool file data was dropped, for a client that starts showing tool files
/// (`message.restoreFiles`). Each session's messages are re-read one at a time, so many screenshots don't fan out
/// at once.
pub fn restore_files(&self) {
for (session, ids) in self.read(State::dropped_files) {
let data = self.clone();
self.runtime().spawn(async move {
for message in ids {
let completion = Restore { session: session.clone(), message }.fetch(&data).await;
if let Err(error) = data.finish(completion, |_| {}) {
data.refresh_failed(&error);
}
}
});
}
}
/// Refetches one projected message and upserts it (the `session.model.selected` read). A response that
/// arrives after the transcript was deleted, evicted or reverted publishes nothing (deviation
/// O6-held-message-read).
fn fetch_message(&self, session: SessionID, message: SessionMessageID) {
let incarnation = self.read(|state| state.incarnation(&session));
self.follow(MessageRead { session, message, incarnation });
}
/// Loads older pages (`message.loadMore`). Joins a load in flight; with `all`, it then
/// continues to the oldest page.
pub async fn message_load_more(&self, session: &SessionID, options: LoadMore) -> Result<(), Error> {
let cancelled = || options.cancel.as_ref().is_some_and(|token| token.is_cancelled());
if cancelled() {
return Ok(());
}
loop {
let pending = self.read_tasks(|state, tasks| {
let token = state.sessions.get(session)?.message_load?;
Some(tasks.loads[&token].clone())
});
let Some(pending) = pending else { break };
let published = match &options.cancel {
None => pending.await?,
Some(token) => tokio::select! {
result = pending => match result {
Ok(published) => published,
Err(_) if token.is_cancelled() => return Ok(()),
Err(error) => return Err(error),
},
_ = token.cancelled() => return Ok(()),
},
};
if (!options.all && published) || cancelled() {
return Ok(());
}
}
if cancelled() {
return Ok(());
}
match self.start_load(session, options) {
Some(task) => task.await.map(|_| ()),
None => Ok(()),
}
}
/// Starts an older-page load from the current cursor, if any, and registers it for joiners.
fn start_load(&self, session: &SessionID, options: LoadMore) -> Option<Task<bool>> {
let mut store = self.lock();
let (token, page) = store.begin_older(session)?;
let data = self.clone();
let id = session.clone();
let task = self.spawn(async move {
let cancel = options.cancel;
let result = load_pages(&data, &id, page, options.all, cancel.as_ref()).await;
data.complete(Completion::OlderEnded { session: id, token }, |tasks| {
tasks.loads.remove(&token);
});
match result {
Err(_) if cancel.as_ref().is_some_and(CancellationToken::is_cancelled) => Ok(false),
result => result,
}
});
store.tasks().loads.insert(token, task.clone());
self.flush(&mut store);
Some(task)
}
}
/// Options of [`Data::message_load_more`].
#[derive(Debug, Clone, Default)]
pub struct LoadMore {
/// Loads every older page in one publication.
pub all: bool,
/// Cancels the wait and the request (the TS `signal`).
pub cancel: Option<CancellationToken>,
}
/// Publishes older pages once. If a refresh changes the cursor, restart from the new cursor to avoid a gap. Returns
/// false on cancellation before publication.
async fn load_pages(
data: &Data,
session: &SessionID,
mut page: Page,
all: bool,
cancel: Option<&CancellationToken>,
) -> Result<bool, Error> {
loop {
let mut fetched = Vec::new();
let mut next = Some(page.cursor.clone());
while let Some(cursor) = next {
let input = MessageListInput {
session_id: session.clone(),
limit: Some(if all { 200 } else { MESSAGE_PAGE }),
cursor: Some(cursor),
..Default::default()
};
let request = data.client().message_list(&input);
let response = match cancel {
None => request.await,
Some(token) => tokio::select! {
response = request => response,
_ = token.cancelled() => return Ok(false),
},
}
.map_err(Arc::new)?;
if cancel.is_some_and(CancellationToken::is_cancelled) {
return Ok(false);
}
fetched.extend(response.data);
next = response.cursor.next.flatten();
if !all {
break;
}
}
let moved = data.write(|state| {
let moved = state.page_moved(session, &page);
let completion = Completion::Older { session: session.clone(), page, fetched, next };
state.complete(completion, &mut Vec::new());
moved
});
match moved {
None => return Ok(true),
Some(None) => return Ok(false),
Some(Some(current)) => page = current,
}
}
}
/// A gate an admission waits for before it sends.
pub type Gate = BoxFuture<'static, Result<(), Error>>;
/// Input of [`Data::prompt`].
pub struct Prompt {
pub input: SessionPromptInput,
/// Waited for, with the session's creation and earlier admissions, before sending.
pub gate: Option<Gate>,
/// Runs after the gates, just before the prompt is sent.
pub prepare: Option<Box<dyn FnOnce() -> Gate + Send>>,
}
impl From<SessionPromptInput> for Prompt {
fn from(input: SessionPromptInput) -> Self {
Self { input, gate: None, prepare: None }
}
}
/// Inbox.
impl Data {
/// Reads pending inbox items once per invalidation (`pending.sync`), reconciling events that
/// overtook the response.
pub fn pending_sync(&self, session: &SessionID) -> Task<()> {
self.sync(Read::Session(session.as_str(), SessionRead::Pending), State::begin_pending)
}
/// Optimistic prompt admission: renders the prompt at once under a client-minted ID, then
/// sends it; the durable `session.inbox.enqueued` echo upserts the same ID. A failure rolls
/// back only rows this call admitted and the server has not acknowledged.
pub fn prompt(&self, prompt: impl Into<Prompt>) -> Task<SessionInboxUser> {
let prompt = prompt.into();
let mut request = prompt.input;
let session = request.session_id.clone();
let id = request.id.clone().flatten().unwrap_or_else(|| SessionMessageID(opencode_api::id::message()));
request.id = Some(Some(id.clone()));
let fresh = self.write(|state| state.admit_prompt(&request));
let prepare = prompt.prepare;
self.send_admission(
&session.clone(),
prompt.gate,
None,
move |data| async move {
if let Some(prepare) = prepare {
prepare().await?;
}
data.client().session_prompt(&request).await.map_err(Error::new)
},
move |token, result| Completion::Prompted { session, token, id, fresh, failed: result.is_err() },
|_, _, _| {},
)
}
/// Admits a compaction (`compact`). A second gesture while one is in flight returns the same
/// request. The server may coalesce onto another ID; the response's ID then replaces the
/// proposed row.
pub fn compact(&self, session: &SessionID, model: Option<ModelRef>) -> Task<SessionInboxCompaction> {
let id = SessionMessageID(opencode_api::id::message());
let existing = self.write_tasks(|state, tasks| {
let token = state.admit_compaction(session, &id)?;
Some(tasks.compactions[&token].clone())
});
if let Some(request) = existing {
return request;
}
let input = SessionCompactInput { session_id: session.clone(), id: Some(id.clone()), delivery: None };
let target = session.clone();
self.send_admission(
session,
None,
Some(id.clone()),
move |data| async move {
if let Some(model) = model {
data.client()
.session_switch_model(&SessionSwitchModelInput { session_id: input.session_id.clone(), model })
.await
.map_err(Error::new)?;
}
data.client().session_compact(&input).await.map_err(Error::new)
},
move |token, result| Completion::Compacted { session: target, token, proposed: id, result: result.clone() },
|tasks, token, request| {
tasks.compactions.insert(token, request.clone());
},
)
}
/// Sends one admission after the session's creation, the previous admission of the session,
/// and `gate` (`sendAdmission`); a compaction under its proposed ID `compaction`. The admission begins under the
/// lock that spawns the request, where `register` keeps its task, and `complete` turns its result into its
/// completion.
fn send_admission<T, F, Fut>(
&self,
session: &SessionID,
gate: Option<Gate>,
compaction: Option<SessionMessageID>,
send: F,
complete: impl FnOnce(u64, &Result<T, Error>) -> Completion + Send + 'static,
register: impl FnOnce(&mut Tasks, u64, &Task<T>),
) -> Task<T>
where
T: Clone + Send + Sync + 'static,
F: FnOnce(Data) -> Fut + Send + 'static,
Fut: Future<Output = Result<T, Error>> + Send + 'static,
{
let mut store = self.lock();
let Admission { token, creating, previous } = store.begin_admission(session, compaction);
let created = creating.map(|creating| store.tasks().creations[&creating].clone());
let previous = previous.map(|previous| store.tasks().sends[&previous].clone());
let data = self.clone();
let request = self.spawn(async move {
let ready = futures_util::future::try_join3(
async move {
match gate {
Some(gate) => gate.await,
None => Ok(()),
}
},
async move {
match created {
Some(created) => created.await,
None => Ok(()),
}
},
async move {
// One failure does not block the next admission.
if let Some(previous) = previous {
let _ = previous.await;
}
Ok(())
},
)
.await;
let result = match ready {
Ok(_) => send(data.clone()).await,
Err(error) => Err(error),
};
data.complete(complete(token, &result), |tasks| {
tasks.sends.remove(&token);
tasks.compactions.remove(&token);
});
result
});
let chain = request.clone().map(|result| result.map(|_| ())).boxed().shared();
store.tasks().sends.insert(token, chain);
register(store.tasks(), token, &request);
self.flush(&mut store);
request
}
}
/// Locations and their catalogs.
impl Data {
fn resolve(&self, location: Option<&Location>) -> Location {
location.cloned().unwrap_or_else(|| self.read(|state| state.default_location().clone()))
}
/// Reads a catalog once per invalidation. It publishes under the location the server
/// answers with; model and provider reads also under the requested one.
pub fn catalog_sync(&self, catalog: Catalog, location: Option<&Location>) -> Task<()> {
let read = Read::Catalog(catalog, &self.resolve(location));
match catalog {
Catalog::Shell => self.sync(read, State::begin_shells),
_ => self.sync(read, State::begin_catalog),
}
}
pub fn catalog_invalidate(&self, catalog: Catalog, location: Option<&Location>) {
let location = self.resolve(location);
self.write(|state| state.invalidate(Read::Catalog(catalog, &location)));
}
/// Reads a location's running shells once per invalidation.
pub fn shell_sync(&self, location: Option<&Location>) -> Task<()> {
self.catalog_sync(Catalog::Shell, location)
}
/// Reads location info once per invalidation (`location.syncInfo`). A read of the default
/// location adopts the server's directory as the default.
pub fn location_sync_info(&self, location: Option<&Location>) -> Task<()> {
let adopt = location.is_none();
self.sync(Read::Location(&self.resolve(location)), move |state, ticket| state.begin_location(ticket, adopt))
}
/// Reads location info, then every catalog a session view shows (`location.sync`).
pub fn location_sync(&self, location: Option<&Location>) -> Task<()> {
let data = self.clone();
let requested = location.cloned();
self.spawn(async move {
data.location_sync_info(requested.as_ref()).await?;
let location = data.resolve(requested.as_ref());
let mut reads: Vec<Task<()>> = [
Catalog::Vcs,
Catalog::Agent,
Catalog::Command,
Catalog::Integration,
Catalog::McpServer,
Catalog::McpResource,
Catalog::Model,
Catalog::Provider,
Catalog::Reference,
Catalog::Skill,
Catalog::Shell,
]
.into_iter()
.map(|catalog| data.catalog_sync(catalog, Some(&location)))
.collect();
reads.push(data.form_sync(crate::forms::GLOBAL, Some(&location)));
try_join_all(reads).await?;
Ok(())
})
}
/// Reads web search providers on every call; there is no cached read.
pub fn websearch_refresh(&self, location: Option<&Location>) -> Task<()> {
let location = self.resolve(location);
let data = self.clone();
self.spawn(async move {
let input = WebsearchProvidersInput { location: location.query() };
let result = data.client().websearch_providers(&input).await.map_err(Error::new);
data.finish(Completion::Websearch(result), |_| {})
})
}
/// `server.connected`: reads the default location's info without the sync key, as TS does.
fn rehydrate_location(&self) {
self.follow(LocationRead { ticket: None, location: self.resolve(None), adopt: false });
}
fn refresh_catalogs(&self, catalogs: Vec<Catalog>, location: Location) {
self.refresh(|data| {
let reads: Vec<Task<()>> =
catalogs.into_iter().map(|catalog| data.catalog_sync(catalog, Some(&location))).collect();
async move { try_join_all(reads).await.map(|_| ()) }
});
}
/// Reads `catalog` once a burst of events that ask for it goes quiet for [`SETTLE`].
fn settle(&self, catalog: Catalog, location: Location) {
let data = self.clone();
let mut store = self.lock();
let (key, token, previous) = store.begin_settle(catalog, &location);
// Spawned under the lock, so the timer cannot fire before its entry exists.
let handle = self.runtime().spawn(async move {
tokio::time::sleep(SETTLE).await;
data.complete(Completion::Settled { key, token, catalog, location }, |tasks| {
tasks.timers.remove(&token);
});
});
store.tasks().timers.insert(token, handle.abort_handle());
if let Some(previous) = previous.and_then(|previous| store.tasks().timers.remove(&previous)) {
previous.abort();
}
}
}
/// Permissions, forms, jobs and projects.
impl Data {
/// Reads pending permissions once per invalidation. Requests opened or settled during the read take precedence
/// over its snapshot.
pub fn permission_sync(&self, session: &SessionID) -> Task<()> {
self.sync(Read::Session(session.as_str(), SessionRead::Permissions), State::begin_permissions)
}
/// Replies and drops the request; an already settled request counts as replied.
pub async fn permission_reply(&self, input: PermissionReplyInput) -> Result<(), Error> {
if let Err(error) = self.client().permission_reply(&input).await {
let error = Error::new(error);
if !is_tag(&error, "PermissionNotFoundError") {
return Err(error);
}
}
let completion = Completion::PermissionReplied { session: input.session_id, request: input.request_id };
self.complete(completion, |_| {});
Ok(())
}
/// Reads pending forms for a session or location. Forms created or settled during the read take precedence over
/// its snapshot.
pub fn form_sync(&self, owner: &str, location: Option<&Location>) -> Task<()> {
let location = self.resolve(location);
self.sync(form_read(owner, &location), State::begin_forms)
}
pub fn form_invalidate(&self, owner: &str, location: Option<&Location>) {
self.write(|state| {
let location = location.unwrap_or(state.default_location()).clone();
state.invalidate(form_read(owner, &location));
});
}
/// Answers a form and drops it. A form that is already settled counts as answered. A global
/// form needs its location, which the request names in a header.
pub async fn form_reply(&self, input: SessionFormReplyInput, location: Option<&Location>) -> Result<(), Error> {
let result = form_client(self.client(), &input.session_id, location).session_form_reply(&input).await;
self.settle_form(input.session_id, input.form_id, location, result)
}
/// Cancels a form and drops it; see [`Data::form_reply`].
pub async fn form_cancel(&self, input: SessionFormCancelInput, location: Option<&Location>) -> Result<(), Error> {
let result = form_client(self.client(), &input.session_id, location).session_form_cancel(&input).await;
self.settle_form(input.session_id, input.form_id, location, result)
}
/// Drops a form that a reply or a cancel settled; the owner's other forms are read again.
fn settle_form(
&self,
owner: String,
id: FormID,
location: Option<&Location>,
result: Result<(), opencode_api::error::Error>,
) -> Result<(), Error> {
if let Err(error) = result {
let settled = error.declared().is_some_and(|declared| {
matches!(declared.tag.as_deref(), Some("FormNotFoundError" | "FormAlreadySettledError"))
&& declared.body.get("id").and_then(serde_json::Value::as_str) == Some(id.0.as_str())
});
if !settled {
return Err(Error::new(error));
}
}
self.complete(Completion::FormReplied { owner, id, location: location.cloned() }, |_| {});
Ok(())
}
/// Reads the running jobs of the tree under `root` once per invalidation. Job events received during the read
/// apply over its answer.
pub fn job_sync(&self, root: &SessionID) -> Task<()> {
self.sync(Read::Session(root.as_str(), SessionRead::Jobs), State::begin_jobs)
}
/// Cancels a running job, interrupting the work it started; a finished job stays finished.
pub async fn job_cancel(&self, id: &str) -> Result<(), Error> {
let input = ExperimentalJobCancelInput { id: id.to_owned() };
self.client().experimental_job_cancel(&input).await.map_err(Error::new)
}
/// Reads every project once per invalidation; the read replaces the cached set.
pub fn project_sync(&self) -> Task<()> {
self.sync(Read::Projects, |_, ticket| Projects { ticket })
}
}
/// Global forms name their location in a header (`formRequestOptions`).
fn form_client(client: &Client, owner: &str, location: Option<&Location>) -> Client {
match (owner, location) {
(GLOBAL, Some(location)) => {
client.with_header("x-opencode-directory", opencode_api::js::encode_component(&location.directory))
}
_ => client.clone(),
}
}
async fn load(
client: &Client,
catalog: Catalog,
location: &Location,
) -> Result<(Location, Loaded), opencode_api::error::Error> {
let query = location.query();
Ok(match catalog {
Catalog::Vcs => {
let response = client.vcs_get(&VcsGetInput { location: query }).await?;
((&response.location).into(), Loaded::Vcs(response.data))
}
Catalog::UsageLimits => {
let response = client.experimental_usage_limits(&ExperimentalUsageLimitsInput { location: query }).await?;
((&response.location).into(), Loaded::UsageLimits(response.data))
}
Catalog::Agent => {
let response = client.agent_list(&AgentListInput { location: query }).await?;
((&response.location).into(), Loaded::Agent(response.data.into()))
}
Catalog::Command => {
let response = client.command_list(&CommandListInput { location: query }).await?;
((&response.location).into(), Loaded::Command(response.data.into()))
}
// Config answers without a location; it publishes under the requested directory.
Catalog::Config => {
let entries = client.config_get(&ConfigGetInput { location: query }).await?;
(Location::new(location.directory.clone()), Loaded::Config(entries.into()))
}
Catalog::Integration => {
let response = client.integration_list(&IntegrationListInput { location: query }).await?;
((&response.location).into(), Loaded::Integration(response.data.into()))
}
Catalog::McpServer => {
let response = client.mcp_list(&McpListInput { location: query }).await?;
((&response.location).into(), Loaded::McpServer(response.data.into()))
}
Catalog::McpResource => {
let response = client.mcp_resource_catalog(&McpResourceCatalogInput { location: query }).await?;
((&response.location).into(), Loaded::McpResource(response.data.resources.into()))
}
Catalog::Model => {
let response = client.model_list(&ModelListInput { location: query, types: None }).await?;
((&response.location).into(), Loaded::Model(response.data.into()))
}
Catalog::Provider => {
let response = client.provider_list(&ProviderListInput { location: query }).await?;
((&response.location).into(), Loaded::Provider(response.data.into()))
}
Catalog::Reference => {
let response = client.reference_list(&ReferenceListInput { location: query }).await?;
((&response.location).into(), Loaded::Reference(response.data.into()))
}
Catalog::Skill => {
let response = client.skill_list(&SkillListInput { location: query }).await?;
((&response.location).into(), Loaded::Skill(response.data.into()))
}
Catalog::Shell => unreachable!("shells have their own request"),
})
}

View file

@ -1,10 +1,10 @@
//! Pending forms are kept in their session's record, or under [`GLOBAL`] for elicitations without a session.
use opencode_api::client::Client;
use opencode_api::generated::*;
use crate::core::{Effect, Forms, Ticket};
use crate::location::Location;
use crate::reads::{Read, SessionRead};
use crate::state::{Data, Error, Overlay, State, Task, evict_missing};
use crate::reads::{Read, ReadKey, SessionRead};
use crate::state::{Error, Overlay, State};
/// The owner of global MCP elicitations. They temporarily use "global" instead of a real session
/// ID, so the server cannot recover their location when settling them; the store keeps the event
@ -22,7 +22,7 @@ pub struct Form {
pub(crate) type FormRead = (String, Option<Location>);
/// The keyed read of `owner`'s forms: a session's own, or the global forms of `location`.
fn form_read<'a>(owner: &'a str, location: &'a Location) -> Read<'a> {
pub(crate) fn form_read<'a>(owner: &'a str, location: &'a Location) -> Read<'a> {
match owner {
GLOBAL => Read::GlobalForms(location),
_ => Read::Session(owner, SessionRead::Forms),
@ -118,6 +118,67 @@ impl State {
}
}
/// Begins a read of the forms of `ticket`'s owner, with an overlay of the forms created and settled meanwhile.
pub(crate) fn begin_forms(&mut self, ticket: Ticket) -> Forms {
let (owner, location) = match ticket.key {
ReadKey::Session(key, _) => (self.sessions[key].id.0.clone(), None),
ReadKey::GlobalForms(at) => (GLOBAL.to_owned(), self.location_at(at).cloned()),
_ => unreachable!("a form read"),
};
let read = self.token();
let form = (owner, location);
self.form_reads.insert(form.clone(), Overlay::new(read));
Forms { ticket, form, read, started: self.deletion_epoch }
}
/// Publishes the form read `read` with the forms created and settled during it, unless a newer read or a
/// deletion of the owner since it began supersedes it. An overflowed overlay reads again instead.
pub(crate) fn complete_forms(
&mut self,
forms: Forms,
result: Result<(Vec<Form>, Option<Location>), Error>,
effects: &mut Vec<Effect>,
) {
let overlay = Overlay::take(&mut self.form_reads, &forms.form, forms.read);
let (owner, location) = forms.form;
let (list, at) = match result {
Ok(found) => found,
Err(error) => {
if owner != GLOBAL {
self.evict_missing(&error);
}
return;
}
};
let Some(overlay) = overlay else { return };
if self.deleted_since(&owner, forms.started) {
return;
}
match overlay.apply(list, |form| &form.info.id.0) {
Some(list) => self.publish_forms(&owner, list, at),
None => {
self.invalidate_key(forms.ticket.key);
effects.push(Effect::Forms(owner, location));
}
}
}
/// Drops the form a reply or a cancel settled; the owner's other forms are read again at once.
pub(crate) fn complete_form_reply(
&mut self,
owner: String,
id: &FormID,
location: Option<Location>,
effects: &mut Vec<Effect>,
) {
if !self.remove_form(&owner, id, location.as_ref()) {
return;
}
let at = location.unwrap_or_else(|| self.default_location().clone());
self.invalidate(form_read(&owner, &at));
effects.push(Effect::FormsReplied(owner, at));
}
/// Publishes a form read; a global read only replaces the forms of `at`, where the server read them.
fn publish_forms(&mut self, owner: &str, mut list: Vec<Form>, at: Option<Location>) {
let forms = self.owner_forms(owner);
@ -133,103 +194,3 @@ impl State {
self.touch_forms(owner);
}
}
impl Data {
/// Reads pending forms for a session or location. Forms created or settled during the read take precedence over
/// its snapshot.
pub fn form_sync(&self, owner: &str, location: Option<&Location>) -> Task<()> {
let location = location.cloned().unwrap_or_else(|| self.read(|state| state.default_location().clone()));
let owner = owner.to_owned();
let read: FormRead = (owner.clone(), (owner == GLOBAL).then(|| location.clone()));
let again = (owner.clone(), location.clone());
self.overlay_sync(
self.keyed(form_read(&owner, &location)),
SessionID(owner.clone()),
read,
|state, read, overlay| {
state.form_reads.insert(read.clone(), overlay);
},
|state, read, ticket| Overlay::take(&mut state.form_reads, read, ticket),
|form| &form.info.id.0,
move |data| async move {
if owner == GLOBAL {
let response = data
.client()
.form_list(&FormListInput { location: location.query() })
.await
.map_err(Error::new)?;
let at = Location::from(&response.location);
let list = response
.data
.into_iter()
.filter(|form| form.session_id == GLOBAL)
.map(|info| Form { info, location: Some(at.clone()) });
return Ok((list.collect(), Some(at)));
}
let list = data
.client()
.session_form_list(&SessionFormListInput { session_id: owner.clone() })
.await
.map_err(|error| evict_missing(&data, error))?;
Ok((list.into_iter().map(|info| Form { info, location: None }).collect(), None))
},
|state, read, list, at| state.publish_forms(&read.0, list, at),
move |data| data.form_sync(&again.0, Some(&again.1)),
)
}
pub fn form_invalidate(&self, owner: &str, location: Option<&Location>) {
self.write(|state| {
let location = location.unwrap_or(state.default_location()).clone();
state.invalidate(form_read(owner, &location));
});
}
/// Answers a form and drops it. A form that is already settled counts as answered. A global
/// form needs its location, which the request names in a header.
pub async fn form_reply(&self, input: SessionFormReplyInput, location: Option<&Location>) -> Result<(), Error> {
let result = form_client(self.client(), &input.session_id, location).session_form_reply(&input).await;
self.settle_form(&input.session_id, &input.form_id, location, result)
}
/// Cancels a form and drops it; see [`Data::form_reply`].
pub async fn form_cancel(&self, input: SessionFormCancelInput, location: Option<&Location>) -> Result<(), Error> {
let result = form_client(self.client(), &input.session_id, location).session_form_cancel(&input).await;
self.settle_form(&input.session_id, &input.form_id, location, result)
}
fn settle_form(
&self,
owner: &str,
id: &FormID,
location: Option<&Location>,
result: Result<(), opencode_api::error::Error>,
) -> Result<(), Error> {
if let Err(error) = result {
let settled = error.declared().is_some_and(|declared| {
matches!(declared.tag.as_deref(), Some("FormNotFoundError" | "FormAlreadySettledError"))
&& declared.body.get("id").and_then(serde_json::Value::as_str) == Some(id.0.as_str())
});
if !settled {
return Err(Error::new(error));
}
}
if !self.write(|state| state.remove_form(owner, id, location)) {
return Ok(());
}
// The form may have been one of several; read the rest again.
self.form_invalidate(owner, location);
drop(self.form_sync(owner, location));
Ok(())
}
}
/// Global forms name their location in a header (`formRequestOptions`).
fn form_client(client: &Client, owner: &str, location: Option<&Location>) -> Client {
match (owner, location) {
(GLOBAL, Some(location)) => {
client.with_header("x-opencode-directory", opencode_api::js::encode_component(&location.directory))
}
_ => client.clone(),
}
}

View file

@ -1,19 +1,16 @@
//! Pending inbox items and optimistic prompt and compaction admission.
use std::collections::HashSet;
use std::future::Future;
use futures_util::FutureExt;
use futures_util::future::BoxFuture;
use indexmap::IndexMap;
use opencode_api::generated::*;
use crate::changes::Touched;
use crate::connection::Follow;
use crate::core::{Effect, List, Ticket};
use crate::messages::{MessageExt, from_event};
use crate::reads::{Read, SessionRead};
use crate::sessions::Life;
use crate::state::{Compacting, Data, Error, SessionStatus, State, Task, evict_missing};
use crate::state::{Compacting, Error, SessionStatus, State};
/// `DataPendingStatus`: where a pending user prompt stands relative to the runner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -62,24 +59,6 @@ impl InboxExt for SessionInboxInfo {
}
}
/// A gate an admission waits for before it sends.
pub type Gate = BoxFuture<'static, Result<(), Error>>;
/// Input of [`Data::prompt`].
pub struct Prompt {
pub input: SessionPromptInput,
/// Waited for, with the session's creation and earlier admissions, before sending.
pub gate: Option<Gate>,
/// Runs after the gates, just before the prompt is sent.
pub prepare: Option<Box<dyn FnOnce() -> Gate + Send>>,
}
impl From<SessionPromptInput> for Prompt {
fn from(input: SessionPromptInput) -> Self {
Self { input, gate: None, prepare: None }
}
}
impl State {
/// Pending inbox items in admission order (`pending.list`).
pub fn pending(&self, session: &(impl AsRef<str> + ?Sized)) -> &[SessionInboxInfo] {
@ -239,7 +218,7 @@ impl State {
}
}
pub(crate) fn on_inbox_delivered(&mut self, event: &SessionInboxDelivered) -> Vec<Follow> {
pub(crate) fn on_inbox_delivered(&mut self, event: &SessionInboxDelivered, effects: &mut Vec<Effect>) {
let data = &event.data;
let session = &data.session_id;
let inbox = data.inbox_id.as_str();
@ -261,10 +240,10 @@ impl State {
// transcript reads its head again.
let read = Read::Session(session.as_str(), SessionRead::Messages);
if known || !self.has_read(read) {
return Vec::new();
return;
}
self.invalidate(read);
vec![Follow::Messages(session.clone())]
effects.push(Effect::Messages(session.clone()));
}
pub(crate) fn on_inbox_delivery_changed(&mut self, data: &SessionInboxDeliveryChangedData) {
@ -350,312 +329,231 @@ pub(crate) fn now() -> f64 {
opencode_util::time::now_ms() as f64
}
impl Data {
/// Reads pending inbox items once per invalidation (`pending.sync`), reconciling events that
/// overtook the response.
pub fn pending_sync(&self, session: &SessionID) -> Task<()> {
let session = session.clone();
// Events after this call must reach the read's overtake log, so it opens before the read
// is spawned.
let register = {
let session = session.clone();
move |state: &mut State, _| {
let token = state.token();
// Ordered, as the TS `Map`: overtaking enqueues keep their arrival order.
state.sessions.get_or_insert(&session).pending_read = Some((token, IndexMap::new()));
(state.deletion_epoch, token)
}
impl State {
/// Begins a read of the pending inbox items of the session of `ticket`. Events after this must reach the read's overtake
/// log, so it opens before the read is fetched.
pub(crate) fn begin_pending(&mut self, ticket: Ticket) -> List {
let read = self.token();
let record = &mut self.sessions[ticket.session()];
// Ordered, as the TS `Map`: overtaking enqueues keep their arrival order.
record.pending_read = Some((read, IndexMap::new()));
List { ticket, session: record.id.clone(), read, started: self.deletion_epoch }
}
/// Publishes the inbox read `read`, reconciling the events that overtook it.
pub(crate) fn complete_pending(
&mut self,
list: List,
result: Result<Vec<SessionInboxInfo>, Error>,
effects: &mut Vec<Effect>,
) {
let session = &list.session;
let updates = release_updates(self, session, list.read);
let response = match result {
Ok(response) => response,
Err(error) => return self.evict_missing(&error),
};
self.sync_start(
self.keyed(Read::Session(session.as_str(), SessionRead::Pending)),
register,
move |data, (started, token)| async move {
let response =
data.client().session_inbox_list(&SessionInboxListInput { session_id: session.clone() }).await;
let response = match response {
Ok(response) => response,
Err(error) => {
data.write(|state| {
release_updates(state, &session, token);
});
return Err(evict_missing(&data, error));
}
};
let reread = data.write(|state| {
let updates = release_updates(state, &session, token).unwrap_or_default();
if state.deleted_since(&session, started) {
return false;
}
let mut current: IndexMap<String, SessionInboxInfo> =
response.into_iter().map(|item| (item.id().to_owned(), item)).collect();
for (id, update) in updates {
match update {
PendingUpdate::Removed => {
current.shift_remove(&id);
}
PendingUpdate::Delivery(delivery) => {
if let Some(item) = current.get_mut(&id) {
item.set_delivery(delivery);
}
}
PendingUpdate::Item(item) => {
current.insert(id, *item);
}
}
}
let pending: Vec<_> = current.into_values().collect();
// A positive read acknowledges admission even when its echo is delayed.
for item in &pending {
state.outbox.remove(item.id());
}
// Compactions also coalesce by session, not just by the proposed ID.
if pending.iter().any(|item| matches!(item, SessionInboxInfo::Compaction(_))) {
let local: Vec<String> = state
.pending(&session)
.iter()
.filter(|item| matches!(item, SessionInboxInfo::Compaction(_)))
.map(|item| item.id().to_owned())
.collect();
for id in local {
state.outbox.remove(&id);
}
}
// Keep optimistic rows still awaiting their echo: this read may have raced ahead
// of an admission the server does not know yet.
let inflight: Vec<_> = state
.pending(&session)
.iter()
.filter(|item| state.outbox.contains(item.id()))
.cloned()
.collect();
let mut merged = pending;
merged.extend(inflight);
// An item the read no longer lists was cancelled or delivered by an event this client missed (a
// reconnect loses events): its row goes, and a synced transcript reads again for a delivered one.
let listed: HashSet<&str> = merged.iter().map(SessionInboxInfo::id).collect();
let dropped: Vec<String> = state
.pending(&session)
.iter()
.filter(|item| !listed.contains(item.id()))
.map(|item| item.id().to_owned())
.collect();
let record = state.sessions.get_or_insert(&session);
let mut retracted = false;
if let Some(transcript) = &mut record.transcript {
for id in &dropped {
retracted |= transcript.remove(id).is_some();
}
}
record.pending = merged.clone();
let read = Read::Session(session.as_str(), SessionRead::Messages);
let reread = retracted && state.has_read(read);
if retracted {
state.touch(&session, Touched::SHAPE);
}
if reread {
state.invalidate(read);
}
state.touch(&session, Touched::PENDING);
for item in &merged {
state.materialize(item);
}
reread
});
if reread {
data.refresh(|data| data.message_sync(&session));
}
Ok(())
},
)
}
/// Optimistic prompt admission: renders the prompt at once under a client-minted ID, then
/// sends it; the durable `session.inbox.enqueued` echo upserts the same ID. A failure rolls
/// back only rows this call admitted and the server has not acknowledged.
pub fn prompt(&self, prompt: impl Into<Prompt>) -> Task<SessionInboxUser> {
let prompt = prompt.into();
let mut request = prompt.input;
let session = request.session_id.clone();
let id = request.id.clone().flatten().unwrap_or_else(|| SessionMessageID(opencode_api::id::message()));
request.id = Some(Some(id.clone()));
let fresh = self.write(|state| {
// A retry may reuse an ID that is already rendered, and possibly durable.
let fresh = !state.transcript(&session).is_some_and(|transcript| transcript.contains(id.as_str()))
&& !state.pending(&session).iter().any(|item| item.id() == id.as_str());
if fresh {
state.outbox.insert(id.0.clone());
state.admit_local(SessionInboxInfo::User(SessionInboxUser {
id: id.clone(),
session_id: session.clone(),
time: SessionInboxUserTime { created: now() },
r#type: tag::User,
delivery: request.delivery.clone().flatten().unwrap_or(SessionInboxDelivery::Steer),
payload: SessionInboxUserPayload {
text: request.text.clone(),
files: optimistic_files(request.files.as_ref()),
agents: request.agents.clone(),
skills: None,
metadata: request.metadata.clone(),
},
}));
}
fresh
});
let prepare = prompt.prepare;
self.send_admission(
&session.clone(),
prompt.gate,
move |data| async move {
if let Some(prepare) = prepare {
prepare().await?;
}
data.client().session_prompt(&request).await.map_err(Error::new)
},
move |state, result| {
if result.is_err() && fresh && state.outbox.remove(id.as_str()) {
state.retract_local(&session, id.as_str());
}
},
|_, _| {},
)
}
/// Admits a compaction (`compact`). A second gesture while one is in flight returns the same
/// request. The server may coalesce onto another ID; the response's ID then replaces the
/// proposed row.
pub fn compact(&self, session: &SessionID, model: Option<ModelRef>) -> Task<SessionInboxCompaction> {
let id = SessionMessageID(opencode_api::id::message());
let existing = self.write(|state| {
if let Some(active) = state.sessions.get(session).and_then(|session| session.compacting.as_ref()) {
return Some(active.request.clone());
}
if !state.pending(session).iter().any(|item| matches!(item, SessionInboxInfo::Compaction(_))) {
state.outbox.insert(id.0.clone());
state.admit_local(SessionInboxInfo::Compaction(SessionInboxCompaction {
id: id.clone(),
session_id: session.clone(),
time: SessionInboxUserTime { created: now() },
r#type: tag::Compaction,
delivery: SessionInboxDelivery::Steer,
payload: SessionInboxCompactionPayload::default(),
}));
}
None
});
if let Some(request) = existing {
return request;
let updates = updates.unwrap_or_default();
if self.deleted_since(session, list.started) {
return;
}
let input = SessionCompactInput { session_id: session.clone(), id: Some(id.clone()), delivery: None };
let target = session.clone();
let proposed = id.clone();
self.send_admission(
session,
None,
move |data| async move {
if let Some(model) = model {
data.client()
.session_switch_model(&SessionSwitchModelInput { session_id: input.session_id.clone(), model })
.await
.map_err(Error::new)?;
let mut current: IndexMap<String, SessionInboxInfo> =
response.into_iter().map(|item| (item.id().to_owned(), item)).collect();
for (id, update) in updates {
match update {
PendingUpdate::Removed => {
current.shift_remove(&id);
}
data.client().session_compact(&input).await.map_err(Error::new)
},
move |state, result| {
let active = state.sessions.get_mut(&target).and_then(|session| session.compacting.take());
let observed = active.map(|active| active.observed).unwrap_or_default();
match result {
Ok(item) => {
state.outbox.remove(proposed.as_str());
if item.id != proposed {
state.remove_pending(&target, proposed.as_str());
}
let shown =
state.transcript(&target).is_some_and(|transcript| transcript.contains(item.id.as_str()));
if !observed.contains(item.id.as_str()) && !shown {
state.admit_local(SessionInboxInfo::Compaction(item.clone()));
}
}
Err(_) => {
if state.outbox.remove(proposed.as_str()) {
state.remove_pending(&target, proposed.as_str());
}
PendingUpdate::Delivery(delivery) => {
if let Some(item) = current.get_mut(&id) {
item.set_delivery(delivery);
}
}
},
move |state, request| {
state.sessions.get_or_insert(session).compacting =
Some(Compacting { id, observed: HashSet::new(), request: request.clone() });
},
)
PendingUpdate::Item(item) => {
current.insert(id, *item);
}
}
}
let pending: Vec<_> = current.into_values().collect();
// A positive read acknowledges admission even when its echo is delayed.
for item in &pending {
self.outbox.remove(item.id());
}
// Compactions also coalesce by session, not just by the proposed ID.
if pending.iter().any(|item| matches!(item, SessionInboxInfo::Compaction(_))) {
let local: Vec<String> = self
.pending(session)
.iter()
.filter(|item| matches!(item, SessionInboxInfo::Compaction(_)))
.map(|item| item.id().to_owned())
.collect();
for id in local {
self.outbox.remove(&id);
}
}
// Keep optimistic rows still awaiting their echo: this read may have raced ahead
// of an admission the server does not know yet.
let inflight: Vec<_> =
self.pending(session).iter().filter(|item| self.outbox.contains(item.id())).cloned().collect();
let mut merged = pending;
merged.extend(inflight);
// An item the read no longer lists was cancelled or delivered by an event this client missed (a
// reconnect loses events): its row goes, and a synced transcript reads again for a delivered one.
let listed: HashSet<&str> = merged.iter().map(SessionInboxInfo::id).collect();
let dropped: Vec<String> = self
.pending(session)
.iter()
.filter(|item| !listed.contains(item.id()))
.map(|item| item.id().to_owned())
.collect();
let record = self.sessions.get_or_insert(session);
let mut retracted = false;
if let Some(transcript) = &mut record.transcript {
for id in &dropped {
retracted |= transcript.remove(id).is_some();
}
}
record.pending = merged.clone();
let read = Read::Session(session.as_str(), SessionRead::Messages);
let reread = retracted && self.has_read(read);
if retracted {
self.touch(session, Touched::SHAPE);
}
if reread {
self.invalidate(read);
}
self.touch(session, Touched::PENDING);
for item in &merged {
self.materialize(item);
}
if reread {
effects.push(Effect::Messages(session.clone()));
}
}
/// Sends one admission after the session's creation, the previous admission of the session,
/// and `gate` (`sendAdmission`). `settle` runs under the store lock with the result; `register`
/// runs under the same lock that spawns the request.
pub(crate) fn send_admission<T, F, Fut>(
&self,
session: &SessionID,
gate: Option<Gate>,
send: F,
settle: impl FnOnce(&mut State, &Result<T, Error>) + Send + 'static,
register: impl FnOnce(&mut State, &Task<T>),
) -> Task<T>
where
T: Clone + Send + Sync + 'static,
F: FnOnce(Data) -> Fut + Send + 'static,
Fut: Future<Output = Result<T, Error>> + Send + 'static,
{
let mut state = self.lock();
let key = state.sessions.entry(session);
let created = match &state.sessions[key].life {
Life::Creating { gate, .. } => Some(gate.clone()),
/// Renders a prompt at once under its client-minted ID, unless that ID is already rendered: a retry may reuse
/// it, and it may be durable. True when it rendered it, so a failure may roll it back.
pub(crate) fn admit_prompt(&mut self, request: &SessionPromptInput) -> bool {
let session = &request.session_id;
let Some(Some(id)) = &request.id else { return false };
let fresh = !self.transcript(session).is_some_and(|transcript| transcript.contains(id.as_str()))
&& !self.pending(session).iter().any(|item| item.id() == id.as_str());
if fresh {
self.outbox.insert(id.0.clone());
self.admit_local(SessionInboxInfo::User(SessionInboxUser {
id: id.clone(),
session_id: session.clone(),
time: SessionInboxUserTime { created: now() },
r#type: tag::User,
delivery: request.delivery.clone().flatten().unwrap_or(SessionInboxDelivery::Steer),
payload: SessionInboxUserPayload {
text: request.text.clone(),
files: optimistic_files(request.files.as_ref()),
agents: request.agents.clone(),
skills: None,
metadata: request.metadata.clone(),
},
}));
}
fresh
}
/// Renders a compaction under `id` unless one is pending. `Some` with the token of a compaction in flight, which
/// a second gesture joins.
pub(crate) fn admit_compaction(&mut self, session: &SessionID, id: &SessionMessageID) -> Option<u64> {
if let Some(active) = self.sessions.get(session).and_then(|session| session.compacting.as_ref()) {
return Some(active.token);
}
if !self.pending(session).iter().any(|item| matches!(item, SessionInboxInfo::Compaction(_))) {
self.outbox.insert(id.0.clone());
self.admit_local(SessionInboxInfo::Compaction(SessionInboxCompaction {
id: id.clone(),
session_id: session.clone(),
time: SessionInboxUserTime { created: now() },
r#type: tag::Compaction,
delivery: SessionInboxDelivery::Steer,
payload: SessionInboxCompactionPayload::default(),
}));
}
None
}
/// Begins an admission to `session` (`sendAdmission`): it waits for the session's creation and for the admission
/// before it. A compaction is recorded as in flight under the proposed ID `compaction`.
pub(crate) fn begin_admission(&mut self, session: &SessionID, compaction: Option<SessionMessageID>) -> Admission {
let key = self.sessions.entry(session);
let token = self.token();
let record = &mut self.sessions[key];
let creating = match record.life {
Life::Creating { token, .. } => Some(token),
_ => None,
};
let previous = state.sessions[key].sending.as_ref().map(|(_, task)| task.clone());
let token = state.token();
let data = self.clone();
let id = session.clone();
let request = self.spawn(async move {
let ready = futures_util::future::try_join3(
async move {
match gate {
Some(gate) => gate.await,
None => Ok(()),
}
},
async move {
match created {
Some(created) => created.await,
None => Ok(()),
}
},
async move {
// One failure does not block the next admission.
if let Some(previous) = previous {
let _ = previous.await;
}
Ok(())
},
)
.await;
let result = match ready {
Ok(_) => send(data.clone()).await,
Err(error) => Err(error),
};
data.write(|state| {
settle(state, &result);
if let Some(session) = state.sessions.get_mut(&id) {
session.sending.take_if(|(current, _)| *current == token);
}
});
result
});
let chain = request.clone().map(|result| result.map(|_| ())).boxed().shared();
state.sessions[key].sending = Some((token, chain));
register(&mut state, &request);
self.flush(&mut state);
request
let previous = record.sending.replace(token);
if let Some(id) = compaction {
record.compacting = Some(Compacting { id, observed: HashSet::new(), token });
}
Admission { token, creating, previous }
}
/// Ends the prompt admission `token`: a failure rolls back the row it rendered (`fresh`) while the server has not
/// acknowledged it.
pub(crate) fn complete_prompt(
&mut self,
session: &SessionID,
token: u64,
id: &SessionMessageID,
fresh: bool,
failed: bool,
) {
if failed && fresh && self.outbox.remove(id.as_str()) {
self.retract_local(session, id.as_str());
}
self.end_admission(session, token);
}
/// Ends the compaction admission `token` that proposed `proposed`. The server may coalesce onto another ID; the
/// response's ID then replaces the proposed row.
pub(crate) fn complete_compaction(
&mut self,
session: &SessionID,
token: u64,
proposed: &SessionMessageID,
result: Result<SessionInboxCompaction, Error>,
) {
let active = self.sessions.get_mut(session).and_then(|session| session.compacting.take());
let observed = active.map(|active| active.observed).unwrap_or_default();
match result {
Ok(item) => {
self.outbox.remove(proposed.as_str());
if item.id != *proposed {
self.remove_pending(session, proposed.as_str());
}
let shown = self.transcript(session).is_some_and(|transcript| transcript.contains(item.id.as_str()));
if !observed.contains(item.id.as_str()) && !shown {
self.admit_local(SessionInboxInfo::Compaction(item));
}
}
Err(_) => {
if self.outbox.remove(proposed.as_str()) {
self.remove_pending(session, proposed.as_str());
}
}
}
self.end_admission(session, token);
}
fn end_admission(&mut self, session: &SessionID, token: u64) {
if let Some(session) = self.sessions.get_mut(session) {
session.sending.take_if(|current| *current == token);
}
}
}
/// An admission to send: its token, and the tokens of the creation and the admission it waits for.
pub(crate) struct Admission {
pub(crate) token: u64,
pub(crate) creating: Option<u64>,
pub(crate) previous: Option<u64>,
}
/// Ends the inbox read `token`: the events that overtook it, while that read is still the current one.

View file

@ -6,9 +6,10 @@ use indexmap::IndexMap;
use opencode_api::generated::*;
use crate::changes::Touched;
use crate::core::{Effect, Jobs, Ticket};
use crate::reads::{Read, SessionRead};
use crate::sessions::SessionKey;
use crate::state::{Data, Error, Overlay, State, Task, evict_missing};
use crate::state::{Error, Overlay, State};
impl State {
/// Running jobs owned by `session` or any session below it: a synced tree's listed members, plus jobs whose
@ -75,14 +76,12 @@ impl State {
}
}
/// The synced trees, read again after `server.connected`.
pub(crate) fn job_roots(&mut self) -> Vec<SessionID> {
let mut roots = Vec::new();
/// Reads the synced trees again, after `server.connected`.
pub(crate) fn job_roots(&mut self, effects: &mut Vec<Effect>) {
for session in self.sessions.iter_mut().filter(|session| session.job_tree.is_some()) {
session.reads[SessionRead::Jobs].invalidate();
roots.push(session.id.clone());
effects.push(Effect::Jobs(session.id.clone()));
}
roots
}
/// Whether a session is `ancestor` or below it, by the parents in loaded session info.
@ -108,24 +107,32 @@ impl State {
|| matches!(job, JobInfo::Subagent(job) if self.within_tree(&job.child_session_id, ancestor))
}
fn begin_job_read(&mut self, root: &SessionID) -> u64 {
let ticket = self.token();
self.sessions.get_or_insert(root).job_read = Some(Overlay::new(ticket));
ticket
/// Begins a read of the running jobs of the tree under the session of `ticket`. Job events received during the read
/// apply over its answer.
pub(crate) fn begin_jobs(&mut self, ticket: Ticket) -> Jobs {
let read = self.token();
let record = &mut self.sessions[ticket.session()];
record.job_read = Some(Overlay::new(read));
Jobs { ticket, root: record.id.clone(), read }
}
/// Ends the job read `ticket` of `root`: its overlay, while that read is still the current one.
fn end_job_read(&mut self, root: &SessionID, ticket: u64) -> Option<Overlay<JobInfo>> {
self.sessions.get_mut(root)?.job_read.take_if(|read| read.ticket() == ticket)
}
/// Publishes the list read `ticket` started, with the events that overtook it. True when the overlay
/// overflowed: nothing is published and the caller reads again.
fn publish_jobs(&mut self, root: &SessionID, ticket: u64, list: Vec<JobInfo>) -> bool {
let Some(read) = self.end_job_read(root, ticket) else { return false };
/// Publishes the job read `read` of `root`, with the events that overtook it. An overflowed overlay publishes
/// nothing and reads again.
pub(crate) fn complete_jobs(&mut self, jobs: Jobs, result: Result<Vec<JobInfo>, Error>, effects: &mut Vec<Effect>) {
let root = jobs.root;
let read = self
.sessions
.get_mut(&root)
.and_then(|session| session.job_read.take_if(|read| read.ticket() == jobs.read));
let list = match result {
Ok(list) => list,
Err(error) => return self.evict_missing(&error),
};
let Some(read) = read else { return };
let Some(changes) = read.into_changes() else {
self.invalidate(Read::Session(root.as_str(), SessionRead::Jobs));
return true;
effects.push(Effect::Jobs(root));
return;
};
let listed: HashSet<String> = list.iter().map(|job| job.id().to_owned()).collect();
let mut next: IndexMap<String, JobInfo> = list.into_iter().map(|job| (job.id().to_owned(), job)).collect();
@ -134,18 +141,18 @@ impl State {
None => {
next.shift_remove(&id);
}
Some(info) if listed.contains(&id) || self.job_within(&info, root) => {
Some(info) if listed.contains(&id) || self.job_within(&info, &root) => {
next.insert(id, info);
}
Some(_) => {}
}
}
// Replaced below, and nothing in between reads it.
let previous = self.sessions.get_mut(root).and_then(|session| session.job_tree.take()).unwrap_or_default();
let previous = self.sessions.get_mut(&root).and_then(|session| session.job_tree.take()).unwrap_or_default();
let stale: Vec<String> = self
.jobs
.iter()
.filter(|(id, job)| !next.contains_key(*id) && (previous.contains(*id) || self.job_within(job, root)))
.filter(|(id, job)| !next.contains_key(*id) && (previous.contains(*id) || self.job_within(job, &root)))
.map(|(id, _)| id.clone())
.collect();
for id in stale {
@ -153,13 +160,12 @@ impl State {
self.log_job(&job);
}
}
self.sessions.get_or_insert(root).job_tree = Some(next.keys().cloned().collect());
self.sessions.get_or_insert(&root).job_tree = Some(next.keys().cloned().collect());
for job in next.values() {
self.log_job(job);
}
self.jobs.extend(next);
self.touch(root, Touched::JOBS);
false
self.touch(&root, Touched::JOBS);
}
}
@ -190,41 +196,3 @@ pub fn owned_jobs<'a>(
};
jobs.iter().copied().filter(|job| owned(job)).collect()
}
impl Data {
/// Reads the running jobs of the tree under `root` once per invalidation. Job events received during the read
/// apply over its answer.
pub fn job_sync(&self, root: &SessionID) -> Task<()> {
let (begin, fetched) = (root.clone(), root.clone());
self.sync_start(
self.keyed(Read::Session(root.as_str(), SessionRead::Jobs)),
move |state, _| state.begin_job_read(&begin),
move |data, ticket| async move {
let input = ExperimentalJobListInput {
session_id: Some(fetched.clone()),
status: Some(JobStatus::Running),
descendants: Some(true),
..ExperimentalJobListInput::default()
};
let list = match data.client().experimental_job_list(&input).await {
Ok(list) => list,
Err(error) => {
data.write(|state| state.end_job_read(&fetched, ticket));
return Err(evict_missing(&data, error));
}
};
if data.write(|state| state.publish_jobs(&fetched, ticket, list)) {
let again = fetched.clone();
data.refresh(move |data| data.job_sync(&again));
}
Ok(())
},
)
}
/// Cancels a running job, interrupting the work it started; a finished job stays finished.
pub async fn job_cancel(&self, id: &str) -> Result<(), Error> {
let input = ExperimentalJobCancelInput { id: id.to_owned() };
self.client().experimental_job_cancel(&input).await.map_err(Error::new)
}
}

View file

@ -2,6 +2,8 @@
pub mod changes;
pub mod connection;
mod core;
mod driver;
pub mod environment;
pub mod forms;
pub mod inbox;
@ -17,10 +19,11 @@ pub mod state;
pub mod target;
pub use changes::{Changes, Dirty, Selected, Touched};
pub use driver::{DELTAS, Data, DeltaListening, Gate, Listening, LoadMore, Prompt, Task};
pub use forms::Form;
pub use inbox::{InboxExt, PendingStatus, Prompt};
pub use inbox::{InboxExt, PendingStatus};
pub use location::{Catalog, Location, LocationData};
pub use messages::{LoadMore, MessageExt, MessageKey, Transcript};
pub use messages::{MessageExt, MessageKey, Transcript};
pub use sessions::CreateSession;
pub use shells::Shell;
pub use state::{DELTAS, Data, DeltaListening, Error, Listening, Options, SessionStatus, State, Task};
pub use state::{Error, Options, SessionStatus, State};

View file

@ -3,15 +3,13 @@
use std::sync::Arc;
use std::time::Duration;
use futures_util::future::try_join_all;
use indexmap::IndexMap;
use opencode_api::client::Client;
use opencode_api::generated::*;
use crate::connection::Follow;
use crate::reads::Read;
use crate::core::{CatalogRead, Effect, LocationRead, Ticket};
use crate::reads::{Read, ReadKey};
use crate::shells::{Shell, ShellRead};
use crate::state::{Data, Error, State, Task};
use crate::state::State;
/// Trailing window for event bursts that each ask for the same refetch (`settleMs`).
pub const SETTLE: Duration = Duration::from_millis(150);
@ -123,7 +121,7 @@ impl LocationData {
/// One catalog read, ready to publish.
#[derive(Clone)]
enum Loaded {
pub(crate) enum Loaded {
Vcs(VcsInfo),
UsageLimits(Option<UsageLimitsInfo>),
Agent(Arc<[AgentInfo]>),
@ -190,98 +188,79 @@ impl State {
}
/// `refreshLocation`: invalidates the catalog and reads it again where something read it.
pub(crate) fn refresh_catalog(&mut self, catalog: Catalog, location: &Location) -> Vec<Follow> {
let active = self.has_catalog(catalog, location);
self.invalidate(Read::Catalog(catalog, location));
follow_if(active, vec![catalog], location)
pub(crate) fn refresh_catalog(&mut self, catalog: Catalog, location: &Location, effects: &mut Vec<Effect>) {
self.refresh_together(&[catalog], vec![catalog], location, effects);
}
/// Invalidates `catalogs` and reads them again together when any of `watched` was read.
fn refresh_together(&mut self, watched: &[Catalog], catalogs: Vec<Catalog>, location: &Location) -> Vec<Follow> {
fn refresh_together(
&mut self,
watched: &[Catalog],
catalogs: Vec<Catalog>,
location: &Location,
effects: &mut Vec<Effect>,
) {
let active = watched.iter().any(|catalog| self.has_catalog(*catalog, location));
for catalog in &catalogs {
self.invalidate(Read::Catalog(*catalog, location));
}
follow_if(active, catalogs, location)
if active {
effects.push(Effect::Catalogs(catalogs, location.clone()));
}
}
/// The catalog arms of `handleEvent`: credentials, then the events that name a location.
pub(crate) fn on_catalog_event(&mut self, event: &V2Event) -> Vec<Follow> {
pub(crate) fn on_catalog_event(&mut self, event: &V2Event, effects: &mut Vec<Effect>) {
match event {
V2Event::CredentialUpdated(_) => {
let locations: Vec<Location> = self.locations.keys().cloned().collect();
return locations
.iter()
.flat_map(|location| {
let mut follow = self.refresh_catalog(Catalog::UsageLimits, location);
follow.extend(self.refresh_catalog(Catalog::Integration, location));
follow
})
.collect();
for location in &locations {
self.refresh_catalog(Catalog::UsageLimits, location, effects);
self.refresh_catalog(Catalog::Integration, location, effects);
}
return;
}
V2Event::CredentialSwitched(event) => {
let locations: Vec<Location> = self.locations.keys().cloned().collect();
return locations
.iter()
.flat_map(|location| {
let mut follow = self.refresh_catalog(Catalog::UsageLimits, location);
self.promote_credential(location, &event.data);
follow.extend(self.refresh_together(
&[Catalog::Integration, Catalog::Model, Catalog::Provider],
vec![Catalog::Model, Catalog::Provider],
location,
));
follow
})
.collect();
for location in &locations {
self.refresh_catalog(Catalog::UsageLimits, location, effects);
self.promote_credential(location, &event.data);
let watched = [Catalog::Integration, Catalog::Model, Catalog::Provider];
self.refresh_together(&watched, vec![Catalog::Model, Catalog::Provider], location, effects);
}
return;
}
_ => {}
}
let Some(location) = located(event) else { return Vec::new() };
let Some(location) = located(event) else { return };
let location = Location::from(location);
match event {
V2Event::ProviderUpdated(_) => self.refresh_catalog(Catalog::Provider, &location),
V2Event::ModelUpdated(_) => self.refresh_catalog(Catalog::Model, &location),
V2Event::AgentUpdated(_) => self.refresh_catalog(Catalog::Agent, &location),
V2Event::CommandUpdated(_) => self.refresh_catalog(Catalog::Command, &location),
V2Event::SkillUpdated(_) => self.refresh_catalog(Catalog::Skill, &location),
V2Event::ProviderUpdated(_) => self.refresh_catalog(Catalog::Provider, &location, effects),
V2Event::ModelUpdated(_) => self.refresh_catalog(Catalog::Model, &location, effects),
V2Event::AgentUpdated(_) => self.refresh_catalog(Catalog::Agent, &location, effects),
V2Event::CommandUpdated(_) => self.refresh_catalog(Catalog::Command, &location, effects),
V2Event::SkillUpdated(_) => self.refresh_catalog(Catalog::Skill, &location, effects),
// The event names only the current branch. Reload the rest: the default branch and
// provider can change with it, and a read served before the location's VCS provider
// loaded has neither.
V2Event::VcsBranchUpdated(_) => self.refresh_catalog(Catalog::Vcs, &location),
V2Event::FormCreated(event) => {
self.on_form_created(&event.data.form, &location);
Vec::new()
}
V2Event::ShellCreated(event) => {
self.on_shell_created(&event.data.info, &location);
Vec::new()
}
V2Event::ShellExited(event) => {
self.remove_shell(&event.data.id, &location);
Vec::new()
}
V2Event::ShellDeleted(event) => {
self.remove_shell(&event.data.id, &location);
Vec::new()
}
V2Event::ReferenceUpdated(_) => self.refresh_catalog(Catalog::Reference, &location),
V2Event::VcsBranchUpdated(_) => self.refresh_catalog(Catalog::Vcs, &location, effects),
V2Event::FormCreated(event) => self.on_form_created(&event.data.form, &location),
V2Event::ShellCreated(event) => self.on_shell_created(&event.data.info, &location),
V2Event::ShellExited(event) => self.remove_shell(&event.data.id, &location),
V2Event::ShellDeleted(event) => self.remove_shell(&event.data.id, &location),
V2Event::ReferenceUpdated(_) => self.refresh_catalog(Catalog::Reference, &location, effects),
V2Event::IntegrationUpdated(_) => {
let mut follow = self.refresh_catalog(Catalog::UsageLimits, &location);
let catalogs = vec![Catalog::Integration, Catalog::Model, Catalog::Provider];
follow.extend(self.refresh_together(&catalogs.clone(), catalogs, &location));
follow
self.refresh_catalog(Catalog::UsageLimits, &location, effects);
let catalogs = [Catalog::Integration, Catalog::Model, Catalog::Provider];
self.refresh_together(&catalogs, catalogs.to_vec(), &location, effects);
}
V2Event::ConfigUpdated(_) => {
let mut follow = self.refresh_catalog(Catalog::Config, &location);
self.refresh_catalog(Catalog::Config, &location, effects);
if self.has_websearch(&location) {
follow.push(Follow::Websearch(location));
effects.push(Effect::Websearch(location));
}
follow
}
V2Event::WebsearchUpdated(_) if self.has_websearch(&location) => {
vec![Follow::Websearch(location)]
}
V2Event::WebsearchUpdated(_) if self.has_websearch(&location) => effects.push(Effect::Websearch(location)),
// Authenticating an MCP integration reconnects its server, which emits
// mcp.status.changed, so the MCP list syncs here rather than off integration.updated.
// The server emits one event per MCP server as each settles, so the read waits for the
@ -289,16 +268,71 @@ impl State {
V2Event::McpStatusChanged(_) => {
let active = self.has_catalog(Catalog::McpServer, &location);
self.invalidate(Read::Catalog(Catalog::McpServer, &location));
if !active {
return Vec::new();
if active {
effects.push(Effect::Settle(Catalog::McpServer, location));
}
vec![Follow::Settle(Catalog::McpServer, location)]
}
V2Event::McpResourcesChanged(_) => self.refresh_catalog(Catalog::McpResource, &location),
_ => Vec::new(),
V2Event::McpResourcesChanged(_) => self.refresh_catalog(Catalog::McpResource, &location, effects),
_ => {}
}
}
/// Begins a read of `catalog` at the location `at`.
pub(crate) fn begin_catalog(&mut self, ticket: Ticket) -> CatalogRead {
let ReadKey::Catalog(catalog, at) = ticket.key else { unreachable!("a catalog read") };
CatalogRead { ticket, catalog, location: self.read_location(at) }
}
/// Publishes a catalog under the location the server answered with; model and provider reads also under the
/// requested one.
pub(crate) fn complete_catalog(&mut self, read: CatalogRead, at: Location, loaded: Loaded) {
if read.catalog.alias() && at != read.location {
self.publish(&read.location, loaded.clone());
}
self.publish(&at, loaded);
}
/// Begins a read of the location info of `ticket`'s location; one of the default location `adopt`s the server's
/// directory as the default.
pub(crate) fn begin_location(&mut self, ticket: Ticket, adopt: bool) -> LocationRead {
let ReadKey::Location(at) = ticket.key else { unreachable!("a location read") };
LocationRead { ticket: Some(ticket), location: self.read_location(at), adopt }
}
/// Stores location info, under the directory the server answered with.
pub(crate) fn complete_location(&mut self, adopt: bool, info: LocationPublicInfo) {
let at = Location::new(info.directory.0.clone());
if adopt {
self.default_location = at.clone();
}
self.location_mut(&at).info = Some(info);
}
/// Begins the trailing refetch of `catalog` at `location`: its key, its token, and the token of the timer it
/// replaces.
pub(crate) fn begin_settle(&mut self, catalog: Catalog, location: &Location) -> (ReadKey, u64, Option<u64>) {
let token = self.token();
let key = self.read_key(Read::Catalog(catalog, location));
let previous = self.settling.insert(key, token);
(key, token, previous)
}
/// The trailing refetch `token` of `key` fires, unless a newer one replaced it.
pub(crate) fn complete_settle(
&mut self,
key: ReadKey,
token: u64,
catalog: Catalog,
location: Location,
effects: &mut Vec<Effect>,
) {
if self.settling.get(&key) != Some(&token) {
return;
}
self.settling.remove(&key);
effects.push(Effect::Catalogs(vec![catalog], location));
}
fn has_websearch(&self, location: &Location) -> bool {
self.locations.get(location).is_some_and(|data| data.websearch.is_some())
}
@ -328,13 +362,6 @@ impl State {
}
}
fn follow_if(active: bool, catalogs: Vec<Catalog>, location: &Location) -> Vec<Follow> {
if !active {
return Vec::new();
}
vec![Follow::Catalogs(catalogs, location.clone())]
}
/// The location of the events the catalog arms handle.
fn located(event: &V2Event) -> Option<&LocationRef> {
let location = match event {
@ -358,210 +385,3 @@ fn located(event: &V2Event) -> Option<&LocationRef> {
};
location.as_ref()
}
impl Data {
fn resolve(&self, location: Option<&Location>) -> Location {
location.cloned().unwrap_or_else(|| self.read(|state| state.default_location.clone()))
}
/// Reads a catalog once per invalidation. It publishes under the location the server
/// answers with; model and provider reads also under the requested one.
pub fn catalog_sync(&self, catalog: Catalog, location: Option<&Location>) -> Task<()> {
let location = self.resolve(location);
if catalog == Catalog::Shell {
return self.shell_read(location);
}
self.sync_run(self.keyed(Read::Catalog(catalog, &location)), move |data| async move {
let (at, loaded) = load(data.client(), catalog, &location).await.map_err(Error::new)?;
data.write(|state| {
if catalog.alias() && at != location {
state.publish(&location, loaded.clone());
}
state.publish(&at, loaded);
});
Ok(())
})
}
pub fn catalog_invalidate(&self, catalog: Catalog, location: Option<&Location>) {
let location = self.resolve(location);
self.write(|state| state.invalidate(Read::Catalog(catalog, &location)));
}
/// Reads location info once per invalidation (`location.syncInfo`). A read of the default
/// location adopts the server's directory as the default.
pub fn location_sync_info(&self, location: Option<&Location>) -> Task<()> {
let default = location.is_none();
let current = self.resolve(location);
self.sync_run(self.keyed(Read::Location(&current)), move |data| async move {
let info = data
.client()
.location_get(&LocationGetInput { location: current.query() })
.await
.map_err(Error::new)?;
data.write(|state| {
let at = Location::new(info.directory.0.clone());
if default {
state.default_location = at.clone();
}
state.location_mut(&at).info = Some(info);
});
Ok(())
})
}
/// Reads location info, then every catalog a session view shows (`location.sync`).
pub fn location_sync(&self, location: Option<&Location>) -> Task<()> {
let data = self.clone();
let requested = location.cloned();
self.spawn(async move {
data.location_sync_info(requested.as_ref()).await?;
let location = data.resolve(requested.as_ref());
let mut reads: Vec<Task<()>> = [
Catalog::Vcs,
Catalog::Agent,
Catalog::Command,
Catalog::Integration,
Catalog::McpServer,
Catalog::McpResource,
Catalog::Model,
Catalog::Provider,
Catalog::Reference,
Catalog::Skill,
Catalog::Shell,
]
.into_iter()
.map(|catalog| data.catalog_sync(catalog, Some(&location)))
.collect();
reads.push(data.form_sync(crate::forms::GLOBAL, Some(&location)));
try_join_all(reads).await?;
Ok(())
})
}
/// Reads web search providers on every call; there is no cached read.
pub fn websearch_refresh(&self, location: Option<&Location>) -> Task<()> {
let location = self.resolve(location);
let data = self.clone();
self.spawn(async move {
let providers = data
.client()
.websearch_providers(&WebsearchProvidersInput { location: location.query() })
.await
.map_err(Error::new)?;
data.write(|state| {
state.location_mut(&Location::from(&providers.location)).websearch = Some(providers.data);
});
Ok(())
})
}
/// `server.connected`: reads the default location's info without the sync key, as TS does.
pub(crate) fn rehydrate_location(&self) {
let location = self.resolve(None);
self.refresh(|data| async move {
let info = data
.client()
.location_get(&LocationGetInput { location: location.query() })
.await
.map_err(Error::new)?;
let at = Location::new(info.directory.0.clone());
data.write(|state| state.location_mut(&at).info = Some(info));
Ok(())
});
}
pub(crate) fn refresh_catalogs(&self, catalogs: Vec<Catalog>, location: Location) {
self.refresh(|data| {
let reads: Vec<Task<()>> =
catalogs.into_iter().map(|catalog| data.catalog_sync(catalog, Some(&location))).collect();
async move { try_join_all(reads).await.map(|_| ()) }
});
}
/// Reads `catalog` once a burst of events that ask for it goes quiet for [`SETTLE`].
pub(crate) fn settle(&self, catalog: Catalog, location: Location) {
let data = self.clone();
let mut state = self.lock();
let token = state.token();
let key = state.read_key(Read::Catalog(catalog, &location));
// Spawned under the lock, so the timer cannot fire before its entry exists.
let handle = self.runtime().spawn(async move {
tokio::time::sleep(SETTLE).await;
let current = {
let mut state = data.lock();
let current = state.settling.get(&key).is_some_and(|(owner, _)| *owner == token);
if current {
state.settling.remove(&key);
}
current
};
if current {
data.refresh_catalogs(vec![catalog], location);
}
});
if let Some((_, previous)) = state.settling.insert(key, (token, handle.abort_handle())) {
previous.abort();
}
}
}
async fn load(
client: &Client,
catalog: Catalog,
location: &Location,
) -> Result<(Location, Loaded), opencode_api::error::Error> {
let query = location.query();
Ok(match catalog {
Catalog::Vcs => {
let response = client.vcs_get(&VcsGetInput { location: query }).await?;
((&response.location).into(), Loaded::Vcs(response.data))
}
Catalog::UsageLimits => {
let response = client.experimental_usage_limits(&ExperimentalUsageLimitsInput { location: query }).await?;
((&response.location).into(), Loaded::UsageLimits(response.data))
}
Catalog::Agent => {
let response = client.agent_list(&AgentListInput { location: query }).await?;
((&response.location).into(), Loaded::Agent(response.data.into()))
}
Catalog::Command => {
let response = client.command_list(&CommandListInput { location: query }).await?;
((&response.location).into(), Loaded::Command(response.data.into()))
}
// Config answers without a location; it publishes under the requested directory.
Catalog::Config => {
let entries = client.config_get(&ConfigGetInput { location: query }).await?;
(Location::new(location.directory.clone()), Loaded::Config(entries.into()))
}
Catalog::Integration => {
let response = client.integration_list(&IntegrationListInput { location: query }).await?;
((&response.location).into(), Loaded::Integration(response.data.into()))
}
Catalog::McpServer => {
let response = client.mcp_list(&McpListInput { location: query }).await?;
((&response.location).into(), Loaded::McpServer(response.data.into()))
}
Catalog::McpResource => {
let response = client.mcp_resource_catalog(&McpResourceCatalogInput { location: query }).await?;
((&response.location).into(), Loaded::McpResource(response.data.resources.into()))
}
Catalog::Model => {
let response = client.model_list(&ModelListInput { location: query, types: None }).await?;
((&response.location).into(), Loaded::Model(response.data.into()))
}
Catalog::Provider => {
let response = client.provider_list(&ProviderListInput { location: query }).await?;
((&response.location).into(), Loaded::Provider(response.data.into()))
}
Catalog::Reference => {
let response = client.reference_list(&ReferenceListInput { location: query }).await?;
((&response.location).into(), Loaded::Reference(response.data.into()))
}
Catalog::Skill => {
let response = client.skill_list(&SkillListInput { location: query }).await?;
((&response.location).into(), Loaded::Skill(response.data.into()))
}
Catalog::Shell => unreachable!("Data::shell_read reads shells"),
})
}

View file

@ -4,13 +4,11 @@ use opencode_api::generated::*;
use serde_json::Value;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use crate::changes::Touched;
use crate::reads::{Read, SessionRead};
use crate::core::{Delta, Effect, Head, Ticket};
use crate::sessions::SessionKey;
use crate::state::{Data, Error, MESSAGE_PAGE, OVERLAY_LIMIT, State, Task, evict_missing};
use crate::state::{Error, OVERLAY_LIMIT, State};
/// A message's key in its transcript, never given to another message of it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
@ -288,15 +286,6 @@ fn omit_message_file_data(message: &mut SessionMessageInfo) {
}
}
/// Options of [`Data::message_load_more`].
#[derive(Debug, Clone, Default)]
pub struct LoadMore {
/// Loads every older page in one publication.
pub all: bool,
/// Cancels the wait and the request (the TS `signal`).
pub cancel: Option<CancellationToken>,
}
impl State {
pub fn messages(&self, session: &SessionID) -> &[SessionMessageInfo] {
self.transcript(session).map(Transcript::items).unwrap_or_default()
@ -475,8 +464,10 @@ impl State {
}
}
}
// A replayed edit already asked for what it reads when it arrived.
let mut ignored = Vec::new();
for event in &read.edits {
self.apply_event(event);
self.apply(event, &mut ignored);
}
unknown
}
@ -484,11 +475,11 @@ impl State {
/// Edits one loaded assistant message; drops the edit when it is not loaded (`editAssistant`).
pub(crate) fn edit_assistant(
&mut self,
session: &SessionID,
message: &SessionMessageID,
session: &(impl AsRef<str> + ?Sized),
message: &(impl AsRef<str> + ?Sized),
f: impl FnOnce(&mut SessionMessageAssistant),
) {
let Some((key, position)) = self.edited(session, message) else { return };
let Some((key, position)) = self.edited(session.as_ref(), message.as_ref()) else { return };
let Some(transcript) = &mut self.sessions[key].transcript else { return };
let SessionMessageInfo::Assistant(assistant) = &mut transcript.items_mut()[position] else { return };
f(assistant);
@ -498,17 +489,17 @@ impl State {
/// Where `message` of `session` is. A run of deltas edits one message, so the last place found is checked first:
/// two ID comparisons in place of two hashes.
fn edited(&mut self, session: &SessionID, message: &SessionMessageID) -> Option<(SessionKey, usize)> {
fn edited(&mut self, session: &str, message: &str) -> Option<(SessionKey, usize)> {
if let Some((key, position)) = self.last_edited
&& let Some(record) = self.sessions.live(key)
&& record.id == *session
&& record.transcript.as_ref()?.items().get(position).is_some_and(|item| item.id() == message.as_str())
&& record.id.as_str() == session
&& record.transcript.as_ref()?.items().get(position).is_some_and(|item| item.id() == message)
{
return Some((key, position));
}
let key = self.sessions.key(session)?;
let transcript = self.sessions[key].transcript.as_ref()?;
let position = transcript.position(transcript.key(&message.0)?)?;
let position = transcript.position(transcript.key(message)?)?;
self.last_edited = Some((key, position));
Some((key, position))
}
@ -516,8 +507,8 @@ impl State {
/// Edits the latest tool part with `tool` (`editTool`).
fn edit_tool(
&mut self,
session: &SessionID,
message: &SessionMessageID,
session: &(impl AsRef<str> + ?Sized),
message: &(impl AsRef<str> + ?Sized),
tool: &str,
f: impl FnOnce(&mut SessionMessageAssistantTool),
) {
@ -535,8 +526,8 @@ impl State {
/// Edits the latest text part (`editText`).
fn edit_text(
&mut self,
session: &SessionID,
message: &SessionMessageID,
session: &(impl AsRef<str> + ?Sized),
message: &(impl AsRef<str> + ?Sized),
f: impl FnOnce(&mut SessionMessageAssistantText),
) {
self.edit_assistant(session, message, |assistant| {
@ -553,8 +544,8 @@ impl State {
/// Edits the latest reasoning part that has not completed (`editReasoning`).
fn edit_reasoning(
&mut self,
session: &SessionID,
message: &SessionMessageID,
session: &(impl AsRef<str> + ?Sized),
message: &(impl AsRef<str> + ?Sized),
f: impl FnOnce(&mut SessionMessageAssistantReasoning),
) {
self.edit_assistant(session, message, |assistant| {
@ -684,10 +675,6 @@ impl State {
});
}
pub(crate) fn on_text_delta(&mut self, data: &SessionTextDeltaData) {
self.edit_text(&data.session_id, &data.assistant_message_id, |text| text.text.push_str(&data.delta));
}
pub(crate) fn on_text_ended(&mut self, data: &SessionTextEndedData) {
self.edit_text(&data.session_id, &data.assistant_message_id, |text| text.text.clone_from(&data.text));
}
@ -712,12 +699,6 @@ impl State {
});
}
pub(crate) fn on_reasoning_delta(&mut self, data: &SessionTextDeltaData) {
self.edit_reasoning(&data.session_id, &data.assistant_message_id, |reasoning| {
reasoning.text.push_str(&data.delta)
});
}
pub(crate) fn on_reasoning_ended(&mut self, event: &SessionReasoningEnded) {
let data = &event.data;
self.edit_reasoning(&data.session_id, &data.assistant_message_id, |reasoning| {
@ -757,14 +738,6 @@ impl State {
});
}
pub(crate) fn on_tool_input_delta(&mut self, data: &SessionToolInputDeltaData) {
self.edit_tool(&data.session_id, &data.assistant_message_id, &data.id, |tool| {
if let SessionMessageAssistantToolState::Streaming(state) = &mut tool.state {
state.input.push_str(&data.delta);
}
});
}
pub(crate) fn on_tool_input_ended(&mut self, data: &SessionToolInputEndedData) {
self.edit_tool(&data.session_id, &data.assistant_message_id, &data.id, |tool| {
if let SessionMessageAssistantToolState::Streaming(state) = &mut tool.state {
@ -925,8 +898,26 @@ impl State {
self.touch(session, Touched::SHAPE);
}
pub(crate) fn on_compaction_delta(&mut self, data: &SessionCompactionDeltaData) {
let session = &data.session_id;
/// Applies a streaming delta: it appends to the part it names.
pub(crate) fn apply_delta(&mut self, delta: Delta<'_>) {
self.event_seq = None;
match delta {
Delta::Text { session, message, delta } => {
self.edit_text(session, message, |text| text.text.push_str(delta))
}
Delta::Reasoning { session, message, delta } => {
self.edit_reasoning(session, message, |reasoning| reasoning.text.push_str(delta))
}
Delta::ToolInput { session, message, tool, delta } => self.edit_tool(session, message, tool, |tool| {
if let SessionMessageAssistantToolState::Streaming(state) = &mut tool.state {
state.input.push_str(delta);
}
}),
Delta::Compaction { session, text } => self.on_compaction_delta(session, text),
}
}
fn on_compaction_delta(&mut self, session: &str, text: &str) {
let Some(transcript) = self.sessions.get_mut(session).and_then(|session| session.transcript.as_mut()) else {
return;
};
@ -936,7 +927,7 @@ impl State {
else {
return;
};
current.summary.push_str(&data.text);
current.summary.push_str(text);
let id = current.id.clone();
self.message_changed(session, &id);
}
@ -1081,257 +1072,149 @@ fn edit_session(event: &V2Event) -> Option<&SessionID> {
})
}
impl Data {
/// Reads the newest transcript page once per invalidation. Merge concurrent events by `durable.seq`; see
/// [`State::publish_head`].
pub fn message_sync(&self, session: &SessionID) -> Task<()> {
let begin = session.clone();
let session = session.clone();
let limit = self.inner.options.initial_message_limit.unwrap_or(MESSAGE_PAGE);
self.sync_start(
self.keyed(Read::Session(session.as_str(), SessionRead::Messages)),
move |state, key| {
let ticket = state.token();
state.sessions.get_or_insert(&begin).head_read = Some(HeadRead { ticket, ..HeadRead::default() });
(state.incarnation(&begin), ticket, key)
},
move |data, (incarnation, ticket, key)| async move {
let input = MessageListInput {
session_id: session.clone(),
limit: Some(limit),
order: Some(MessageListInputOrder::Desc),
..Default::default()
};
let response = match data.client().message_list(&input).await {
Ok(response) => response,
Err(error) => {
data.write(|state| HeadRead::take(state, &session, ticket));
return Err(evict_missing(&data, error));
}
};
let reread = data.write(|state| {
// Deletion and eviction drop the read; a revert ends the window under it, so it reads again.
let Some(read) = HeadRead::take(state, &session, ticket) else { return false };
let reread = state.incarnation(&session) != incarnation
|| state.publish_head(&session, read, response.data, response.cursor.next.flatten());
if reread {
state.invalidate_key(key);
}
reread
impl State {
/// Begins a read of the newest transcript page of the session of `ticket`, opening a log of what overtakes it.
pub(crate) fn begin_messages(&mut self, ticket: Ticket) -> Head {
let read = self.token();
let record = &mut self.sessions[ticket.session()];
record.head_read = Some(HeadRead { ticket: read, ..HeadRead::default() });
Head { ticket, session: record.id.clone(), read, incarnation: record.incarnation }
}
/// Publishes the newest transcript page read `read` fetched, unless deletion or eviction dropped the read. A
/// revert ends the window under it, and an order [`State::publish_head`] cannot know, read it again.
pub(crate) fn complete_messages(
&mut self,
head: Head,
result: Result<SessionMessagesResponse, Error>,
effects: &mut Vec<Effect>,
) {
let session = &head.session;
let read = HeadRead::take(self, session, head.read);
let response = match result {
Ok(response) => response,
Err(error) => return self.evict_missing(&error),
};
let Some(read) = read else { return };
let reread = self.incarnation(session) != head.incarnation
|| self.publish_head(session, read, response.data, response.cursor.next.flatten());
if reread {
self.invalidate_key(head.ticket.key);
effects.push(Effect::Messages(head.session));
}
}
/// Upserts one projected message (the `session.model.selected` read), unless a head read dropped the row as older
/// than its page or the transcript window it was asked in ended (deviation O6-held-message-read).
pub(crate) fn complete_message(&mut self, session: &SessionID, incarnation: u64, item: SessionMessageInfo) {
if self.incarnation(session) != incarnation || self.message(session, item.id()).is_none() {
return;
}
let item = self.stored(item);
self.upsert_message(session, item);
}
/// The loaded messages whose tool file data was dropped, by session, for a client that starts showing tool files.
pub(crate) fn dropped_files(&self) -> Vec<(SessionID, Vec<SessionMessageID>)> {
self.sessions
.iter()
.filter_map(|session| {
let ids: Vec<_> = session
.transcript
.as_ref()?
.items()
.iter()
.filter(|message| has_dropped_file_data(message))
.map(|message| SessionMessageID(message.id().to_owned()))
.collect();
(!ids.is_empty()).then(|| (session.id.clone(), ids))
})
.collect()
}
/// Copies back only the emptied tool files of a message read again: live events may have moved the message on
/// since the server read it.
pub(crate) fn restore_files(&mut self, session: &SessionID, message: &SessionMessageID, item: SessionMessageInfo) {
let SessionMessageInfo::Assistant(fetched) = item else { return };
if self.omit_file_data {
return;
}
self.edit_assistant(session, message, |assistant| {
for part in &mut assistant.content {
let SessionMessageAssistantContentItem::Tool(tool) = part else { continue };
if !has_dropped_file(tool) {
continue;
}
let content = fetched.content.iter().rev().find_map(|other| match other {
SessionMessageAssistantContentItem::Tool(other) if other.id == tool.id => Some(other),
_ => None,
});
if reread {
data.refresh(|data| data.message_sync(&session));
let Some(content) = content.and_then(tool_content) else { continue };
match &mut tool.state {
SessionMessageAssistantToolState::Completed(state) => state.content = content.to_vec(),
SessionMessageAssistantToolState::Error(state) => state.content = Some(content.to_vec()),
_ => {}
}
Ok(())
},
)
}
pub fn message_invalidate(&self, session: &SessionID) {
self.write(|state| state.invalidate(Read::Session(session.as_str(), SessionRead::Messages)));
}
/// Follows a setting that changes while the client runs (`omitToolFileData` as a function): it applies to messages
/// and events stored from now on. Turning it off does not bring back dropped payloads; see [`Data::restore_files`].
pub fn set_omit_tool_file_data(&self, omit: bool) {
self.lock().omit_file_data = omit;
}
/// Re-reads every loaded message whose tool file data was dropped, for a client that starts showing tool files
/// (`message.restoreFiles`). Each session's messages are re-read one at a time, so many screenshots don't fan out
/// at once.
pub fn restore_files(&self) {
let sessions: Vec<(SessionID, Vec<SessionMessageID>)> = self.read(|state| {
state
.sessions
.iter()
.filter_map(|session| {
let ids: Vec<_> = session
.transcript
.as_ref()?
.items()
.iter()
.filter(|message| has_dropped_file_data(message))
.map(|message| SessionMessageID(message.id().to_owned()))
.collect();
(!ids.is_empty()).then(|| (session.id.clone(), ids))
})
.collect()
});
for (session, ids) in sessions {
let data = self.clone();
self.runtime().spawn(async move {
for message in ids {
if let Err(error) = data.restore_message_files(&session, message).await {
data.refresh_failed(&error);
}
}
});
}
}
/// Copies back only the emptied tool files: live events may have moved the message on since the server read it.
async fn restore_message_files(&self, session: &SessionID, message: SessionMessageID) -> Result<(), Error> {
let item = self
.client()
.session_message_get(&SessionMessageGetInput { session_id: session.clone(), message_id: message.clone() })
.await
.map_err(Error::new)?;
self.write(|state| {
let SessionMessageInfo::Assistant(fetched) = item else { return };
if state.omit_file_data {
return;
}
state.edit_assistant(session, &message, |assistant| {
for part in &mut assistant.content {
let SessionMessageAssistantContentItem::Tool(tool) = part else { continue };
if !has_dropped_file(tool) {
continue;
}
let content = fetched.content.iter().rev().find_map(|other| match other {
SessionMessageAssistantContentItem::Tool(other) if other.id == tool.id => Some(other),
_ => None,
});
let Some(content) = content.and_then(tool_content) else { continue };
match &mut tool.state {
SessionMessageAssistantToolState::Completed(state) => state.content = content.to_vec(),
SessionMessageAssistantToolState::Error(state) => state.content = Some(content.to_vec()),
_ => {}
}
}
});
});
Ok(())
}
/// Loads older pages (`message.loadMore`). Joins a load in flight; with `all`, it then
/// continues to the oldest page.
pub async fn message_load_more(&self, session: &SessionID, options: LoadMore) -> Result<(), Error> {
let cancelled = || options.cancel.as_ref().is_some_and(|token| token.is_cancelled());
if cancelled() {
return Ok(());
}
loop {
let pending = self.read(|state| {
state
.sessions
.get(session)
.and_then(|session| session.message_load.as_ref())
.map(|(_, task)| task.clone())
});
let Some(pending) = pending else { break };
let published = match &options.cancel {
None => pending.await?,
Some(token) => tokio::select! {
result = pending => match result {
Ok(published) => published,
Err(_) if token.is_cancelled() => return Ok(()),
Err(error) => return Err(error),
},
_ = token.cancelled() => return Ok(()),
},
};
if (!options.all && published) || cancelled() {
return Ok(());
}
}
if cancelled() {
return Ok(());
}
match self.start_load(session, options) {
Some(task) => task.await.map(|_| ()),
None => Ok(()),
}
}
/// Starts an older-page load from the current cursor, if any, and registers it for joiners.
fn start_load(&self, session: &SessionID, options: LoadMore) -> Option<Task<bool>> {
let mut state = self.lock();
let key = state.sessions.key(session)?;
let cursor = state.sessions[key].cursor.clone()?;
let incarnation = state.sessions[key].incarnation;
/// Begins an older-page load of `session` from its cursor, if any, registering it for joiners.
pub(crate) fn begin_older(&mut self, session: &SessionID) -> Option<(u64, Page)> {
let key = self.sessions.key(session)?;
let cursor = self.sessions[key].cursor.clone()?;
let token = self.token();
let record = &mut self.sessions[key];
// No view reads `messages_loading` (the transcript keeps its own flag), so it logs no change.
state.sessions[key].loading = true;
let token = state.token();
let data = self.clone();
let id = session.clone();
let all = options.all;
let cancel = options.cancel.clone();
let task = self.spawn(async move {
let result = load_pages(&data, &id, (cursor, incarnation), all, cancel.as_ref()).await;
data.write(|state| {
let Some(session) = state.sessions.get_mut(&id) else { return };
session.loading = false;
session.message_load.take_if(|(current, _)| *current == token);
});
match result {
Err(_) if cancel.as_ref().is_some_and(CancellationToken::is_cancelled) => Ok(false),
result => result,
}
});
state.sessions[key].message_load = Some((token, task.clone()));
self.flush(&mut state);
Some(task)
record.loading = true;
record.message_load = Some(token);
Some((token, Page { cursor, incarnation: record.incarnation }))
}
/// Where a load that read from `page` goes on: `None` while `page` is current, so its pages publish; else from
/// the cursor a refresh left, `Some(None)` when none is left.
pub(crate) fn page_moved(&self, session: &SessionID, page: &Page) -> Option<Option<Page>> {
let current = self.sessions.get(session).and_then(|session| session.cursor.as_ref());
let incarnation = self.incarnation(session);
if current == Some(&page.cursor) && incarnation == page.incarnation {
return None;
}
Some(current.map(|cursor| Page { cursor: cursor.clone(), incarnation }))
}
/// Publishes older pages read from `page`, oldest last in `fetched`, while `page` is current.
pub(crate) fn complete_older(
&mut self,
session: &SessionID,
page: &Page,
fetched: Vec<SessionMessageInfo>,
next: Option<String>,
) {
if self.page_moved(session, page).is_some() {
return;
}
let fetched: Vec<_> = fetched.into_iter().map(|item| self.stored(item)).collect();
let record = self.sessions.get_or_insert(session);
let transcript = record.transcript.get_or_insert_default();
let older = fetched.into_iter().rev().filter(|item| !transcript.contains(item.id())).collect();
transcript.prepend(older);
record.cursor = next;
self.touch(session, Touched::SHAPE);
}
/// Ends the older-page load `token` of `session`.
pub(crate) fn end_older(&mut self, session: &SessionID, token: u64) {
let Some(session) = self.sessions.get_mut(session) else { return };
session.loading = false;
session.message_load.take_if(|current| *current == token);
}
}
/// Publishes older pages once. If a refresh changes the cursor, restart from the new cursor to avoid a gap. Returns
/// false on cancellation before publication.
async fn load_pages(
data: &Data,
session: &SessionID,
(mut cursor, mut incarnation): (String, u64),
all: bool,
cancel: Option<&CancellationToken>,
) -> Result<bool, Error> {
loop {
let mut fetched = Vec::new();
let mut next = Some(cursor.clone());
while let Some(page) = next {
let input = MessageListInput {
session_id: session.clone(),
limit: Some(if all { 200 } else { MESSAGE_PAGE }),
cursor: Some(page),
..Default::default()
};
let request = data.client().message_list(&input);
let response = match cancel {
None => request.await,
Some(token) => tokio::select! {
response = request => response,
_ = token.cancelled() => return Ok(false),
},
}
.map_err(Arc::new)?;
if cancel.is_some_and(CancellationToken::is_cancelled) {
return Ok(false);
}
fetched.extend(response.data);
next = response.cursor.next.flatten();
if !all {
break;
}
}
let stale = data.write(|state| {
let current = state.sessions.get(session).and_then(|session| session.cursor.as_ref());
if current != Some(&cursor) || state.incarnation(session) != incarnation {
return Some(current.cloned().map(|cursor| (cursor, state.incarnation(session))));
}
let fetched: Vec<_> = fetched.into_iter().map(|item| state.stored(item)).collect();
let record = state.sessions.get_or_insert(session);
let transcript = record.transcript.get_or_insert_default();
let older = fetched.into_iter().rev().filter(|item| !transcript.contains(item.id())).collect();
transcript.prepend(older);
record.cursor = next;
state.touch(session, Touched::SHAPE);
None
});
match stale {
None => return Ok(true),
Some(None) => return Ok(false),
Some(Some(current)) => (cursor, incarnation) = current,
}
}
/// Where an older-page load reads from: a cursor of the transcript window it began in.
#[derive(Debug, Clone)]
pub(crate) struct Page {
pub(crate) cursor: String,
pub(crate) incarnation: u64,
}
#[cfg(test)]

View file

@ -1,8 +1,8 @@
use opencode_api::generated::*;
use crate::changes::Touched;
use crate::reads::{Read, SessionRead};
use crate::state::{Data, Error, State, Task, evict_missing, is_tag};
use crate::core::{Effect, List, Ticket};
use crate::state::{Error, Overlay, State};
impl State {
/// Pending permission requests of a session; none until read or asked.
@ -58,43 +58,46 @@ impl State {
self.touch(session, Touched::PERMISSIONS);
}
}
}
impl Data {
/// Reads pending permissions once per invalidation. Requests opened or settled during the read take precedence
/// over its snapshot.
pub fn permission_sync(&self, session: &SessionID) -> Task<()> {
let (fetched, again) = (session.clone(), session.clone());
self.overlay_sync(
self.keyed(Read::Session(session.as_str(), SessionRead::Permissions)),
session.clone(),
session.clone(),
|state, session, overlay| state.sessions.get_or_insert(session).permission_read = Some(overlay),
|state, session, ticket| {
state.sessions.get_mut(session)?.permission_read.take_if(|read| read.ticket() == ticket)
},
|request| &request.id.0,
move |data| async move {
let list = data.client().permission_list(&PermissionListInput { session_id: fetched }).await;
Ok((list.map_err(|error| evict_missing(&data, error))?, ()))
},
|state, session, list, ()| {
state.sessions.get_or_insert(session).permissions = Some(list);
state.touch(session, Touched::PERMISSIONS);
},
move |data| data.permission_sync(&again),
)
/// Begins a read of the pending permission requests of the session of `ticket`, with an overlay of the requests asked
/// and replied to meanwhile.
pub(crate) fn begin_permissions(&mut self, ticket: Ticket) -> List {
let read = self.token();
let record = &mut self.sessions[ticket.session()];
record.permission_read = Some(Overlay::new(read));
List { ticket, session: record.id.clone(), read, started: self.deletion_epoch }
}
/// Replies and drops the request; an already settled request counts as replied.
pub async fn permission_reply(&self, input: PermissionReplyInput) -> Result<(), Error> {
if let Err(error) = self.client().permission_reply(&input).await {
let error = Error::new(error);
if !is_tag(&error, "PermissionNotFoundError") {
return Err(error);
/// Publishes the permission read `read` with the requests asked and replied to during it, unless a newer read or
/// a deletion of the session since it began supersedes it. An overflowed overlay reads again instead.
pub(crate) fn complete_permissions(
&mut self,
list: List,
result: Result<Vec<PermissionRequest>, Error>,
effects: &mut Vec<Effect>,
) {
let session = list.session;
let overlay = self
.sessions
.get_mut(&session)
.and_then(|record| record.permission_read.take_if(|current| current.ticket() == list.read));
let requests = match result {
Ok(requests) => requests,
Err(error) => return self.evict_missing(&error),
};
let Some(overlay) = overlay else { return };
if self.deleted_since(&session, list.started) {
return;
}
match overlay.apply(requests, |request| &request.id.0) {
Some(requests) => {
self.sessions.get_or_insert(&session).permissions = Some(requests);
self.touch(&session, Touched::PERMISSIONS);
}
None => {
self.invalidate_key(list.ticket.key);
effects.push(Effect::Permissions(session));
}
}
self.write(|state| state.remove_permission(&input.session_id, &input.request_id));
Ok(())
}
}

View file

@ -4,9 +4,9 @@ use std::collections::HashSet;
use opencode_api::generated::*;
use crate::changes::Touched;
use crate::connection::Follow;
use crate::reads::{Read, SessionRead};
use crate::state::{Data, Error, State, Task};
use crate::core::Effect;
use crate::reads::SessionRead;
use crate::state::State;
/// The project of sessions outside any repository (`Project.ID.global`).
const GLOBAL_PROJECT: &str = "global";
@ -45,7 +45,7 @@ impl State {
/// Replaces the cached set as Solid's `reconcile` does: a kept project keeps its place, a new one
/// goes last, so the order of projects that sort equal does not change between reads.
fn replace_projects(&mut self, projects: Vec<Project>) {
pub(crate) fn replace_projects(&mut self, projects: Vec<Project>) {
let ids: HashSet<&ProjectID> = projects.iter().map(|project| &project.id).collect();
self.projects.retain(|id, _| ids.contains(id));
for project in projects {
@ -57,8 +57,7 @@ impl State {
/// Moves cached sessions into the resolved repository's project. A session of an adopted
/// project matches by the project's canonical directory; a session whose adopted project is not
/// cached is read again instead.
pub(crate) fn on_worktree_resolved(&mut self, data: &WorktreeResolvedData) -> Vec<Follow> {
let mut follow = Vec::new();
pub(crate) fn on_worktree_resolved(&mut self, data: &WorktreeResolvedData, effects: &mut Vec<Effect>) {
for (key, session) in self.sessions.entries_mut() {
let Some(info) = &mut session.info else { continue };
let explicit = data.adopted.as_ref().is_some_and(|adopted| adopted.contains(&info.project_id));
@ -69,7 +68,7 @@ impl State {
};
let Some(directory) = directory else {
session.reads[SessionRead::Info].invalidate();
follow.push(Follow::Session(session.id.clone()));
effects.push(Effect::Session(session.id.clone()));
continue;
};
let Some((project, subpath)) = adopt(&info.project_id.0, directory, data) else { continue };
@ -77,7 +76,6 @@ impl State {
info.subpath = subpath.map(RelativePath);
self.log.touch(session, key, Touched::INFO);
}
follow
}
}
@ -133,17 +131,6 @@ fn is_windows_root(root: &str) -> bool {
bytes.len() >= 3 && bytes[0] == b'/' && bytes[1].is_ascii_alphabetic() && bytes[2] == b':'
}
impl Data {
/// Reads every project once per invalidation; the read replaces the cached set.
pub fn project_sync(&self) -> Task<()> {
self.sync_run(self.keyed(Read::Projects), |data| async move {
let projects = data.client().project_list(&ProjectListInput::default()).await.map_err(Error::new)?;
data.write(|state| state.replace_projects(projects));
Ok(())
})
}
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -4,7 +4,7 @@ use std::ops::{Index, IndexMut};
use crate::location::{Catalog, Location};
use crate::sessions::SessionKey;
use crate::state::{State, Task};
use crate::state::State;
/// Where a keyed read stands.
#[derive(Default)]
@ -14,8 +14,20 @@ pub(crate) enum ReadState {
Idle,
/// Read, until invalidated.
Done,
/// A load in flight; every caller joins it.
Loading { token: u64, task: Task<()>, phase: Phase },
/// A load in flight, by token; every caller joins it.
Loading { token: u64, phase: Phase },
}
/// What a caller of a keyed read does ([`State::start_read`]).
pub(crate) enum Start {
/// Nothing: it is read.
Done,
/// Joins the load in flight with this token.
Join(u64),
/// Begins the load with this token now.
Run(u64),
/// Begins the load with the first token once the stale load with the second settles.
After(u64, u64),
}
#[derive(Clone, Copy, PartialEq, Eq)]
@ -152,6 +164,11 @@ impl State {
self.read_locations.get_index(key.0 as usize)
}
/// The location of a read's key: interned locations stay.
pub(crate) fn read_location(&self, key: LocationKey) -> Location {
self.location_at(key).expect("an interned location").clone()
}
/// The key of `read`, while anything of it is kept.
fn find_key(&self, read: Read) -> Option<ReadKey> {
let location = |location| self.location_key(location);
@ -172,6 +189,45 @@ impl State {
}
}
/// Starts or joins the read `key`: what the caller does, with the token of a new load.
pub(crate) fn start_read(&mut self, key: ReadKey) -> Start {
let stale = match self.read_state_mut(key) {
Some(ReadState::Done) => return Start::Done,
Some(ReadState::Loading { token, phase: Phase::Stale }) => Some(*token),
Some(ReadState::Loading { token, .. }) => return Start::Join(*token),
_ => None,
};
let token = self.token();
match stale {
Some(stale) => Start::After(token, stale),
None => Start::Run(token),
}
}
/// Records the new load `token` of `key` as in flight, once a load that runs now has begun: a begin that fails
/// leaves the read to the next caller.
pub(crate) fn load_read(&mut self, key: ReadKey, token: u64, queued: bool) {
if let Some(read) = self.read_state_mut(key) {
*read = ReadState::Loading { token, phase: if queued { Phase::Queued } else { Phase::Running } };
}
}
/// The queued load `token` of `key` begins: the one it replaced settled.
pub(crate) fn resume_read(&mut self, key: ReadKey, token: u64) {
if let Some(ReadState::Loading { token: current, phase }) = self.read_state_mut(key)
&& *current == token
{
*phase = Phase::Running;
}
}
/// Settles the load `token` of `key`; see [`ReadState::settle`].
pub(crate) fn settle_read(&mut self, key: ReadKey, token: u64, ok: bool) {
if let Some(read) = self.read_state_mut(key) {
read.settle(token, ok);
}
}
/// The state of `key`, `None` once its session record is gone.
pub(crate) fn read_state_mut(&mut self, key: ReadKey) -> Option<&mut ReadState> {
match key {

View file

@ -1,20 +1,16 @@
use std::collections::{HashMap, HashSet};
use std::ops::{Index, IndexMut};
use futures_util::FutureExt;
use indexmap::IndexMap;
use opencode_api::generated::*;
use crate::changes::Touched;
use crate::connection::Follow;
use crate::core::{Effect, Info, Ticket};
use crate::forms::Form;
use crate::inbox::{PendingUpdate, now};
use crate::messages::{HeadRead, Transcript, from_event};
use crate::reads::{Read, ReadState, SessionRead, SessionReads};
use crate::state::{Compacting, Data, Error, Overlay, SessionStatus, State, Task, evict_missing};
/// Children per page of a family read (`CHILD_PAGE`).
const CHILD_PAGE: i64 = 200;
use crate::reads::{Read, ReadKey, ReadState, SessionRead, SessionReads};
use crate::state::{Compacting, Error, Overlay, SessionStatus, State};
/// The fewest slots at which [`Sessions::sweep`] looks for records that hold nothing.
const SWEEP_FLOOR: usize = 256;
@ -79,10 +75,10 @@ pub(crate) struct Session {
pub(crate) permission_read: Option<Overlay<PermissionRequest>>,
/// The head read in flight, with what overtook it.
pub(crate) head_read: Option<HeadRead>,
/// The older-page load in flight, by token.
pub(crate) message_load: Option<(u64, Task<bool>)>,
/// The last admission, by token: each admission waits for the previous one to settle.
pub(crate) sending: Option<(u64, Task<()>)>,
/// The token of the older-page load in flight.
pub(crate) message_load: Option<u64>,
/// The token of the last admission: each admission waits for the previous one to settle.
pub(crate) sending: Option<u64>,
pub(crate) compacting: Option<Compacting>,
/// As the root of a synced job tree: the job IDs the server listed, plus those events added for owners in the
/// tree. Loaded session info only reaches direct children, so parents alone would drop a grandchild's jobs.
@ -99,8 +95,8 @@ pub(crate) enum Life {
Known,
/// Deleted at deletion epoch `epoch`: one of the newest deletions.
Missing { epoch: u64 },
/// An optimistic creation in flight, by token; prompts to the session wait for `gate`.
Creating { token: u64, gate: Task<()>, echo: Echo },
/// An optimistic creation in flight, by token; prompts to the session wait for it.
Creating { token: u64, echo: Echo },
}
/// What the server said of a creation in flight.
@ -330,11 +326,14 @@ pub struct CreateSession {
}
/// How an execution ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
#[derive(Debug, Clone, Copy)]
pub(crate) enum Outcome<'a> {
Succeeded,
Failed,
Interrupted,
Failed(&'a SessionStructuredError),
/// `shutdown` when the server stopped it.
Interrupted {
shutdown: bool,
},
}
impl State {
@ -551,15 +550,16 @@ impl State {
self.session(id).is_some() || self.has_read(Read::Session(id.as_str(), SessionRead::Info))
}
fn revalidate(&mut self, id: &SessionID) -> Vec<Follow> {
/// Reads the session's info again where a read is worth it; also on `session.viewed`.
pub(crate) fn revalidate(&mut self, id: &SessionID, effects: &mut Vec<Effect>) {
if !self.known(id) {
return Vec::new();
return;
}
self.invalidate(Read::Session(id.as_str(), SessionRead::Info));
vec![Follow::Session(id.clone())]
effects.push(Effect::Session(id.clone()));
}
pub(crate) fn on_session_created(&mut self, data: &SessionCreatedData) -> Vec<Follow> {
pub(crate) fn on_session_created(&mut self, data: &SessionCreatedData, effects: &mut Vec<Effect>) {
let id = &data.session_id;
if let Some(key) = self.sessions.key(id) {
self.clear_deleted(key);
@ -571,7 +571,7 @@ impl State {
let reads = &mut self.sessions.get_or_insert(id).reads;
reads[SessionRead::Pending].complete();
reads[SessionRead::Messages].complete();
vec![Follow::Session(id.clone())]
effects.push(Effect::Session(id.clone()));
}
pub(crate) fn on_usage_updated(&mut self, data: &SessionUsageUpdatedData) {
@ -597,7 +597,7 @@ impl State {
self.insert_message(&data.session_id, SessionMessageInfo::AgentSwitched(row));
}
pub(crate) fn on_model_selected(&mut self, event: &SessionModelSelected) -> Vec<Follow> {
pub(crate) fn on_model_selected(&mut self, event: &SessionModelSelected, effects: &mut Vec<Effect>) {
let data = &event.data;
let previous =
data.previous.clone().or_else(|| self.session(&data.session_id).and_then(|info| info.model.clone()));
@ -606,7 +606,7 @@ impl State {
// A head read in flight places the row (models M2, O3).
let shown = self.sessions.get(&data.session_id);
if !shown.is_some_and(|session| session.transcript.is_some() || session.head_read.is_some()) {
return Vec::new();
return;
}
let id = from_event(&event.id);
let row = SessionMessageModelSelected {
@ -618,7 +618,7 @@ impl State {
time: SessionInboxUserTime { created: event.created },
};
self.insert_message(&data.session_id, SessionMessageInfo::ModelSwitched(row));
vec![Follow::Message(data.session_id.clone(), id)]
effects.push(Effect::Message(data.session_id.clone(), id));
}
pub(crate) fn on_moved(&mut self, event: &SessionMoved) {
@ -681,10 +681,10 @@ impl State {
self.revert_messages(id, &data.to);
}
pub(crate) fn on_execution_started(&mut self, id: &SessionID) -> Vec<Follow> {
pub(crate) fn on_execution_started(&mut self, id: &SessionID, effects: &mut Vec<Effect>) {
self.set_status(id, SessionStatus::Running);
// Revalidate so `time.busy` follows the projected execution start.
self.revalidate(id)
self.revalidate(id, effects);
}
pub(crate) fn on_execution_ended(
@ -693,127 +693,87 @@ impl State {
created: f64,
id: &SessionID,
outcome: Outcome,
error: Option<&SessionStructuredError>,
shutdown: bool,
) -> Vec<Follow> {
effects: &mut Vec<Effect>,
) {
self.set_status(id, SessionStatus::Idle);
self.clear_retry(id);
if shutdown {
return Vec::new();
}
let (outcome, error) = match outcome {
Outcome::Interrupted { shutdown: true } => return,
Outcome::Succeeded => (SessionInfoOutcome::Succeeded, None),
Outcome::Failed(error) => (SessionInfoOutcome::Failed, Some(error.clone())),
Outcome::Interrupted { .. } => (SessionInfoOutcome::Interrupted, None),
};
// Mirror the projected idle marker so turn boundaries match before the next read.
let row = SessionMessageIdle {
id: from_event(event_id),
r#type: tag::Idle,
outcome: match outcome {
Outcome::Succeeded => SessionInfoOutcome::Succeeded,
Outcome::Failed => SessionInfoOutcome::Failed,
Outcome::Interrupted => SessionInfoOutcome::Interrupted,
},
error: error.cloned(),
outcome,
error,
metadata: None,
time: SessionInboxUserTime { created },
};
self.insert_message(id, SessionMessageInfo::Idle(row));
let mut follow = Vec::new();
if self.has_live_tool(id) {
self.invalidate(Read::Session(id.as_str(), SessionRead::Messages));
follow.push(Follow::Messages(id.clone()));
effects.push(Effect::Messages(id.clone()));
}
// An event can overtake the first read; revalidate when that read is still active.
follow.extend(self.revalidate(id));
follow
self.revalidate(id, effects);
}
pub(crate) fn on_viewed(&mut self, id: &SessionID) -> Vec<Follow> {
self.revalidate(id)
}
}
impl Data {
/// Reads a session once per invalidation (`session.sync`); with `children`, also every direct
/// child, under its own key.
pub fn session_sync(&self, id: &SessionID, children: bool) -> Task<()> {
let read = if children { SessionRead::Family } else { SessionRead::Info };
let id = id.clone();
self.sync_start(
self.keyed(Read::Session(id.as_str(), read)),
|state, _| state.deletion_epoch,
move |data, started| async move {
let info = async {
data.client()
.session_get(&SessionGetInput { session_id: id.clone() })
.await
.map_err(|error| evict_missing(&data, error))
};
let family = async {
if !children {
return Ok(Vec::new());
}
list_children(&data, &id).await
};
let (info, family) = futures_util::future::try_join(info, family).await?;
data.write(|state| {
for session in std::iter::once(info).chain(family) {
if state.deleted_since(&session.id, started) {
continue;
}
state.remember(session);
}
});
Ok(())
},
)
/// Begins a read of the info of the session of `ticket`, and of its children for [`SessionRead::Family`].
pub(crate) fn begin_session_read(&mut self, ticket: Ticket) -> Info {
let id = self.sessions[ticket.session()].id.clone();
let children = matches!(ticket.key, ReadKey::Session(_, SessionRead::Family));
Info { ticket, id, children, started: self.deletion_epoch }
}
pub fn session_invalidate(&self, id: &SessionID) {
self.write(|state| state.invalidate(Read::Session(id.as_str(), SessionRead::Info)));
/// Stores what a session read found, but not a session deleted since it began.
pub(crate) fn complete_session_read(
&mut self,
read: Info,
result: Result<(SessionInfo, Vec<SessionInfo>), Error>,
evicts: bool,
) {
let (info, children) = match result {
Ok(found) => found,
Err(error) => {
if evicts {
self.evict_missing(&error);
}
return;
}
};
for session in std::iter::once(info).chain(children) {
if self.deleted_since(&session.id, read.started) {
continue;
}
self.remember(session);
}
}
/// Stores fetched info, as a list read does.
pub fn remember(&self, info: SessionInfo) {
self.write(|state| state.remember(info));
}
pub fn set_status(&self, id: &SessionID, status: SessionStatus) {
self.write(|state| state.set_status(id, status));
}
/// Forgets a session as deleted.
pub fn forget(&self, id: &SessionID) {
self.write(|state| state.mark_deleted(id));
}
/// Clears heavy cached data of the family of `id`.
pub fn evict(&self, id: &SessionID) {
self.write(|state| state.evict(id));
}
/// Optimistic creation: admits a local record under a client-minted ID so a session view can
/// open at once, then creates the session. Prompts to it wait for the request; a failure
/// removes the record unless the server acknowledged it.
pub fn session_create(&self, input: CreateSession) -> (SessionID, Task<SessionInfo>) {
/// Admits an optimistic session under `input.id` or a fresh ID, so a session view can open at once, and says how
/// to create it. Admissions to it wait for the creation.
pub(crate) fn begin_creation(&mut self, input: CreateSession) -> Creation {
let id = input.id.clone().unwrap_or_else(|| SessionID(opencode_api::id::session()));
let mut state = self.lock();
let location = input.location.clone().unwrap_or_else(|| LocationPublicRef {
directory: AbsolutePath(state.default_location().directory.clone()),
directory: AbsolutePath(self.default_location().directory.clone()),
});
let fresh = state.session(&id).is_none();
let key = state.sessions.entry(&id);
state.clear_deleted(key);
let fresh = self.session(&id).is_none();
let key = self.sessions.entry(&id);
self.clear_deleted(key);
if fresh {
let created = now();
let project_id = input
.project_id
.clone()
.or_else(|| {
state
.location(Some(&(&location).into()))
self.location(Some(&(&location).into()))
.and_then(|data| data.info.as_ref())
.map(|info| info.project.id.clone())
})
.unwrap_or_default();
state.remember(SessionInfo {
self.remember(SessionInfo {
id: id.clone(),
project_id,
agent: input.agent.clone(),
@ -828,10 +788,10 @@ impl Data {
// A mounted optimistic session must not read its empty collections before creation
// settles; the `session.created` echo reads its info again.
for read in [SessionRead::Family, SessionRead::Pending, SessionRead::Messages] {
state.sessions[key].reads[read].complete();
self.sessions[key].reads[read].complete();
}
}
let request = SessionCreateInput {
let input = SessionCreateInput {
id: Some(Some(id.clone())),
title: input.title.map(Some),
agent: input.agent.map(Some),
@ -839,103 +799,110 @@ impl Data {
location: Some(Some(location)),
..Default::default()
};
let token = state.token();
let data = self.clone();
let session = id.clone();
let task = self.spawn(async move {
let result = data.client().session_create(&request).await.map_err(Error::new);
data.write(|state| {
// A failure of a call that admitted nothing leaves another call's creation unacknowledged.
let acknowledged = (result.is_ok() || fresh)
&& state.sessions.get_mut(&session).is_some_and(|record| record.life.acknowledge());
match &result {
Ok(info) => state.remember(info.clone()),
// Roll back only a record this call admitted and neither the echo nor the
// response acknowledged: anything else is server state.
Err(_) => {
if acknowledged {
state.remove_session(&session);
}
}
}
if state.sessions.get_mut(&session).is_some_and(|record| record.life.end_creation(token)) {
// `is_creating` is part of the session's view.
state.touch(&session, Touched::INFO);
}
});
result
});
let token = self.token();
if fresh {
let gate = task.clone().map(|result| result.map(|_| ())).boxed().shared();
state.sessions[key].life = Life::Creating { token, gate, echo: Echo::Awaited };
self.sessions[key].life = Life::Creating { token, echo: Echo::Awaited };
}
self.flush(&mut state);
(id, task)
Creation { id, token, fresh, input }
}
}
/// Every direct child, newest first, through every page (`listChildren`).
async fn list_children(data: &Data, parent: &SessionID) -> Result<Vec<SessionInfo>, Error> {
let mut input = SessionListInput {
parent_id: Some(Some(parent.clone())),
order: Some(SessionListInputOrder::Desc),
limit: Some(CHILD_PAGE),
..Default::default()
};
let mut children = Vec::new();
loop {
let page = data.client().session_list(&input).await.map_err(Error::new)?;
let full = page.data.len() as i64 >= CHILD_PAGE;
children.extend(page.data);
let Some(next) = page.cursor.next.flatten().filter(|_| full) else { return Ok(children) };
// Later pages carry only the cursor and the size, as in TS.
input = SessionListInput { cursor: Some(next), limit: Some(CHILD_PAGE), ..Default::default() };
}
}
impl Data {
/// Refetches one projected message and upserts it (the `session.model.selected` read). A response that
/// arrives after the transcript was deleted, evicted or reverted publishes nothing (deviation
/// O6-held-message-read).
pub(crate) fn fetch_message(&self, session: SessionID, message: SessionMessageID) {
let incarnation = self.read(|state| state.incarnation(&session));
self.refresh(move |data| async move {
let item = data
.client()
.session_message_get(&SessionMessageGetInput { session_id: session.clone(), message_id: message })
.await
.map_err(Error::new)?;
data.write(|state| {
// A head read dropped the row as older than its page, or the window ended.
if state.incarnation(&session) != incarnation || state.message(&session, item.id()).is_none() {
return;
/// Ends the creation `token` of `id`.
pub(crate) fn complete_creation(
&mut self,
id: &SessionID,
token: u64,
fresh: bool,
result: Result<SessionInfo, Error>,
) {
// A failure of a call that admitted nothing leaves another call's creation unacknowledged.
let acknowledged =
(result.is_ok() || fresh) && self.sessions.get_mut(id).is_some_and(|record| record.life.acknowledge());
match result {
Ok(info) => self.remember(info),
// Roll back only a record this call admitted and neither the echo nor the
// response acknowledged: anything else is server state.
Err(_) => {
if acknowledged {
self.remove_session(id);
}
let item = state.stored(item);
state.upsert_message(&session, item);
});
Ok(())
});
}
}
if self.sessions.get_mut(id).is_some_and(|record| record.life.end_creation(token)) {
// `is_creating` is part of the session's view.
self.touch(id, Touched::INFO);
}
}
/// Applies a live title after the session's reads, so a racing read cannot overwrite it.
pub(crate) fn renamed(&self, session: SessionID, title: String) {
self.refresh(|data| async move {
let family = data.read(|state| {
matches!(
state.read_state(Read::Session(session.as_str(), SessionRead::Family)),
Some(ReadState::Loading { .. })
)
});
let own = data.session_sync(&session, false);
if family {
futures_util::future::try_join(own, data.session_sync(&session, true)).await?;
} else {
own.await?;
}
data.write(|state| state.edit_info(&session, |info| info.title = Some(title)));
Ok(())
});
/// Applies a live title.
pub(crate) fn rename(&mut self, id: &SessionID, title: String) {
self.edit_info(id, |info| info.title = Some(title));
}
/// True while the session's family read is in flight: a live title waits for it too.
pub(crate) fn family_loading(&self, id: &SessionID) -> bool {
matches!(self.read_state(Read::Session(id.as_str(), SessionRead::Family)), Some(ReadState::Loading { .. }))
}
/// Reconciles session status with the `session.active` snapshot of connection `token`. Status events received
/// during the read supersede the snapshot; a snapshot of an older connection is ignored.
pub(crate) fn complete_active(
&mut self,
token: u64,
result: Result<SessionActiveOutput, Error>,
effects: &mut Vec<Effect>,
) {
let active = match result {
Ok(active) => active,
Err(_) => {
if self.active_updates.as_ref().is_some_and(|(current, _)| *current == token) {
self.active_updates = None;
}
return;
}
};
let Some((current, updates)) = self.active_updates.take() else { return };
if current != token {
self.active_updates = Some((current, updates));
return;
}
let mut snapshot: HashMap<SessionID, SessionStatus> =
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 self.sessions.entries_mut() {
let status = snapshot.remove(&session.id);
if session.status != status {
session.status = status;
self.log.touch(session, key, Touched::STATUS);
}
}
// What is left names sessions the store holds nothing of.
for (id, status) in snapshot {
let key = self.sessions.entry(&id);
self.sessions[key].status = Some(status);
self.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.
let unknown = self
.sessions
.iter()
.filter(|session| session.status == Some(SessionStatus::Running) && session.info.is_none())
.map(|session| Effect::Session(session.id.clone()));
effects.extend(unknown);
}
}
/// An optimistic creation to send: the ID it admitted, under `token` when `fresh`.
pub(crate) struct Creation {
pub(crate) id: SessionID,
pub(crate) token: u64,
pub(crate) fresh: bool,
pub(crate) input: SessionCreateInput,
}
#[cfg(test)]

View file

@ -3,9 +3,10 @@
use indexmap::IndexMap;
use opencode_api::generated::*;
use crate::core::{Effect, Shells, Ticket};
use crate::location::{Catalog, Location};
use crate::reads::Read;
use crate::state::{Data, Error, Overlay, State, Task};
use crate::reads::{Read, ReadKey};
use crate::state::{Overlay, State};
/// A running shell and the location that reported it.
#[derive(Debug, Clone, PartialEq)]
@ -71,19 +72,25 @@ impl State {
}
}
/// Starts a shell read of `location` with an empty overlay; the returned ticket alone may publish it.
fn begin_shell_read(&mut self, location: &Location) -> u64 {
let ticket = self.token();
self.locations.entry(location.clone()).or_default().shell_read = Some(Overlay::new(ticket));
ticket
/// Begins a shell read of `location` with an empty overlay; its ticket alone may publish it. Shell creation and
/// exit events received during the read take precedence over its answer.
pub(crate) fn begin_shells(&mut self, ticket: Ticket) -> Shells {
let ReadKey::Catalog(Catalog::Shell, at) = ticket.key else { unreachable!("a shell read") };
let location = self.read_location(at);
let read = self.token();
self.locations.entry(location.clone()).or_default().shell_read = Some(Overlay::new(read));
Shells { ticket, location, read }
}
/// Publishes the list read `ticket` started, with its overlay applied. True when the overlay overflowed: the
/// list is published alone and the read is invalidated, so the caller reads again.
fn publish_shells(&mut self, location: &Location, ticket: u64, response: ShellListOutput) -> bool {
let read =
self.locations.get_mut(location).and_then(|data| data.shell_read.take_if(|read| read.ticket() == ticket));
let Some(read) = read else { return false };
/// Publishes the list read `read` began, with its overlay applied. An overflowed overlay publishes the list alone
/// and invalidates the read, which reads again.
pub(crate) fn complete_shells(&mut self, shells: Shells, response: ShellListOutput, effects: &mut Vec<Effect>) {
let location = shells.location;
let read = self
.locations
.get_mut(&location)
.and_then(|data| data.shell_read.take_if(|read| read.ticket() == shells.read));
let Some(read) = read else { return };
let at = Location::from(&response.location);
let mut shells: IndexMap<ShellID, Shell> = response
.data
@ -106,10 +113,12 @@ impl State {
}
}
if overflowed {
self.invalidate(Read::Catalog(Catalog::Shell, location));
self.invalidate(Read::Catalog(Catalog::Shell, &location));
}
self.location_mut(&at).shell = Some(shells);
overflowed
if overflowed {
effects.push(Effect::Catalogs(vec![Catalog::Shell], location));
}
}
}
@ -117,33 +126,6 @@ impl State {
/// another read.
pub(crate) type ShellRead = Overlay<Shell>;
impl Data {
/// Reads a location's running shells once per invalidation.
pub fn shell_sync(&self, location: Option<&Location>) -> Task<()> {
self.catalog_sync(Catalog::Shell, location)
}
/// Shell creation and exit events received during a list read take precedence over the snapshot.
pub(crate) fn shell_read(&self, location: Location) -> Task<()> {
let begin = location.clone();
self.sync_start(
self.keyed(Read::Catalog(Catalog::Shell, &location)),
move |state, _| state.begin_shell_read(&begin),
move |data, ticket| async move {
let response = data
.client()
.shell_list(&ShellListInput { location: location.query() })
.await
.map_err(Error::new)?;
if data.write(|state| state.publish_shells(&location, ticket, response)) {
data.refresh_catalogs(vec![Catalog::Shell], location);
}
Ok(())
},
)
}
}
/// The list read's shell type has the same fields as the event's.
pub(crate) fn from_list(info: ShellInfo) -> ShellInfo {
ShellInfo {

View file

@ -1,41 +1,21 @@
//! [`Data`] shares a locked [`State`] across handles. The lock never crosses an `.await`; requests run on the runtime
//! captured at construction, including those issued on the UI thread.
//! The store contents as plain data. [`crate::Data`] owns them behind a lock and runs their requests.
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::hash::Hash;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::sync::Arc;
use futures_util::FutureExt;
use futures_util::future::{BoxFuture, Shared};
use indexmap::{IndexMap, IndexSet};
use opencode_api::client::Client;
use opencode_api::generated::{JobInfo, Project, ProjectID, SessionID, SessionInboxCompaction, SessionMessageID};
use opencode_api::kinds::EventKinds;
use opencode_util::lock;
use tokio::runtime::Handle;
use tokio::sync::{broadcast, watch};
use tokio::task::AbortHandle;
use opencode_api::generated::{JobInfo, Project, ProjectID, SessionID, SessionMessageID};
use crate::changes::{Log, Touched};
use crate::forms::Form;
use crate::location::{Location, LocationData};
use crate::reads::{Phase, Read, ReadKey, ReadState};
use crate::reads::{ReadKey, ReadState};
use crate::sessions::{SessionKey, Sessions};
/// How many [`Data::signals`] events a slow receiver may fall behind. One batch may hold hundreds of a listened type
/// (a burst of `filesystem.changed`).
const SIGNALS: usize = 1024;
/// The most streaming deltas kept for the [`DeltaListening`]s; past that, the oldest go.
pub const DELTAS: usize = 4096;
/// A store error. Shared, because one keyed read answers every caller.
pub type Error = Arc<opencode_api::error::Error>;
/// A spawned request any number of callers can await.
pub type Task<T> = Shared<BoxFuture<'static, Result<T, Error>>>;
/// Raw messages of the first transcript read (`messagePageLimit`).
pub(crate) const MESSAGE_PAGE: i64 = 20;
@ -49,7 +29,7 @@ pub struct Options {
/// Raw messages of the first transcript read; later pages keep their size.
pub initial_message_limit: Option<i64>,
/// Drops inline `data:` payloads of tool-result files before they enter the store. Change it later with
/// [`Data::set_omit_tool_file_data`].
/// [`crate::Data::set_omit_tool_file_data`].
pub omit_tool_file_data: bool,
}
@ -60,7 +40,7 @@ pub enum SessionStatus {
Running,
}
/// The store contents and its bookkeeping. Read it through [`Data::read`].
/// The store contents and its bookkeeping. Read it through [`crate::Data::read`].
#[derive(Default)]
pub struct State {
pub(crate) sessions: Sessions,
@ -93,8 +73,8 @@ pub struct State {
/// The sessions whose transcript window ended last (deleted, evicted or reverted), oldest first: the newest
/// [`DELETED_LIMIT`], the only ones with an incarnation.
ended: IndexSet<SessionKey>,
/// Trailing refetch timers by the read they refetch, with the token of the newest.
pub(crate) settling: HashMap<ReadKey, (u64, AbortHandle)>,
/// The token of the newest trailing refetch timer, by the read it refetches.
pub(crate) settling: HashMap<ReadKey, u64>,
/// The form read in flight per owner (and location, for [`crate::forms::GLOBAL`]), with the
/// forms created and settled that overtook it.
pub(crate) form_reads: HashMap<crate::forms::FormRead, Overlay<Form>>,
@ -164,8 +144,6 @@ impl<V> Overlay<V> {
}
}
type ErrorHandler = Arc<dyn Fn(&Error) + Send + Sync>;
/// Status events by session; `None` removes the session.
pub(crate) type StatusUpdates = HashMap<SessionID, Option<SessionStatus>>;
@ -174,10 +152,19 @@ pub(crate) struct Compacting {
pub(crate) id: SessionMessageID,
/// Inbox IDs consumed or echoed while the request runs, so its response cannot resurrect them.
pub(crate) observed: HashSet<String>,
pub(crate) request: Task<SessionInboxCompaction>,
/// The token of the request.
pub(crate) token: u64,
}
impl State {
pub(crate) fn new(options: &Options) -> Self {
Self {
omit_file_data: options.omit_tool_file_data,
default_location: Location::new(options.directory.clone()),
..Self::default()
}
}
pub(crate) fn token(&mut self) -> u64 {
self.next_token += 1;
self.next_token
@ -207,8 +194,15 @@ impl State {
self.remove_session(id);
}
/// Marks the session of a `SessionNotFoundError` deleted (`evictMissing`).
pub(crate) fn evict_missing(&mut self, error: &Error) {
if let Some(id) = session_not_found(error) {
self.mark_deleted(&id);
}
}
/// True when `id` was deleted after the epoch a read started at.
pub(crate) fn deleted_since(&self, id: &SessionID, started: u64) -> bool {
pub(crate) fn deleted_since(&self, id: &(impl AsRef<str> + ?Sized), started: u64) -> bool {
self.sessions.get(id).and_then(|session| session.life.deleted()).unwrap_or(0) > started
}
@ -233,525 +227,6 @@ impl State {
}
}
/// The store handle. Cheap to clone.
#[derive(Clone)]
pub struct Data {
pub(crate) inner: Arc<Inner>,
}
pub(crate) struct Inner {
pub(crate) client: Client,
pub(crate) options: Options,
runtime: Handle,
state: Mutex<State>,
revision: watch::Sender<u64>,
/// The events views act on themselves, sent after their batch is applied.
pub(crate) signals: broadcast::Sender<Arc<opencode_api::generated::V2Event>>,
/// How many [`Listening`]s want each event kind on [`Data::signals`], by `kind as usize`.
pub(crate) listened: [AtomicUsize; opencode_api::generated::EventKind::COUNT],
/// How many [`Listening`]s want each name of the kinds a listener names (`EventKind::named`).
pub(crate) named: Mutex<HashMap<String, usize>>,
/// The streaming deltas kept for the [`DeltaListening`]s.
pub(crate) deltas: Mutex<Deltas>,
/// How many [`DeltaListening`]s live, as `deltas` counts them: a hint the hot path reads without the lock.
pub(crate) delta_listeners: AtomicUsize,
/// False while the event connection is not connected; follow-up reads are skipped then.
pub(crate) online: AtomicBool,
disposed: AtomicBool,
on_error: Mutex<Option<ErrorHandler>>,
}
impl Data {
/// A store on `client`. Must be called inside a tokio runtime, which runs its requests.
pub fn new(client: Client, options: Options) -> Self {
Self::with_runtime(client, options, Handle::current())
}
pub fn with_runtime(client: Client, options: Options, runtime: Handle) -> Self {
let state = State {
omit_file_data: options.omit_tool_file_data,
default_location: Location::new(options.directory.clone()),
..State::default()
};
Self {
inner: Arc::new(Inner {
client,
options,
runtime,
state: Mutex::new(state),
revision: watch::channel(0).0,
signals: broadcast::channel(SIGNALS).0,
listened: std::array::from_fn(|_| AtomicUsize::new(0)),
named: Mutex::default(),
deltas: Mutex::default(),
delta_listeners: AtomicUsize::new(0),
online: AtomicBool::new(true),
disposed: AtomicBool::new(false),
on_error: Mutex::new(None),
}),
}
}
pub fn client(&self) -> &Client {
&self.inner.client
}
/// Receives failed event-driven reads (`onError`). Without it they are logged.
pub fn on_error(&self, handler: impl Fn(&Error) + Send + Sync + 'static) {
*lock(&self.inner.on_error) = Some(Arc::new(handler));
}
/// Stops follow-up reads, as disposing the TS owner does.
pub fn dispose(&self) {
self.inner.disposed.store(true, Ordering::SeqCst);
for (_, (_, timer)) in self.lock().settling.drain() {
timer.abort();
}
}
/// Reads the state. Keep `f` short: it holds the store lock. A `read` inside `f` on the same thread reuses the
/// outer guard, so code that runs under a read (a keymap condition during a row render) may read again.
#[allow(unsafe_code)]
pub fn read<R>(&self, f: impl FnOnce(&State) -> R) -> R {
let key = self.key();
if let Some(state) = held(key) {
assert!(!state.is_null(), "store read inside a store write on this thread");
// SAFETY: the outer `read` on this thread holds the guard until this call returns, and lends only `&State`.
return f(unsafe { &*state });
}
let guard = lock(&self.inner.state);
let _held = Held::enter(key, &*guard);
f(&guard)
}
/// The revision of the last flush.
pub fn revision(&self) -> u64 {
*self.inner.revision.borrow()
}
/// Wakes on every flush with its revision.
pub fn subscribe(&self) -> watch::Receiver<u64> {
self.inner.revision.subscribe()
}
/// Receives the events of each type a [`Listening`] wants, for the views that handle one themselves (`tui.*`,
/// `session.deleted`) and the plugins' `on_event`, after the store applied their batch. Streaming deltas are never
/// sent ([`DeltaListening::take`] has them). A receiver that falls behind skips the oldest.
pub fn signals(&self) -> broadcast::Receiver<Arc<opencode_api::generated::V2Event>> {
self.inner.signals.subscribe()
}
/// Sends the events of each type in `kinds` on [`Data::signals`] until the returned guard drops.
pub fn listen(&self, kinds: impl Into<EventKinds>) -> Listening {
let kinds = kinds.into();
let mut named = lock(&self.inner.named);
for name in kinds.names() {
*named.entry(name.clone()).or_default() += 1;
}
for index in kinds.indices() {
self.inner.listened[index].fetch_add(1, Ordering::SeqCst);
}
Listening { inner: Arc::downgrade(&self.inner), kinds }
}
/// Keeps the streaming deltas (`session.*.delta`), which [`Data::signals`] never sends, for
/// [`DeltaListening::take`] from now until the returned guard drops: at most [`DELTAS`] it has not taken, the
/// oldest dropped past that. A batch that kept one wakes [`Data::subscribe`] also when it changed nothing.
pub fn listen_deltas(&self) -> DeltaListening {
let mut deltas = lock(&self.inner.deltas);
let id = deltas.ids;
deltas.ids += 1;
let next = deltas.next;
deltas.cursors.insert(id, next);
self.inner.delta_listeners.store(deltas.cursors.len(), Ordering::SeqCst);
DeltaListening { inner: Arc::downgrade(&self.inner), id }
}
/// Keeps `events`, one batch, for the [`DeltaListening`]s, all under one lock so a take gets all or none of
/// them; whether it kept any.
pub(crate) fn keep_deltas<'a>(&self, events: impl Iterator<Item = &'a opencode_api::generated::V2Event>) -> bool {
let mut events = events.peekable();
if self.inner.delta_listeners.load(Ordering::SeqCst) == 0 || events.peek().is_none() {
return false;
}
let mut deltas = lock(&self.inner.deltas);
// Checked again under the lock: the last listener may have gone since.
if deltas.cursors.is_empty() {
return false;
}
for event in events {
if deltas.kept.len() == DELTAS {
deltas.kept.pop_front();
}
deltas.kept.push_back(event.clone());
deltas.next += 1;
}
true
}
/// Wakes [`Data::subscribe`] with the revision it has, for deltas kept without a change.
pub(crate) fn wake_deltas(&self) {
self.inner.revision.send_modify(|_| {});
}
/// Mutates the state and flushes its changes unless a batch is open.
pub(crate) fn write<R>(&self, f: impl FnOnce(&mut State) -> R) -> R {
let mut state = self.lock();
let result = f(&mut state);
self.flush(&mut state);
result
}
/// Locks the state for a write. Locking it while this thread reads or writes it panics instead of deadlocking.
pub(crate) fn lock(&self) -> Locked<'_> {
let key = self.key();
assert!(held(key).is_none(), "store write inside a store read or write on this thread");
let guard = lock(&self.inner.state);
Locked { _held: Held::enter(key, std::ptr::null()), guard }
}
fn key(&self) -> usize {
Arc::as_ptr(&self.inner) as usize
}
pub(crate) fn flush(&self, state: &mut State) {
if state.batch > 0 {
return;
}
if let Some(revision) = state.log.flush() {
self.inner.revision.send_replace(revision);
}
}
pub(crate) fn runtime(&self) -> &Handle {
&self.inner.runtime
}
pub(crate) fn live(&self) -> bool {
!self.inner.disposed.load(Ordering::SeqCst) && self.inner.online.load(Ordering::SeqCst)
}
/// Spawns `future` at once and shares its result.
pub(crate) fn spawn<T: Clone + Send + Sync + 'static>(
&self,
future: impl Future<Output = Result<T, Error>> + Send + 'static,
) -> Task<T> {
let handle = self.inner.runtime.spawn(future);
async move {
handle.await.unwrap_or_else(|error| {
Err(Arc::new(opencode_api::error::Error::Transport(format!("store task failed: {error}"))))
})
}
.boxed()
.shared()
}
/// Runs a follow-up read unless offline or disposed (`refresh`). A `SessionNotFoundError`
/// marks the session deleted; other failures go to [`Data::on_error`].
///
/// Store reads start when they are built, so `load` builds the read only after the check, as
/// the TS `refresh` calls its `load` only when connected.
pub(crate) fn refresh<F>(&self, load: impl FnOnce(Data) -> F)
where
F: Future<Output = Result<(), Error>> + Send + 'static,
{
if !self.live() {
return;
}
let future = load(self.clone());
let data = self.clone();
self.inner.runtime.spawn(async move {
if let Err(error) = future.await {
data.refresh_failed(&error);
}
});
}
/// Handles a failed follow-up read (`refreshFailed`).
pub(crate) fn refresh_failed(&self, error: &Error) {
if !self.live() {
return;
}
if let Some(id) = session_not_found(error) {
self.write(|state| state.mark_deleted(&id));
return;
}
if is_tag(error, "MessageNotFoundError") {
return;
}
let handler = lock(&self.inner.on_error).clone();
match handler {
Some(handler) => handler(error),
None => log::error!("failed to refresh client data: {error}"),
}
}
/// Runs `load` once per key until invalidated (`sync.run`).
pub(crate) fn sync_run<F>(&self, read: Keyed, load: impl FnOnce(Data) -> F + Send + 'static) -> Task<()>
where
F: Future<Output = Result<(), Error>> + Send + 'static,
{
self.sync_start(read, |_, _| (), move |data, ()| load(data))
}
/// Locks the state and finds the key of `read`, for [`Data::sync_start`].
pub(crate) fn keyed(&self, read: Read) -> Keyed<'_> {
let mut state = self.lock();
let key = state.read_key(read);
(state, key)
}
/// [`Data::sync_run`] with a synchronous start, as the part of a TS load before its first
/// `await`. `begin` runs under the store lock before this returns, or, for a reload that waits
/// for the load it replaces, under the lock right after that wait. So no event after the call
/// can miss what it registers (an overtake log, the deletion epoch). `load` builds the read
/// from what `begin` returned, outside the lock.
pub(crate) fn sync_start<R, F>(
&self,
(mut state, key): Keyed,
begin: impl FnOnce(&mut State, ReadKey) -> R + Send + 'static,
load: impl FnOnce(Data, R) -> F + Send + 'static,
) -> Task<()>
where
R: Send + 'static,
F: Future<Output = Result<(), Error>> + Send + 'static,
{
let wait = match state.read_state_mut(key) {
Some(ReadState::Done) => return futures_util::future::ready(Ok(())).boxed().shared(),
Some(ReadState::Loading { task, phase: Phase::Stale, .. }) => Some(task.clone()),
Some(ReadState::Loading { task, .. }) => return task.clone(),
_ => None,
};
let token = state.token();
let phase = if wait.is_some() { Phase::Queued } else { Phase::Running };
let start = match wait {
None => Start::Begun(begin(&mut state, key)),
Some(wait) => Start::After(wait, begin),
};
let data = self.clone();
// Spawned under the lock, so its settlement cannot run before its state exists.
let task = self.spawn(async move {
let begun = match start {
Start::Begun(begun) => begun,
Start::After(wait, begin) => {
let _ = wait.await;
data.write(|state| {
if let Some(ReadState::Loading { token: current, phase, .. }) = state.read_state_mut(key)
&& *current == token
{
*phase = Phase::Running;
}
begin(state, key)
})
}
};
let result = load(data.clone(), begun).await;
data.write(|state| {
if let Some(read) = state.read_state_mut(key) {
read.settle(token, result.is_ok());
}
});
result
});
if let Some(state) = state.read_state_mut(key) {
*state = ReadState::Loading { token, task: task.clone(), phase };
}
task
}
/// Fetches a list and applies its overlay before publishing. Discard superseded reads and reads for deleted
/// sessions. An overflow invalidates the read and schedules another.
#[allow(clippy::too_many_arguments)]
pub(crate) fn overlay_sync<K, V, T, F>(
&self,
sync: Keyed,
session: SessionID,
read: K,
open: fn(&mut State, &K, Overlay<V>),
close: fn(&mut State, &K, u64) -> Option<Overlay<V>>,
id: fn(&V) -> &str,
fetch: impl FnOnce(Data) -> F + Send + 'static,
publish: impl FnOnce(&mut State, &K, Vec<V>, T) + Send + 'static,
again: impl FnOnce(Data) -> Task<()> + Send + 'static,
) -> Task<()>
where
K: Clone + Send + 'static,
V: Send + 'static,
T: Send + 'static,
F: Future<Output = Result<(Vec<V>, T), Error>> + Send + 'static,
{
let begin = read.clone();
self.sync_start(
sync,
move |state, key| {
let ticket = state.token();
open(state, &begin, Overlay::new(ticket));
(state.deletion_epoch, ticket, key)
},
move |data, (started, ticket, key)| async move {
let (list, extra) = match fetch(data.clone()).await {
Ok(fetched) => fetched,
Err(error) => {
data.write(|state| close(state, &read, ticket));
return Err(error);
}
};
let reread = data.write(|state| {
let Some(overlay) = close(state, &read, ticket) else { return false };
if state.deleted_since(&session, started) {
return false;
}
let Some(list) = overlay.apply(list, id) else {
state.invalidate_key(key);
return true;
};
publish(state, &read, list, extra);
false
});
if reread {
data.refresh(again);
}
Ok(())
},
)
}
}
/// The locked state and the key of a read, for [`Data::sync_start`].
pub(crate) type Keyed<'a> = (Locked<'a>, ReadKey);
/// How a keyed load starts: begun under the caller's lock, or after the load it replaces.
enum Start<R, B> {
Begun(R),
After(Task<()>, B),
}
thread_local! {
/// The stores whose state this thread holds locked, innermost last: the state a read lends, or null for a write.
static HOLDING: std::cell::RefCell<Vec<(usize, *const State)>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// What this thread holds of the store `key`.
fn held(key: usize) -> Option<*const State> {
HOLDING.with_borrow(|holding| holding.iter().rev().find(|(held, _)| *held == key).map(|(_, state)| *state))
}
/// One entry of [`HOLDING`], removed on drop.
struct Held(usize);
impl Held {
fn enter(key: usize, state: *const State) -> Self {
HOLDING.with_borrow_mut(|holding| holding.push((key, state)));
Held(key)
}
}
impl Drop for Held {
fn drop(&mut self) {
HOLDING.with_borrow_mut(|holding| {
if let Some(index) = holding.iter().rposition(|(key, _)| *key == self.0) {
holding.remove(index);
}
});
}
}
/// The locked [`State`].
pub(crate) struct Locked<'a> {
_held: Held,
guard: MutexGuard<'a, State>,
}
impl std::ops::Deref for Locked<'_> {
type Target = State;
fn deref(&self) -> &State {
&self.guard
}
}
impl std::ops::DerefMut for Locked<'_> {
fn deref_mut(&mut self) -> &mut State {
&mut self.guard
}
}
/// Event types [`Data::signals`] sends while it lives; see [`Data::listen`].
#[must_use = "the types stop being sent when this drops"]
pub struct Listening {
inner: std::sync::Weak<Inner>,
kinds: EventKinds,
}
impl Drop for Listening {
fn drop(&mut self) {
let Some(inner) = self.inner.upgrade() else { return };
let mut named = lock(&inner.named);
for index in self.kinds.indices() {
inner.listened[index].fetch_sub(1, Ordering::SeqCst);
}
for name in self.kinds.names() {
if let Some(count) = named.get_mut(name) {
*count -= 1;
}
}
named.retain(|_, count| *count > 0);
}
}
/// The streaming deltas kept for the [`DeltaListening`]s, numbered in the order kept.
#[derive(Default)]
pub(crate) struct Deltas {
/// The number the next delta kept gets.
next: u64,
/// The deltas some listener has not taken, the last numbered `next - 1`.
kept: std::collections::VecDeque<opencode_api::generated::V2Event>,
/// Each listener's first delta not taken, by its ID.
cursors: HashMap<u64, u64>,
/// The ID of the next listener.
ids: u64,
}
impl Deltas {
/// Drops the deltas every listener has taken.
fn trim(&mut self) {
let first = self.next - self.kept.len() as u64;
let taken = self.cursors.values().min().copied().unwrap_or(self.next);
self.kept.drain(..taken.saturating_sub(first) as usize);
}
}
/// The streaming deltas kept for [`Self::take`] while it lives; see [`Data::listen_deltas`].
#[must_use = "the deltas stop being kept when this drops"]
pub struct DeltaListening {
inner: std::sync::Weak<Inner>,
id: u64,
}
impl DeltaListening {
/// The streaming deltas the store applied since this listener last took them, or since it started, oldest first.
pub fn take(&self) -> Vec<opencode_api::generated::V2Event> {
let Some(inner) = self.inner.upgrade() else { return Vec::new() };
let mut deltas = lock(&inner.deltas);
let first = deltas.next - deltas.kept.len() as u64;
let next = deltas.next;
let Some(cursor) = deltas.cursors.insert(self.id, next) else { return Vec::new() };
let events = deltas.kept.iter().skip(cursor.saturating_sub(first) as usize).cloned().collect();
deltas.trim();
events
}
}
impl Drop for DeltaListening {
fn drop(&mut self) {
let Some(inner) = self.inner.upgrade() else { return };
let mut deltas = lock(&inner.deltas);
deltas.cursors.remove(&self.id);
inner.delta_listeners.store(deltas.cursors.len(), Ordering::SeqCst);
deltas.trim();
}
}
pub(crate) fn is_tag(error: &Error, tag: &str) -> bool {
error.declared().is_some_and(|declared| declared.tag.as_deref() == Some(tag))
}
@ -764,31 +239,3 @@ pub(crate) fn session_not_found(error: &Error) -> Option<SessionID> {
}
declared.body.get("sessionID").and_then(serde_json::Value::as_str).map(|id| SessionID(id.to_owned()))
}
/// Marks a missing session deleted and passes the error on (`evictMissing`).
pub(crate) fn evict_missing(data: &Data, error: opencode_api::error::Error) -> Error {
let error = Arc::new(error);
if let Some(id) = session_not_found(&error) {
data.write(|state| state.mark_deleted(&id));
}
error
}
#[cfg(test)]
mod tests {
use super::*;
fn data() -> (tokio::runtime::Runtime, Data) {
let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
let client = Client::new("http://opencode.local").unwrap();
let data = Data::with_runtime(client, Options::default(), runtime.handle().clone());
(runtime, data)
}
#[test]
#[should_panic(expected = "store read inside a store write")]
fn a_read_inside_a_write_panics() {
let (_runtime, data) = data();
data.write(|_| data.read(|_| ()));
}
}

View file

@ -7,7 +7,7 @@ use opencode_api::generated::{
SessionPromptInput, SessionRevertCommitInput, SessionShellInput, SessionSwitchAgentInput, SessionSwitchModelInput,
SessionSyntheticInput,
};
use opencode_store::inbox::Gate;
use opencode_store::Gate;
use opencode_store::{CreateSession, Error, Prompt};
use super::autocomplete::parts;