Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(web_chat): route web projection through TinyChannels module

Steven Enamakel876e72057368
diff --git a/crates/openhuman-core/src/web_chat/progress.rs b/crates/openhuman-core/src/web_chat/progress.rs
index f5ef58f541..b7feedc8f9 100644
--- a/crates/openhuman-core/src/web_chat/progress.rs
+++ b/crates/openhuman-core/src/web_chat/progress.rs
@@ -97,7 +97,7 @@ pub(crate) struct ProgressProjection {
}
impl ProgressProjection {
- pub(crate) fn new(
+ pub(crate) async fn new(
ctx: &DispatchCtx,
ids: TurnIds,
metadata: ChatRequestMetadata,
@@ -123,7 +123,7 @@ impl ProgressProjection {
)
.unzip();
Self {
- surface: Surface::new(ctx, ids.clone()),
+ surface: Surface::new(ctx, ids.clone(), config.clone()).await,
turn_state: Some(TurnStateMirror::new(
turn_states,
ids.thread_id.clone(),
@@ -507,7 +507,7 @@ pub(crate) fn spawn_progress_bridge(
request_id,
};
let mut projection =
- ProgressProjection::new(&dispatch_ctx, ids, metadata, config, turn_state_store);
+ ProgressProjection::new(&dispatch_ctx, ids, metadata, config, turn_state_store).await;
let mut beat =
tokio::time::interval(std::time::Duration::from_secs(INFERENCE_HEARTBEAT_SECS));
beat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
diff --git a/crates/openhuman-core/src/web_chat/surface.rs b/crates/openhuman-core/src/web_chat/surface.rs
index d77d25773a..dff3e73f59 100644
--- a/crates/openhuman-core/src/web_chat/surface.rs
+++ b/crates/openhuman-core/src/web_chat/surface.rs
@@ -1,23 +1,18 @@
-//! The host's side of the `tinychannels` web adapter: where a turn's typed
-//! events go.
-//!
-//! The adapter projects canonical output events onto the deployed web wire and
-//! hands each result to a [`WebEventSink`]. This host's sink is the
-//! process-wide `WebChannelEvent` broadcast (`event_bus_channel`), which
-//! Socket.IO, the JSON-RPC `/events` stream, the relay and the TUI already
-//! consume, stamped with the tenant of the context the turn runs under.
+//! The host's adapter between a web-chat turn and TinyChannels' web projection
+//! module. Canonical output crosses TinyBus; the host retains event delivery,
+//! tenant routing, and web-chat-specific lifecycle policy.
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
-use async_trait::async_trait;
+use sha2::Digest as _;
use tinychannels_bus::module_progressive::ChannelOutputEvent;
use tinychannels_bus::web as bus_web;
-use tinychannels_runtime::adapters::web::{WebChannelAdapter, WebEventSink, WebScope};
-use tinychannels_runtime::channel::ChannelSendError;
+use tinychannels_bus::module_web_output::{BeginWebTurn, EndWebTurn, ProjectWebOutput, WebTurnHandle};
use super::event_bus_channel::publish_web_channel_event_in;
use super::WebChannelEvent;
+use crate::config::Config;
use crate::core::runtime::DispatchCtx;
/// Addressing of one turn on the web wire.
@@ -28,91 +23,177 @@ pub(crate) struct TurnIds {
pub(crate) request_id: String,
}
-/// [`WebEventSink`] over the in-process broadcast.
-struct SurfaceSink {
+struct SurfaceState {
+ module: tinybus::module::ModuleClient,
+ handle: Option<WebTurnHandle>,
+}
+
+/// One module-owned projection turn plus its host broadcast destination.
+#[derive(Clone)]
+pub(crate) struct Surface {
+ state: Arc<tokio::sync::Mutex<SurfaceState>>,
ctx: DispatchCtx,
+ scope_key: String,
+ ids: TurnIds,
/// The round of the narration the next `chat_interim` carries. The
/// canonical `Clarification` output has no round, and the frontend keys one
/// interim bubble per round, so the host supplies it here.
- interim_round: AtomicU32,
+ interim_round: Arc<AtomicU32>,
}
-#[async_trait]
-impl WebEventSink for SurfaceSink {
- async fn publish(
- &self,
- _scope: &WebScope,
- event: bus_web::WebChannelEvent,
- ) -> Result<(), ChannelSendError> {
+impl Surface {
+ /// A surface for the turn `ids`, publishing under `ctx`. Every canonical
+ /// projection goes through the compiled TinyChannels module.
+ pub(crate) async fn new(ctx: &DispatchCtx, ids: TurnIds, config: Config) -> Self {
+ #[cfg(test)]
+ let module = {
+ let _ = config;
+ crate::channels::module_fixture::client().await
+ };
+ #[cfg(not(test))]
+ let module = crate::modules::client(config);
+
+ let tenant = super::ops::tenant_of(ctx);
+ let scope_bytes = serde_json::to_vec(&(
+ tenant,
+ &ids.client_id,
+ &ids.thread_id,
+ &ids.request_id,
+ ))
+ .expect("web turn scope tuple is serializable");
+ let scope_key = format!("web-chat:{}", hex::encode(sha2::Sha256::digest(scope_bytes)));
+
+ Self {
+ state: Arc::new(tokio::sync::Mutex::new(SurfaceState {
+ module,
+ handle: None,
+ })),
+ ctx: ctx.clone(),
+ scope_key,
+ ids,
+ interim_round: Arc::new(AtomicU32::new(0)),
+ }
+ }
+
+ async fn begin_if_needed(&self, state: &mut SurfaceState) -> Result<String, String> {
+ if let Some(handle) = &state.handle {
+ return Ok(handle.handle.clone());
+ }
+ let response: WebTurnHandle = state
+ .module
+ .call_confidential(
+ "tinychannels",
+ tinychannels_bus::methods::BEGIN_WEB_TURN,
+ (BeginWebTurn {
+ scope_key: self.scope_key.clone(),
+ context: self.context(),
+ },),
+ )
+ .await
+ .map_err(|error| error.to_string())?;
+ let handle = response.handle.clone();
+ state.handle = Some(response);
+ Ok(handle)
+ }
+
+ async fn end_if_needed(&self, state: &mut SurfaceState) {
+ let Some(handle) = state.handle.take() else {
+ return;
+ };
+ if let Err(error) = state
+ .module
+ .call_confidential::<()>(
+ "tinychannels",
+ tinychannels_bus::methods::END_WEB_TURN,
+ (EndWebTurn {
+ handle: handle.handle,
+ },),
+ )
+ .await
+ {
+ log::warn!(
+ "[web-channel] projection turn cleanup failed request_id={}: {error}",
+ self.ids.request_id
+ );
+ }
+ }
+
+ fn publish(&self, event: bus_web::WebChannelEvent) {
let mut flat = WebChannelEvent::from(event);
if flat.event == "chat_interim" && flat.round.is_none() {
flat.round = Some(self.interim_round.load(Ordering::Relaxed)).filter(|r| *r > 0);
}
publish_web_channel_event_in(&self.ctx, flat);
- Ok(())
}
-}
-
-/// One turn's web adapter plus the sink it publishes through.
-#[derive(Clone)]
-pub(crate) struct Surface {
- adapter: Arc<WebChannelAdapter>,
- sink: Arc<SurfaceSink>,
- ids: TurnIds,
-}
-impl Surface {
- /// A surface for the turn `ids`, publishing under `ctx`. One adapter per
- /// turn: it carries that turn's `seq` counter, and dropping it with the
- /// turn is its cleanup.
- pub(crate) fn new(ctx: &DispatchCtx, ids: TurnIds) -> Self {
- let sink = Arc::new(SurfaceSink {
- ctx: ctx.clone(),
- interim_round: AtomicU32::new(0),
- });
- let adapter = Arc::new(WebChannelAdapter::new(
- None,
- WebScope::local(),
- sink.clone() as Arc<dyn WebEventSink>,
- ));
- Self { adapter, sink, ids }
- }
-
- /// Project one canonical output event onto the web wire, in `seq` order.
+ /// Project one canonical output event onto the web wire, in module-owned
+ /// sequence order. Module errors fail closed; the host never reimplements
+ /// the projection locally.
pub(crate) async fn output(&self, event: ChannelOutputEvent) {
- let TurnIds {
- client_id,
- thread_id,
- request_id,
- } = &self.ids;
- if let Err(error) = self
- .adapter
- .publish_output(client_id, thread_id, request_id, event)
+ let mut state = self.state.lock().await;
+ let handle = match self.begin_if_needed(&mut state).await {
+ Ok(handle) => handle,
+ Err(error) => {
+ log::warn!(
+ "[web-channel] projection turn could not begin request_id={}: {error}",
+ self.ids.request_id
+ );
+ return;
+ }
+ };
+ let terminal = matches!(
+ &event,
+ ChannelOutputEvent::FinalMessage { .. }
+ | ChannelOutputEvent::ChatError { .. }
+ | ChannelOutputEvent::ChatCancelled { .. }
+ );
+ let projected: tinychannels_bus::module_web_output::WebOutputEvents = match state
+ .module
+ .call_confidential(
+ "tinychannels",
+ tinychannels_bus::methods::PROJECT_WEB_OUTPUT,
+ (ProjectWebOutput { handle, event },),
+ )
.await
{
- log::warn!(
- "[web-channel] output event not published request_id={request_id}: {}",
- error.message
- );
+ Ok(projected) => projected,
+ Err(error) => {
+ log::warn!(
+ "[web-channel] output event not projected request_id={}: {error}",
+ self.ids.request_id
+ );
+ return;
+ }
+ };
+ for event in projected.events {
+ self.publish(event);
+ }
+ if terminal {
+ self.end_if_needed(&mut state).await;
}
}
/// The leading narration of `round`, flushed as an interim bubble.
pub(crate) async fn interim(&self, round: u32, text: String) {
- self.sink.interim_round.store(round, Ordering::Relaxed);
+ self.interim_round.store(round, Ordering::Relaxed);
self.output(ChannelOutputEvent::Clarification { prompt: text })
.await;
}
- /// Publish a host-authored event unchanged: a terminal event, or one with
- /// no canonical output form.
+ /// Publish a host-authored event unchanged (queue, goal, todo, or the
+ /// enriched terminal event). It has no canonical projection form, but it
+ /// still closes any module-owned projection state for the turn.
pub(crate) async fn event(&self, event: bus_web::WebChannelEvent) {
- if let Err(error) = self.adapter.publish_event(event).await {
- log::warn!(
- "[web-channel] event not published request_id={}: {}",
- self.ids.request_id,
- error.message
- );
+ let terminal = matches!(
+ &event,
+ bus_web::WebChannelEvent::ChatDone { .. }
+ | bus_web::WebChannelEvent::ChatError { .. }
+ | bus_web::WebChannelEvent::ChatCancelled { .. }
+ );
+ let mut state = self.state.lock().await;
+ self.publish(event);
+ if terminal {
+ self.end_if_needed(&mut state).await;
}
}
diff --git a/crates/openhuman-core/src/web_chat/turn_host.rs b/crates/openhuman-core/src/web_chat/turn_host.rs
index d2af7993c1..6b08bb9570 100644
--- a/crates/openhuman-core/src/web_chat/turn_host.rs
+++ b/crates/openhuman-core/src/web_chat/turn_host.rs
@@ -168,7 +168,8 @@ impl WebHost {
metadata,
config.clone(),
crate::agent::session_store::turn_states_for(&config.workspace_dir),
- );
+ )
+ .await;
self.shared.with(id, |slot| {
slot.session = Some(checked);
slot.fork = policy == CheckoutPolicy::Fork;
diff --git a/crates/openhuman-core/src/web_chat/turn_host_tests.rs b/crates/openhuman-core/src/web_chat/turn_host_tests.rs
index e692075045..1ab7ad6797 100644
--- a/crates/openhuman-core/src/web_chat/turn_host_tests.rs
+++ b/crates/openhuman-core/src/web_chat/turn_host_tests.rs
@@ -141,7 +141,8 @@ async fn the_heartbeat_beats_only_for_a_live_turn() {
Default::default(),
crate::config::Config::default(),
std::sync::Arc::new(tinyagents_session::port::InMemoryTurnStates::default()),
- )));
+ )
+ .await));
let beat = AbortOnDrop(spawn_heartbeat(&DispatchCtx::ambient(), projection.clone()));
// Before `TurnStarted` the turn is not live: no beat, however long it waits.