Skip to content

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

fix(channels): retire workspace-bound runtimes on logout

Eloi Torrentsb1a69caa77ca
diff --git a/crates/openhuman-core/src/channels/mod.rs b/crates/openhuman-core/src/channels/mod.rs
index 5d28f1bc68..3fa24c177d 100644
--- a/crates/openhuman-core/src/channels/mod.rs
+++ b/crates/openhuman-core/src/channels/mod.rs
@@ -136,3 +136,5 @@ pub use controllers::{ChannelAuthMode, ChannelDefinition};
pub use crate::agent::context::channels_prompt::build_system_prompt;
#[cfg(feature = "channels")]
pub use runtime::start_channels;
+#[cfg(feature = "channels")]
+pub(crate) use runtime::{session, start_channels_with_session};
diff --git a/crates/openhuman-core/src/channels/runtime/README.md b/crates/openhuman-core/src/channels/runtime/README.md
index ca84a8f7f3..d44c9ddef3 100644
--- a/crates/openhuman-core/src/channels/runtime/README.md
+++ b/crates/openhuman-core/src/channels/runtime/README.md
@@ -1,6 +1,6 @@
# Runtime
-Boots every enabled channel, keeps their listeners alive, and dispatches inbound messages into the agent loop. `mod.rs` exports only `start_channels`; `dispatch` and `supervision` internals are `pub(crate)` for `channels/tests/` under `#[cfg(test)]`.
+Boots every enabled channel, keeps their listeners alive, and dispatches inbound messages into the agent loop. `mod.rs` exports `start_channels` and a crate-internal startup entry with a captured session lifetime; `dispatch` and `supervision` internals are `pub(crate)` for `channels/tests/` under `#[cfg(test)]`.
## Files
@@ -11,6 +11,10 @@ Boots every enabled channel, keeps their listeners alive, and dispatches inbound
| `dispatch/` | The inbound pipeline that turns a `RuntimeChannelMessage` into an agent turn and a reply |
| `test_support.rs` | `#[cfg(any(test, debug_assertions))]` dispatch harness (`run_dispatch_harness`, `DispatchHarnessOptions`) used by `channels/tests/` and raw coverage |
+## Account lifetime
+
+Model authentication and account lifetime are separate. A local or CLI model can run without an OpenHuman backend session, but explicit logout cancels the old account's channel runtime. `spawn_channels_service` captures the channel lifetime before awaiting config loading, so logout also cancels a partially started runtime. `session.rs` stops the runtime on invalidation; owned listener/bridge tasks, dispatch workers, draft updaters, typing tasks, and relay reconnect supervision terminate when their owners drop. A runtime explicitly started again obtains a fresh lifetime; logout does not automatically start listeners for another account.
+
## Inbound path
1. Each provider listener (`spawn_supervised_listener`, one per channel from `tinychannels::build_channels`) sends `traits::ChannelMessage`s on a bounded `mpsc` (capacity 100). A bridge task in `startup/start_channels.rs` wraps each into `RuntimeChannelMessage` and forwards it to the dispatch queue (also capacity 100). The relay runtime (`start_relay_runtime`) writes `RuntimeChannelMessage`s to that queue directly so relay inbound keeps its original TinyChannels envelope.
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
index 5261bf20eb..49e7b309fe 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@ -23,6 +23,7 @@ use std::time::{Duration, Instant};
use tinybus::NativeRequestError;
use tinymemory_api::provider::MemoryCore as _;
use tokio_util::sync::CancellationToken;
+use tokio_util::task::AbortOnDropHandle;
use super::super::helpers::{
build_channel_context_block, log_worker_join_result, select_acknowledgment_reaction,
@@ -246,7 +247,7 @@ pub(crate) async fn process_channel_runtime_message(
let channel = Arc::clone(channel_ref);
let reply_target = msg.reply_target.clone();
let draft_id = draft_id_ref.to_string();
- Some(tokio::spawn(async move {
+ Some(AbortOnDropHandle::new(tokio::spawn(async move {
let mut accumulated = String::new();
let mut last_thinking_update = None;
const THINKING_UPDATE_INTERVAL_MS: u128 = 2000;
@@ -298,7 +299,7 @@ pub(crate) async fn process_channel_runtime_message(
_ => {}
}
}
- }))
+ })))
} else {
None
};
@@ -307,11 +308,11 @@ pub(crate) async fn process_channel_runtime_message(
// Typing was already started early (before memory/provider setup). Here we only
// spawn the background refresh task that keeps the indicator alive during long turns.
let typing_task = match (target_channel.as_ref(), typing_cancellation.as_ref()) {
- (Some(channel), Some(token)) => Some(spawn_scoped_typing_task(
+ (Some(channel), Some(token)) => Some(AbortOnDropHandle::new(spawn_scoped_typing_task(
Arc::clone(channel),
msg.reply_target.clone(),
token.clone(),
- )),
+ ))),
_ => None,
};
diff --git a/crates/openhuman-core/src/channels/runtime/mod.rs b/crates/openhuman-core/src/channels/runtime/mod.rs
index daf8b881c2..565b78c7ac 100644
--- a/crates/openhuman-core/src/channels/runtime/mod.rs
+++ b/crates/openhuman-core/src/channels/runtime/mod.rs
@@ -1,10 +1,12 @@
//! Channel runtime entry points.
mod dispatch;
+pub(crate) mod session;
mod startup;
mod supervision;
pub use startup::start_channels;
+pub(crate) use startup::start_channels_with_session;
#[cfg(any(test, debug_assertions))]
pub mod test_support;
diff --git a/crates/openhuman-core/src/channels/runtime/session.rs b/crates/openhuman-core/src/channels/runtime/session.rs
new file mode 100644
index 0000000000..d555272c4a
--- /dev/null
+++ b/crates/openhuman-core/src/channels/runtime/session.rs
@@ -0,0 +1,36 @@
+//! Explicit logout invalidates channel runtimes, independently of model auth.
+use std::future::Future;
+use std::sync::{LazyLock, Mutex};
+use tokio_util::sync::CancellationToken;
+
+static SESSION: LazyLock<Mutex<CancellationToken>> =
+ LazyLock::new(|| Mutex::new(CancellationToken::new()));
+
+pub(crate) fn channel_session() -> CancellationToken {
+ SESSION.lock().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
+pub(crate) fn invalidate_channel_session() {
+ let mut session = SESSION.lock().unwrap_or_else(|e| e.into_inner());
+ session.cancel();
+ *session = CancellationToken::new();
+ tracing::debug!("[channels] invalidated channel runtimes on logout");
+}
+
+pub(super) async fn run_in_session(
+ session: CancellationToken,
+ runtime: impl Future<Output = anyhow::Result<()>>,
+) -> anyhow::Result<()> {
+ tokio::select! {
+ biased;
+ _ = session.cancelled() => {
+ tracing::info!("[channels] stopping runtime after logout");
+ Ok(())
+ }
+ result = runtime => result,
+ }
+}
+
+#[cfg(test)]
+#[path = "session_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/channels/runtime/session_tests.rs b/crates/openhuman-core/src/channels/runtime/session_tests.rs
new file mode 100644
index 0000000000..e793c882f0
--- /dev/null
+++ b/crates/openhuman-core/src/channels/runtime/session_tests.rs
@@ -0,0 +1,60 @@
+use super::*;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+
+#[tokio::test]
+async fn independent_local_runtime_does_not_need_an_account_session() {
+ let _guard = crate::inference::inference_test_guard();
+ let _signed_out = crate::cron::scheduler_gate::SignedOutTestGuard::set(true);
+ run_in_session(CancellationToken::new(), async { Ok(()) })
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn invalidated_startup_never_polls_workspace_or_listeners() {
+ let session = CancellationToken::new();
+ session.cancel();
+ let polled = AtomicBool::new(false);
+ run_in_session(session.clone(), async {
+ polled.store(true, Ordering::SeqCst);
+ Ok(())
+ })
+ .await
+ .unwrap();
+ assert!(!polled.load(Ordering::SeqCst));
+ // Exercise the production entry point, not only the generic select helper.
+ crate::channels::start_channels_with_session(crate::config::Config::default(), session)
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn logout_drops_the_old_runtime_and_aborts_owned_workers() {
+ let session = CancellationToken::new();
+ let logout = session.clone();
+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();
+ let (dropped_tx, dropped_rx) = tokio::sync::oneshot::channel();
+ struct Dropped(Option<tokio::sync::oneshot::Sender<()>>);
+ impl Drop for Dropped {
+ fn drop(&mut self) {
+ let _ = self.0.take().unwrap().send(());
+ }
+ }
+ let touched_after_logout = Arc::new(AtomicBool::new(false));
+ let touched = touched_after_logout.clone();
+ let runtime = tokio::spawn(run_in_session(session, async move {
+ let _worker = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
+ let _dropped = Dropped(Some(dropped_tx));
+ let _ = started_tx.send(());
+ std::future::pending::<()>().await;
+ touched.store(true, Ordering::SeqCst);
+ }));
+ std::future::pending::<anyhow::Result<()>>().await
+ }));
+ started_rx.await.unwrap();
+ logout.cancel();
+ runtime.await.unwrap().unwrap();
+ dropped_rx.await.unwrap();
+ assert!(!touched_after_logout.load(Ordering::SeqCst));
+}
diff --git a/crates/openhuman-core/src/channels/runtime/startup.rs b/crates/openhuman-core/src/channels/runtime/startup.rs
index 1e96ea5c46..ccca4671ba 100644
--- a/crates/openhuman-core/src/channels/runtime/startup.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup.rs
@@ -7,6 +7,7 @@ mod relay;
mod start_channels;
pub use start_channels::start_channels;
+pub(crate) use start_channels::start_channels_with_session;
// Re-exported at module scope (rather than left as private `pub(super)`
// items reached only through their owning submodule) so the `#[path]` test
diff --git a/crates/openhuman-core/src/channels/runtime/startup/relay.rs b/crates/openhuman-core/src/channels/runtime/startup/relay.rs
index 4f50e4d03a..d84371a195 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/relay.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/relay.rs
@@ -41,6 +41,12 @@ pub(super) struct RelayRuntimeHandle {
pub(super) _reconnect: tinychannels::relay::RelayReconnectHandle,
}
+impl Drop for RelayRuntimeHandle {
+ fn drop(&mut self) {
+ self._reconnect.abort();
+ }
+}
+
pub(super) async fn start_relay_runtime(
relay: &tinychannels::config::RelayRuntimeConfig,
tx: mpsc::Sender<RuntimeChannelMessage>,
diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
index a393106a88..b1f10eb8bb 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
@@ -24,6 +24,7 @@ use crate::tools;
use anyhow::Result;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
+use tokio_util::task::AbortOnDropHandle;
/// What the channel-server banner prints on its `🧠 Memory:` line.
///
@@ -44,7 +45,18 @@ use std::sync::{Arc, Mutex};
/// printed line is byte-identical to before.
const EFFECTIVE_MEMORY_BACKEND_LABEL: &str = "namespace";
-pub async fn start_channels(mut config: Config) -> Result<()> {
+pub async fn start_channels(config: Config) -> Result<()> {
+ start_channels_with_session(config, super::super::session::channel_session()).await
+}
+
+pub(crate) async fn start_channels_with_session(
+ config: Config,
+ session: tokio_util::sync::CancellationToken,
+) -> Result<()> {
+ super::super::session::run_in_session(session, start_channels_inner(config)).await
+}
+
+async fn start_channels_inner(mut config: Config) -> Result<()> {
// Initialize the global event bus singleton and register the tracing
// subscriber for debug logging of all domain events.
crate::core::bus::init().await.expect("bus init");
@@ -386,7 +398,7 @@ pub async fn start_channels(mut config: Config) -> Result<()> {
let (provider_tx, mut provider_rx) = tokio::sync::mpsc::channel::<traits::ChannelMessage>(100);
let (dispatch_tx, rx) = tokio::sync::mpsc::channel::<RuntimeChannelMessage>(100);
let provider_dispatch_tx = dispatch_tx.clone();
- let provider_bridge = tokio::spawn(async move {
+ let provider_bridge = AbortOnDropHandle::new(tokio::spawn(async move {
while let Some(msg) = provider_rx.recv().await {
if provider_dispatch_tx
.send(RuntimeChannelMessage::from(msg))
@@ -396,7 +408,7 @@ pub async fn start_channels(mut config: Config) -> Result<()> {
break;
}
}
- });
+ }));
let mut relay_handles = Vec::new();
if let Some(ref relay) = relay_config {
@@ -411,12 +423,12 @@ pub async fn start_channels(mut config: Config) -> Result<()> {
// Spawn a listener for each channel
let mut handles = Vec::new();
for ch in &channels {
- handles.push(spawn_supervised_listener(
+ handles.push(AbortOnDropHandle::new(spawn_supervised_listener(
ch.clone(),
provider_tx.clone(),
initial_backoff_secs,
max_backoff_secs,
- ));
+ )));
}
drop(provider_tx); // Drop our copy so provider_rx closes when all channels stop.
drop(dispatch_tx); // Drop startup's copy; relay/bridge clones keep dispatch alive.
diff --git a/crates/openhuman-core/src/core/runtime/services.rs b/crates/openhuman-core/src/core/runtime/services.rs
index 082bbcdb62..f4d7bb72b4 100644
--- a/crates/openhuman-core/src/core/runtime/services.rs
+++ b/crates/openhuman-core/src/core/runtime/services.rs
@@ -168,6 +168,9 @@ pub fn spawn_channels_service() {
.filter(|s| s == "1" || s.eq_ignore_ascii_case("true"))
.is_none()
{
+ // Capture before loading config: logout during that await must also
+ // invalidate a listener that has not finished starting yet.
+ let channel_session = crate::channels::session::channel_session();
tokio::spawn(async move {
let config = match crate::config::Config::load_or_init().await {
Ok(c) => c,
@@ -183,7 +186,9 @@ pub fn spawn_channels_service() {
return;
}
log::info!("[channels] spawning in-process realtime listeners (Telegram, Discord, …)");
- if let Err(e) = crate::channels::start_channels(config).await {
+ if let Err(e) =
+ crate::channels::start_channels_with_session(config, channel_session).await
+ {
log::error!("[channels] start_channels ended with error: {e}");
}
});
diff --git a/crates/openhuman-core/src/security/credentials/ops/session_query.rs b/crates/openhuman-core/src/security/credentials/ops/session_query.rs
index 9ce21b2aa7..1fd535d483 100644
--- a/crates/openhuman-core/src/security/credentials/ops/session_query.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/session_query.rs
@@ -23,6 +23,10 @@ pub async fn clear_session(config: &Config) -> Result<RpcOutcome<serde_json::Val
// `wait_for_capacity()` call instead of firing requests at a backend
// we're about to invalidate. Idempotent.
crate::cron::scheduler_gate::set_signed_out(true);
+ // Local/CLI model authentication can outlive an OpenHuman account.
+ // The old account's listeners and workspace-bound channel state cannot.
+ #[cfg(feature = "channels")]
+ crate::channels::session::invalidate_channel_session();
// Invalidate before removing the profile so a pending revalidation cannot
// recreate it after logout has finished the removal.
diff --git a/crates/openhuman-core/src/security/credentials/ops_provider_oauth_tests.rs b/crates/openhuman-core/src/security/credentials/ops_provider_oauth_tests.rs
index bb9547f9e5..b8956fe828 100644
--- a/crates/openhuman-core/src/security/credentials/ops_provider_oauth_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/ops_provider_oauth_tests.rs
@@ -32,7 +32,14 @@ async fn clear_session_on_empty_store_reports_removed_false() {
let tmp = TempDir::new().unwrap();
let _home = EnvVarGuard::set_to_path("HOME", tmp.path());
let config = test_config(&tmp);
+ #[cfg(feature = "channels")]
+ let old_channel_session = crate::channels::session::channel_session();
let result = clear_session(&config).await.unwrap();
+ #[cfg(feature = "channels")]
+ {
+ assert!(old_channel_session.is_cancelled());
+ assert!(!crate::channels::session::channel_session().is_cancelled());
+ }
assert_eq!(result.value["removed"], false);
}
diff --git a/docs/RELEASE-MANUAL-SMOKE.md b/docs/RELEASE-MANUAL-SMOKE.md
index c1e9febe25..33ee1b6a85 100644
--- a/docs/RELEASE-MANUAL-SMOKE.md
+++ b/docs/RELEASE-MANUAL-SMOKE.md
@@ -46,6 +46,7 @@ Applies to every release, all platforms.
- [ ] **SmartScreen does not block install** β€” Run the installer from a fresh download. Expected: SmartScreen passes (signed binary). If `Windows protected your PC` appears, the EV signature is missing or the reputation has not built up β€” escalate before shipping.
- [ ] **Installer creates Start Menu + Desktop shortcuts** β€” Defaults preserved. Expected: both shortcuts launch the app.
+- [ ] **Logout retires external channel listeners** β€” With a channel configured for a local or Claude CLI model, log out while leaving the core process running, then send a channel message. Expected: the old listener no longer processes the message or returns prior-account memory. Start a fresh local workspace/runtime separately and verify local model use still works without backend login.
- [ ] **App registers `openhuman://` URL scheme** β€” From a browser, click an `openhuman://oauth/success?...` link. Expected: OS prompts to open in OpenHuman; clicking through delivers the deep link.
### Linux
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 349d7a1834..d2bc56133d 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -89,7 +89,7 @@ Canonical mapping of every product feature to its test source(s). Drives gap-fil
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ----- | ------------------ | ----- | ----------------------------------- | ------ | ---------------------------------- |
-| 1.4.1 | Session Logout | WD | `logout-relogin-onboarding.spec.ts` | βœ… | |
+| 1.4.1 | Session Logout | RU+WD | `logout-relogin-onboarding.spec.ts`, `crates/openhuman-core/src/channels/runtime/session_tests.rs`, `crates/openhuman-core/src/security/credentials/ops_provider_oauth_tests.rs` | βœ… | Logout invalidates channel lifetimes, including pending startup; local inference remains independent of backend login. |
| 1.4.2 | Global Logout | WD | _missing_ β€” tracked #968 | ❌ | Multi-session invalidation |
| 1.4.3 | Token Invalidation | WD | _missing_ β€” tracked #968 | ❌ | Server-side revocation propagation |