Skip to content

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

fix(session): remove unused link module and its tests

Steven Enamakel32f040048db2
diff --git a/crates/openhuman-app/src/session/commands.rs b/crates/openhuman-app/src/session/commands.rs
new file mode 100644
index 0000000000..ef943b8d1f
--- /dev/null
+++ b/crates/openhuman-app/src/session/commands.rs
@@ -0,0 +1,60 @@
+//! Tauri commands the renderer uses to drive login, logout and the current
+//! user. Each is a one-line delegate to the managed `SessionHost`; the
+//! `Err(String)` carries `openhuman_session::SessionError`'s stable
+//! `PREFIX:` so the frontend can classify without parsing prose.
+
+use openhuman_session::{CachedUser, SessionState};
+
+use super::SessionHost;
+
+fn err(error: openhuman_session::SessionError) -> String {
+ error.to_string()
+}
+
+/// Exchange a one-time login token for a session JWT, validate it against
+/// the backend, and install it in the core.
+#[tauri::command]
+pub(crate) async fn auth_login_with_token(
+ host: tauri::State<'_, SessionHost>,
+ token: String,
+) -> Result<SessionState, String> {
+ log::info!("[session][cmd] auth_login_with_token");
+ host.manager.login_with_token(&token).await.map_err(err)
+}
+
+/// Install a session JWT (or the offline local token) the renderer already
+/// holds. A JWT is validated against the backend first.
+#[tauri::command]
+pub(crate) async fn auth_store_session(
+ host: tauri::State<'_, SessionHost>,
+ token: String,
+ user: Option<serde_json::Value>,
+) -> Result<SessionState, String> {
+ log::info!("[session][cmd] auth_store_session has_user={}", user.is_some());
+ host.manager.store_session_token(&token, user).await.map_err(err)
+}
+
+/// Sign out: clear the session credential in the core.
+#[tauri::command]
+pub(crate) async fn auth_logout(host: tauri::State<'_, SessionHost>) -> Result<SessionState, String> {
+ log::info!("[session][cmd] auth_logout");
+ host.manager.logout().await.map_err(err)
+}
+
+/// The core's credential state plus the cached current user.
+#[tauri::command]
+pub(crate) async fn auth_state(host: tauri::State<'_, SessionHost>) -> Result<SessionState, String> {
+ host.manager.state().await.map_err(err)
+}
+
+/// The current user from `/auth/me`, served from the cache unless `force`.
+#[tauri::command]
+pub(crate) async fn auth_current_user(
+ host: tauri::State<'_, SessionHost>,
+ force: Option<bool>,
+) -> Result<CachedUser, String> {
+ host.manager
+ .current_user(force.unwrap_or(false))
+ .await
+ .map_err(err)
+}
diff --git a/crates/openhuman-app/src/session/link.rs b/crates/openhuman-app/src/session/link.rs
new file mode 100644
index 0000000000..e8934fcfa9
--- /dev/null
+++ b/crates/openhuman-app/src/session/link.rs
@@ -0,0 +1,63 @@
+//! `CoreLink` over the shell's own RPC path: the same `(url, token)` the
+//! renderer uses, resolved per call so a gateway switch or a core restart is
+//! picked up without re-wiring, and the same transport guard
+//! (`core_rpc::post_json_rpc`) that refuses a bearer over plain HTTP off
+//! loopback.
+
+use async_trait::async_trait;
+use openhuman_session::CoreLink;
+use serde_json::{json, Value};
+
+use crate::core_process::CoreProcessHandle;
+
+pub struct HttpCoreLink {
+ desktop: CoreProcessHandle,
+}
+
+impl HttpCoreLink {
+ pub fn new(desktop: CoreProcessHandle) -> Self {
+ Self { desktop }
+ }
+}
+
+/// Decode a JSON-RPC 2.0 response body into its `result`, or the error
+/// message.
+pub(crate) fn decode_rpc_response(status: u16, body: &str) -> Result<Value, String> {
+ let parsed: Value = serde_json::from_str(body).map_err(|e| {
+ format!("core rpc returned a non-JSON body (http {status}): {e}")
+ })?;
+ if let Some(error) = parsed.get("error").filter(|e| !e.is_null()) {
+ let message = error
+ .get("message")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .unwrap_or_else(|| error.to_string());
+ return Err(message);
+ }
+ if !(200..300).contains(&status) {
+ return Err(format!("core rpc failed with http {status}"));
+ }
+ Ok(parsed.get("result").cloned().unwrap_or(Value::Null))
+}
+
+#[async_trait]
+impl CoreLink for HttpCoreLink {
+ async fn invoke(&self, method: &str, params: Value) -> Result<Value, String> {
+ let (url, token) = crate::active_rpc_endpoint(&self.desktop).await;
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": method,
+ "params": params,
+ })
+ .to_string();
+ log::debug!("[session][link] {method} -> {}", openhuman_rpc::redact_url_for_log(&url));
+ let token = (!token.is_empty()).then_some(token);
+ let response = crate::core_rpc::post_json_rpc(&url, token.as_deref(), body).await?;
+ decode_rpc_response(response.status, &response.body)
+ }
+}
+
+#[cfg(test)]
+#[path = "link_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-app/src/session/link_tests.rs b/crates/openhuman-app/src/session/link_tests.rs
new file mode 100644
index 0000000000..2d01d989db
--- /dev/null
+++ b/crates/openhuman-app/src/session/link_tests.rs
@@ -0,0 +1,21 @@
+use super::decode_rpc_response;
+use serde_json::json;
+
+#[test]
+fn decodes_result_and_error_envelopes() {
+ let ok = decode_rpc_response(200, r#"{"jsonrpc":"2.0","id":1,"result":{"isAuthenticated":true}}"#).unwrap();
+ assert_eq!(ok, json!({ "isAuthenticated": true }));
+
+ let err = decode_rpc_response(
+ 200,
+ r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"token is required"}}"#,
+ )
+ .unwrap_err();
+ assert_eq!(err, "token is required");
+
+ let http = decode_rpc_response(401, r#"{"jsonrpc":"2.0","id":1}"#).unwrap_err();
+ assert!(http.contains("401"), "{http}");
+
+ let garbage = decode_rpc_response(200, "<html>").unwrap_err();
+ assert!(garbage.contains("non-JSON"), "{garbage}");
+}
diff --git a/crates/openhuman-app/src/session/mod.rs b/crates/openhuman-app/src/session/mod.rs
new file mode 100644
index 0000000000..cdb72be52d
--- /dev/null
+++ b/crates/openhuman-app/src/session/mod.rs
@@ -0,0 +1,90 @@
+//! The desktop session owner: login-token exchange, `/auth/me` and the
+//! current-user cache live in `openhuman-session`; this module is the glue
+//! that gives it a link to the embedded (or gateway) core, exposes it to the
+//! renderer as Tauri commands, and forwards its change events as Tauri events.
+//!
+//! The core only *holds* the credential (`auth.set_credential`). Everything
+//! that talks to the backend's auth endpoints happens here, in the shell
+//! process, with the same `x-sdk-name` / version attribution headers the core
+//! sends on its own backend traffic.
+
+mod commands;
+mod link;
+
+use std::sync::Arc;
+
+use openhuman_session::{ClientHeaders, SessionEvent, SessionManager};
+use tauri::{AppHandle, Emitter, Manager};
+
+use crate::core_process::CoreProcessHandle;
+use crate::AppRuntime;
+
+pub(crate) use commands::{
+ auth_current_user, auth_login_with_token, auth_logout, auth_state, auth_store_session,
+};
+pub(crate) use link::HttpCoreLink;
+
+/// Tauri event emitted whenever the credential or the current user changes.
+/// Payload: `openhuman_session::SessionState`.
+pub const AUTH_CHANGED_EVENT: &str = "auth://changed";
+/// Tauri event emitted when the backend rejected the stored credential and it
+/// has been cleared. Payload: `{ source }`.
+pub const AUTH_EXPIRED_EVENT: &str = "auth://expired";
+
+/// Managed Tauri state: the one session manager for this shell process.
+pub struct SessionHost {
+ pub manager: Arc<SessionManager<HttpCoreLink>>,
+}
+
+impl SessionHost {
+ pub fn new(desktop: CoreProcessHandle) -> Self {
+ let headers = ClientHeaders::new(openhuman_core::api::product_identity().as_str())
+ .with_core_version(openhuman_core::CORE_VERSION)
+ .with_tauri_version(env!("CARGO_PKG_VERSION"));
+ let link = Arc::new(HttpCoreLink::new(desktop));
+ Self {
+ manager: SessionManager::new(link, headers),
+ }
+ }
+}
+
+/// Register the session host on the app and start forwarding its events to
+/// the renderer.
+pub fn install(app: &AppHandle<AppRuntime>, desktop: CoreProcessHandle) {
+ let host = SessionHost::new(desktop);
+ let mut events = host.manager.subscribe();
+ app.manage(host);
+
+ let handle = app.clone();
+ tauri::async_runtime::spawn(async move {
+ loop {
+ match events.recv().await {
+ Ok(SessionEvent::Changed(state)) => {
+ log::debug!(
+ "[session] auth changed authenticated={} credential={}",
+ state.core.is_authenticated,
+ state.core.credential.as_deref().unwrap_or("none")
+ );
+ if let Err(e) = handle.emit(AUTH_CHANGED_EVENT, state) {
+ log::debug!("[session] failed to emit {AUTH_CHANGED_EVENT}: {e}");
+ }
+ }
+ Ok(SessionEvent::Expired { source }) => {
+ log::warn!("[session] backend rejected the stored credential (source={source})");
+ if let Err(e) = handle.emit(AUTH_EXPIRED_EVENT, serde_json::json!({ "source": source })) {
+ log::debug!("[session] failed to emit {AUTH_EXPIRED_EVENT}: {e}");
+ }
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
+ log::debug!("[session] event forwarder lagged by {n} events");
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
+ }
+ }
+ });
+}
+
+/// The signed-in user id, for synchronous callers (Sentry `before_send`).
+pub fn peek_user_id() -> Option<String> {
+ openhuman_session::identity::peek_user_id()
+}