Skip to content

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

feat(tui): wire browser sessions and optimize responsive rendering

Steven Enamakeleb152bd1c406
diff --git a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs
index 606dbd564a..5247fbda1d 100644
--- a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs
+++ b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs
@@ -20,7 +20,7 @@ use super::LOG_PREFIX;
use crate::config::rpc as config_rpc;
use crate::core::Outcome;
use crate::security::credentials::session_support::{
- load_app_session_profile, session_state_from_profile, session_token_from_profile,
+ load_app_session_profile, session_state_from_profile,
};
use log::{debug, warn};
use serde_json::Value;
@@ -68,7 +68,12 @@ pub async fn snapshot() -> Result<Outcome<AppStateSnapshot>, String> {
.await
.unwrap_or_else(|e| Err(format!("[app_state] auth profile load task panicked: {e}")))?;
let mut auth = session_state_from_profile(session_profile.as_ref());
- let session_token = session_token_from_profile(session_profile.as_ref());
+ let session_token = crate::security::credentials::session_support::session_token_for_config(
+ &config,
+ session_profile.as_ref(),
+ )
+ .ok()
+ .flatten();
let current_user = sanitize_snapshot_user(auth.user.clone());
auth.user = current_user.clone();
let auth_ms = t_auth.elapsed().as_millis();
diff --git a/crates/openhuman-core/src/security/credentials/README.md b/crates/openhuman-core/src/security/credentials/README.md
index 977fded90d..05013d21b8 100644
--- a/crates/openhuman-core/src/security/credentials/README.md
+++ b/crates/openhuman-core/src/security/credentials/README.md
@@ -18,20 +18,20 @@ Credential management for the backend credential the core authenticates with and
## Key files
-| File | Role |
-| --- | --- |
-| [`mod.rs`](./mod.rs) | Export-focused. Re-exports `core::*`, [`ops`](./ops) (also as `rpc`), Composio-direct helpers, schema controllers (`all_credentials_controller_schemas` / `all_credentials_registered_controllers`), `crate::backend::BackendClient`, and `jwt::user_id_from_profile_payload`. |
-| [`core.rs`](./core.rs) | `AuthService` facade over `AuthProfilesStore`: store/get/remove/set-active profiles, resolve bearer token, profile-id selection logic (override → active → default → any-for-provider), provider normalization, state-dir derivation. |
-| [`profiles.rs`](./profiles.rs) | The persistence engine. `AuthProfile` / `TokenSet` / `AuthProfileKind` / `AuthProfilesData` types and `AuthProfilesStore`: atomic JSON read/write, keychain vs encrypted-JSON secret handling, legacy migration, corrupt-store quarantine, PID-aware stale-lock recovery. |
-| [`api_key.rs`](./api_key.rs) | The `api-key` profile: `store_api_key[_in]`, `get_api_key[_in]`, `has_api_key[_in]`, `clear_api_key`. |
-| [`ops.rs`](./ops.rs) + `ops/` | Business logic + RPC entry points (returns `RpcOutcome<T>`). [`ops/credential.rs`](./ops/credential.rs) (`set_credential` / `clear_credential`, plus the historical `store_session` / `clear_session` names), [`ops/user_scope.rs`](./ops/user_scope.rs) (user-dir activation and process-global rebinding), [`ops/gated_services.rs`](./ops/gated_services.rs) (credential-gated services), [`ops/boot_env.rs`](./ops/boot_env.rs) (env seeding), [`ops/session_query.rs`](./ops/session_query.rs) (`auth_get_state`, `auth_get_session_token_json`), [`ops/provider_credentials.rs`](./ops/provider_credentials.rs), [`ops/composio.rs`](./ops/composio.rs), [`ops/secrets.rs`](./ops/secrets.rs). Re-exported as `rpc`. |
-| [`schemas.rs`](./schemas.rs) | `auth.*` controller schemas + `handle_*` dispatchers delegating to `ops`. Defines `all_controller_schemas` / `all_registered_controllers`. |
-| [`session_support.rs`](./session_support.rs) | `CredentialKind`, `BackendCredential`, `resolve_backend_credential`, `require_live_session_token`, `has_backend_credential`, `build_session_state`, `get_session_token`, `load_app_session_profile`, `user_id_from_jwt_claims`, local-session detection/slug, field parsing. Shared by RPC and the HTTP host. |
-| [`identity.rs`](./identity.rs) | The signed-in user's identity slot (`peek_credential_user_identity`), seeded from the host-supplied payload for prompts and Sentry. |
-| [`responses.rs`](./responses.rs) | Response DTOs: `AuthStateResponse`, `AuthProfileSummary`. |
-| [`bus.rs`](./bus.rs) | `SessionExpiredSubscriber`: `EventHandler` for `DomainEvent::SessionExpired`. |
-| [`tools.rs`](./tools.rs) | Agent tools `credential_list`, `session_state`, `oauth_connect_url`, `oauth_list` (these two dispatch the hosted `auth_oauth_*` controllers by wire name through the registry and answer `BACKEND_UNAVAILABLE:` without the hosted layer). |
-| `*_tests.rs` | Sibling test suites (`#[path = ...]`). |
+| File | Role |
+| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [`mod.rs`](./mod.rs) | Export-focused. Re-exports `core::*`, [`ops`](./ops) (also as `rpc`), Composio-direct helpers, schema controllers (`all_credentials_controller_schemas` / `all_credentials_registered_controllers`), `crate::backend::BackendClient`, and `jwt::user_id_from_profile_payload`. |
+| [`core.rs`](./core.rs) | `AuthService` facade over `AuthProfilesStore`: store/get/remove/set-active profiles, resolve bearer token, profile-id selection logic (override → active → default → any-for-provider), provider normalization, state-dir derivation. |
+| [`profiles.rs`](./profiles.rs) | The persistence engine. `AuthProfile` / `TokenSet` / `AuthProfileKind` / `AuthProfilesData` types and `AuthProfilesStore`: atomic JSON read/write, keychain vs encrypted-JSON secret handling, legacy migration, corrupt-store quarantine, PID-aware stale-lock recovery. |
+| [`api_key.rs`](./api_key.rs) | The `api-key` profile: `store_api_key[_in]`, `get_api_key[_in]`, `has_api_key[_in]`, `clear_api_key`. |
+| [`ops.rs`](./ops.rs) + `ops/` | Business logic + RPC entry points (returns `RpcOutcome<T>`). [`ops/credential.rs`](./ops/credential.rs) (`set_credential` / `clear_credential`, plus the historical `store_session` / `clear_session` names), [`ops/user_scope.rs`](./ops/user_scope.rs) (user-dir activation and process-global rebinding), [`ops/gated_services.rs`](./ops/gated_services.rs) (credential-gated services), [`ops/boot_env.rs`](./ops/boot_env.rs) (env seeding), [`ops/session_query.rs`](./ops/session_query.rs) (`auth_get_state`, `auth_get_session_token_json`), [`ops/provider_credentials.rs`](./ops/provider_credentials.rs), [`ops/composio.rs`](./ops/composio.rs), [`ops/secrets.rs`](./ops/secrets.rs). Re-exported as `rpc`. |
+| [`schemas.rs`](./schemas.rs) | `auth.*` controller schemas + `handle_*` dispatchers delegating to `ops`. Defines `all_controller_schemas` / `all_registered_controllers`. |
+| [`session_support.rs`](./session_support.rs) | `CredentialKind`, `BackendCredential`, `resolve_backend_credential`, `require_live_session_token`, `has_backend_credential`, `build_session_state`, `get_session_token`, `load_app_session_profile`, `user_id_from_jwt_claims`, local-session detection/slug, field parsing. Shared by RPC and the HTTP host. |
+| [`identity.rs`](./identity.rs) | The signed-in user's identity slot (`peek_credential_user_identity`), seeded from the host-supplied payload for prompts and Sentry. |
+| [`responses.rs`](./responses.rs) | Response DTOs: `AuthStateResponse`, `AuthProfileSummary`. |
+| [`bus.rs`](./bus.rs) | `SessionExpiredSubscriber`: `EventHandler` for `DomainEvent::SessionExpired`. |
+| [`tools.rs`](./tools.rs) | Agent tools `credential_list`, `session_state`, `oauth_connect_url`, `oauth_list` (these two dispatch the hosted `auth_oauth_*` controllers by wire name through the registry and answer `BACKEND_UNAVAILABLE:` without the hosted layer). |
+| `*_tests.rs` | Sibling test suites (`#[path = ...]`). |
## Public surface
@@ -49,15 +49,15 @@ Credential management for the backend credential the core authenticates with and
Namespace `auth` (JSON-RPC `openhuman.auth_*` / CLI `openhuman-core auth <function>`). Defined in [`schemas.rs`](./schemas.rs):
-| Method | Description |
-| --- | --- |
-| `auth_set_credential` | Install the backend credential: `{ token, kind?: "session" \| "api-key" \| "local", userId?, user? }`. |
-| `auth_clear_credential` | Remove the credential of one `kind`, or every kind. |
-| `auth_get_state` | Current auth state (`AuthStateResponse`: `isAuthenticated`, `userId`, `user`, `profileId`, `credential`, `expiresAt`). |
-| `auth_get_session_token` | Read stored app session token. |
-| `auth_store_provider_credentials` | Store provider credentials for a profile. |
-| `auth_remove_provider_credentials` | Remove provider credentials. |
-| `auth_list_provider_credentials` | List stored provider credentials (optional provider filter). |
+| Method | Description |
+| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
+| `auth_set_credential` | Install the backend credential: `{ token, kind?: "session" \| "api-key" \| "local", userId?, user? }`. |
+| `auth_clear_credential` | Remove the credential of one `kind`, or every kind. |
+| `auth_get_state` | Current auth state (`AuthStateResponse`: `isAuthenticated`, `userId`, `user`, `profileId`, `credential`, `expiresAt`). |
+| `auth_get_session_token` | Read stored app session token. |
+| `auth_store_provider_credentials` | Store provider credentials for a profile. |
+| `auth_remove_provider_credentials` | Remove provider credentials. |
+| `auth_list_provider_credentials` | List stored provider credentials (optional provider filter). |
The account-bound `auth` methods `auth_create_channel_link_token`, `auth_oauth_connect`, `auth_oauth_list_integrations`, `auth_oauth_fetch_integration_tokens`, `auth_oauth_revoke_integration` and `auth_oauth_fetch_client_key` keep their wire names but are served by `openhuman-tinyhumans` (`hosted::{channel_link, oauth}`, on the TinyHumans SDK), registered only when `openhuman_tinyhumans::install` runs.
@@ -75,6 +75,15 @@ Note: `list_provider_credentials_by_prefix` and the Composio-direct/secret helpe
## Persistence
+New hosted sessions may include `issuingBackend` on `auth_set_credential`, also
+returned by `auth_get_state`. Its canonical HTTP(S) origin is stored as the
+non-secret `session_issuing_backend` profile metadata, beside the encrypted JWT.
+`get_session_token` and `resolve_backend_credential` refuse to release a bound
+JWT for a different configured backend (`SESSION_BACKEND_MISMATCH`). Same-token
+refresh preserves the association; it cannot rebind the token. Legacy profiles
+without this field remain unbound because the original backend cannot be
+inferred. API-key precedence and local-session behavior are unchanged.
+
`AuthProfilesStore` (`profiles.rs`) writes `auth-profiles.json` in the config state directory (parent of `config.config_path`, user-scoped after activation). Layout: `schema_version` (current = 1), `updated_at`, `active_profiles` (provider → profile-id), [`profiles`](./profiles) (id → profile). The `app-session` profile's metadata carries `user_id`, `user_json` (the host-supplied payload) and `session_expires_at` (the JWT `exp`, for the local expiry precheck). Secret handling:
- **OS keychain** when available (`crate::security::keyring::is_available`): all token fields stored under key `auth:{profile_id}` namespaced by a per-user id derived from the state dir; JSON keeps no secret fields.
diff --git a/crates/openhuman-core/src/security/credentials/ops/boot_env.rs b/crates/openhuman-core/src/security/credentials/ops/boot_env.rs
index 78163851cf..1877a98fe8 100644
--- a/crates/openhuman-core/src/security/credentials/ops/boot_env.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/boot_env.rs
@@ -62,6 +62,7 @@ pub async fn seed_session_from_env(config: &Config) {
kind: Some(CredentialKind::Session.as_str().to_string()),
user_id: None,
user: None,
+ issuing_backend: None,
};
match set_credential(config, request).await {
Ok(outcome) => log::info!(
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rs
index a6f42dc589..081644ae92 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs
@@ -66,6 +66,9 @@ pub struct SetCredentialRequest {
/// The user payload (the host's `/auth/me` answer, or the local user).
#[serde(default)]
pub user: Option<Value>,
+ /// Normalized backend used by the host to validate this session.
+ #[serde(default)]
+ pub issuing_backend: Option<String>,
}
fn sanitize_user(user: Option<Value>) -> Option<Value> {
@@ -182,7 +185,16 @@ pub async fn set_credential(
request: SetCredentialRequest,
) -> Result<Outcome<AuthStateResponse>, String> {
refuse_process_credential_in_saas("set_credential")?;
+ let issuing_backend = request.issuing_backend.clone();
let resolved = resolve(request)?;
+ let issuing_backend = if resolved.kind == CredentialKind::Session {
+ issuing_backend
+ .as_deref()
+ .map(crate::security::credentials::session_support::normalize_session_backend)
+ .transpose()?
+ } else {
+ None
+ };
let _mutation = CREDENTIAL_MUTATION_LOCK.lock().await;
if resolved.kind == CredentialKind::ApiKey {
@@ -226,6 +238,29 @@ pub async fn set_credential(
let same_user = existing_user_id.as_deref() == Some(user_id.as_str());
let refresh = same_token && same_user;
+ let mut metadata = std::collections::HashMap::new();
+ if resolved.kind == CredentialKind::Session {
+ let previous_backend = existing
+ .as_ref()
+ .filter(|_| same_token)
+ .and_then(|profile| {
+ profile.metadata.get(
+ crate::security::credentials::session_support::SESSION_ISSUING_BACKEND_META,
+ )
+ });
+ if let (Some(previous), Some(issuing)) = (previous_backend, issuing_backend.as_ref()) {
+ if previous != issuing {
+ return Err("SESSION_BACKEND_MISMATCH: cannot rebind a stored session to a different backend".into());
+ }
+ }
+ if let Some(backend) = previous_backend.cloned().or(issuing_backend) {
+ metadata.insert(
+ crate::security::credentials::session_support::SESSION_ISSUING_BACKEND_META
+ .to_string(),
+ backend,
+ );
+ }
+ }
if existing_token.is_some() && !same_user {
tracing::info!(
domain = "credentials",
@@ -235,8 +270,6 @@ pub async fn set_credential(
let cleared = clear_session_credential(config).await?;
logs.extend(cleared.logs);
}
-
- let mut metadata = std::collections::HashMap::new();
metadata.insert("user_id".to_string(), user_id.clone());
if let Some(user) = &resolved.user {
metadata.insert("user_json".to_string(), user.to_string());
@@ -533,6 +566,7 @@ pub async fn store_session(
kind: None,
user_id,
user,
+ issuing_backend: None,
},
)
.await
diff --git a/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs b/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs
index 6082b66bc0..adac89a47a 100644
--- a/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs
@@ -1,6 +1,57 @@
use super::*;
use crate::security::credentials::api_key;
+#[tokio::test]
+async fn same_token_refresh_preserves_issuing_backend_and_refuses_rebinding() {
+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let key = crate::security::credentials::session_support::SESSION_ISSUING_BACKEND_META;
+ let mut metadata = std::collections::HashMap::new();
+ metadata.insert("user_id".into(), "test-user".into());
+ metadata.insert(key.into(), "https://issuer.example".into());
+ AuthService::from_config(&config)
+ .store_provider_token(
+ APP_SESSION_PROVIDER,
+ DEFAULT_AUTH_PROFILE_NAME,
+ "synthetic-session",
+ metadata,
+ true,
+ )
+ .unwrap();
+ let state = set_credential(
+ &config,
+ SetCredentialRequest {
+ token: "synthetic-session".into(),
+ user_id: Some("test-user".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap()
+ .value;
+ assert_eq!(
+ state.issuing_backend.as_deref(),
+ Some("https://issuer.example")
+ );
+ let error = set_credential(
+ &config,
+ SetCredentialRequest {
+ token: "synthetic-session".into(),
+ user_id: Some("test-user".into()),
+ issuing_backend: Some("https://different.example".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap_err();
+ assert!(error.starts_with("SESSION_BACKEND_MISMATCH"));
+ let stored = crate::security::credentials::session_support::load_app_session_profile(&config)
+ .unwrap()
+ .unwrap();
+ assert_eq!(stored.metadata.get(key).unwrap(), "https://issuer.example");
+}
+
// ── secret_store_for_config ────────────────────────────────────
#[test]
diff --git a/crates/openhuman-core/src/security/credentials/responses.rs b/crates/openhuman-core/src/security/credentials/responses.rs
index 8eae27a5f5..9cfb21990d 100644
--- a/crates/openhuman-core/src/security/credentials/responses.rs
+++ b/crates/openhuman-core/src/security/credentials/responses.rs
@@ -19,6 +19,9 @@ pub struct AuthStateResponse {
/// Absent for API keys, local sessions and `exp`-less tokens.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
+ /// Backend that issued this session. Legacy sessions have no association.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub issuing_backend: Option<String>,
}
/// `AuthStateResponse::credential` value for an app-session JWT.
diff --git a/crates/openhuman-core/src/security/credentials/schemas.rs b/crates/openhuman-core/src/security/credentials/schemas.rs
index e25706b470..0aa53711ee 100644
--- a/crates/openhuman-core/src/security/credentials/schemas.rs
+++ b/crates/openhuman-core/src/security/credentials/schemas.rs
@@ -112,6 +112,7 @@ pub fn schemas(function: &str) -> ControllerSchema {
// Accepted spelling for callers that still send the historical
// `auth_store_session` shape through the legacy alias.
optional_string("user_id", "Alias of `userId`."),
+ optional_string("issuingBackend", "Backend origin used by the host to validate this session; binds future credential use to that deployment."),
optional_json(
"user",
"User payload (the host's /auth/me answer, or the local user).",
diff --git a/crates/openhuman-core/src/security/credentials/session_support.rs b/crates/openhuman-core/src/security/credentials/session_support.rs
index 27d20d54e2..3dda8f5463 100644
--- a/crates/openhuman-core/src/security/credentials/session_support.rs
+++ b/crates/openhuman-core/src/security/credentials/session_support.rs
@@ -220,6 +220,7 @@ pub fn build_session_state(config: &Config) -> Result<AuthStateResponse, String>
profile_id: None,
credential: Some(super::responses::CREDENTIAL_API_KEY.to_string()),
expires_at: None,
+ issuing_backend: None,
});
}
let profile = load_app_session_profile(config)?;
@@ -228,7 +229,62 @@ pub fn build_session_state(config: &Config) -> Result<AuthStateResponse, String>
pub fn get_session_token(config: &Config) -> Result<Option<String>, String> {
let profile = load_app_session_profile(config)?;
- Ok(session_token_from_profile(profile.as_ref()))
+ session_token_for_config(config, profile.as_ref())
+}
+
+/// Release an already-loaded profile's token only for its issuing backend.
+/// Snapshot callers may turn a mismatch into `None` while retaining identity.
+pub fn session_token_for_config(
+ config: &Config,
+ profile: Option<&AuthProfile>,
+) -> Result<Option<String>, String> {
+ check_session_backend(config, profile)?;
+ Ok(session_token_from_profile(profile))
+}
+
+/// Non-secret issuing-backend association stored beside the encrypted JWT.
+/// Legacy sessions are unbound: their origin cannot be inferred retroactively.
+pub const SESSION_ISSUING_BACKEND_META: &str = "session_issuing_backend";
+
+pub fn normalize_session_backend(raw: &str) -> Result<String, String> {
+ let mut parsed =
+ url::Url::parse(raw.trim()).map_err(|_| "invalid issuing backend".to_string())?;
+ if !matches!(parsed.scheme(), "http" | "https")
+ || parsed.host_str().is_none()
+ || !parsed.username().is_empty()
+ || parsed.password().is_some()
+ || parsed.query().is_some()
+ || parsed.fragment().is_some()
+ {
+ return Err("invalid issuing backend".to_string());
+ }
+ // SessionClient addresses auth endpoints at the backend origin.
+ parsed.set_path("");
+ Ok(parsed.as_str().trim_end_matches('/').to_string())
+}
+
+fn check_session_backend(config: &Config, profile: Option<&AuthProfile>) -> Result<(), String> {
+ let Some(profile) = profile else {
+ return Ok(());
+ };
+ if session_token_from_profile(Some(profile))
+ .as_deref()
+ .is_some_and(is_local_session_token)
+ {
+ return Ok(());
+ }
+ let Some(issuing) = profile.metadata.get(SESSION_ISSUING_BACKEND_META) else {
+ return Ok(());
+ };
+ let matches = crate::backend::base_url(&config.api_url)
+ .ok()
+ .and_then(|base| normalize_session_backend(&base).ok())
+ .zip(normalize_session_backend(issuing).ok())
+ .is_some_and(|(current, issuing)| current == issuing);
+ if !matches {
+ return Err("SESSION_BACKEND_MISMATCH: stored session belongs to a different backend; restore its backend or sign in again".to_string());
+ }
+ Ok(())
}
/// Metadata key under which the app-session profile records the decoded JWT
@@ -381,6 +437,7 @@ pub fn resolve_backend_credential(config: &Config) -> Result<BackendCredential,
return Ok(BackendCredential::ApiKey(key));
}
let profile = load_app_session_profile(config)?;
+ check_session_backend(config, profile.as_ref())?;
match classify_session_token(profile.as_ref(), chrono::Utc::now()) {
// The offline local session has no TinyHumans account behind it, so a
// hosted call is unavailable by construction — the typed sentinel lets
@@ -510,6 +567,7 @@ pub fn session_state_from_profile(profile: Option<&AuthProfile>) -> AuthStateRes
profile_id: None,
credential: None,
expires_at: None,
+ issuing_backend: None,
};
};
@@ -526,6 +584,10 @@ pub fn session_state_from_profile(profile: Option<&AuthProfile>) -> AuthStateRes
profile_id: Some(profile.id.clone()),
credential,
expires_at: session_expires_at_from_profile(Some(profile)).map(|dt| dt.to_rfc3339()),
+ issuing_backend: profile
+ .metadata
+ .get(SESSION_ISSUING_BACKEND_META)
+ .and_then(|backend| normalize_session_backend(backend).ok()),
}
}
diff --git a/crates/openhuman-core/src/security/credentials/session_support_tests.rs b/crates/openhuman-core/src/security/credentials/session_support_tests.rs
index 69a82a0cf3..80b937dd57 100644
--- a/crates/openhuman-core/src/security/credentials/session_support_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/session_support_tests.rs
@@ -14,6 +14,77 @@ fn test_config(tmp: &TempDir) -> Config {
}
}
+#[test]
+fn bound_session_token_release_requires_issuing_backend() {
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.api_url = Some("https://issuer.example/".into());
+ let mut metadata = std::collections::HashMap::new();
+ metadata.insert(
+ SESSION_ISSUING_BACKEND_META.into(),
+ "https://issuer.example".into(),
+ );
+ AuthService::from_config(&config)
+ .store_provider_token(
+ APP_SESSION_PROVIDER,
+ DEFAULT_AUTH_PROFILE_NAME,
+ "synthetic-session",
+ metadata,
+ true,
+ )
+ .unwrap();
+ assert_eq!(
+ get_session_token(&config).unwrap().as_deref(),
+ Some("synthetic-session")
+ );
+ assert!(matches!(
+ resolve_backend_credential(&config).unwrap(),
+ BackendCredential::Session(_)
+ ));
+ let state = build_session_state(&config).unwrap();
+ assert_eq!(
+ state.issuing_backend.as_deref(),
+ Some("https://issuer.example")
+ );
+ config.api_url = Some("https://different.example".into());
+ assert!(get_session_token(&config)
+ .unwrap_err()
+ .starts_with("SESSION_BACKEND_MISMATCH"));
+ assert!(resolve_backend_credential(&config)
+ .unwrap_err()
+ .starts_with("SESSION_BACKEND_MISMATCH"));
+ assert!(direct_backend_credential(&config, "test").is_none());
+ crate::security::credentials::api_key::store_api_key(&config, "synthetic-key").unwrap();
+ assert!(matches!(
+ resolve_backend_credential(&config).unwrap(),
+ BackendCredential::ApiKey(_)
+ ));
+}
+
+#[test]
+fn issuing_backend_normalizes_origin_and_rejects_url_secrets() {
+ assert_eq!(
+ normalize_session_backend("HTTPS://ISSUER.EXAMPLE:443/path/").unwrap(),
+ "https://issuer.example"
+ );
+ for invalid in [
+ "https://operator:[email protected]",
+ "https://issuer.example?token=secret",
+ "https://issuer.example#secret",
+ "file:///private",
+ ] {
+ assert_eq!(
+ normalize_session_backend(invalid).unwrap_err(),
+ "invalid issuing backend"
+ );
+ }
+ let legacy: AuthStateResponse = serde_json::from_value(
+ json!({"isAuthenticated":false,"userId":null,"user":null,"profileId":null}),
+ )
+ .unwrap();
+ assert!(legacy.issuing_backend.is_none());
+}
+
// ── profile_name_or_default ────────────────────────────────────
#[test]
diff --git a/crates/openhuman-tinyhumans/src/session/README.md b/crates/openhuman-tinyhumans/src/session/README.md
index 245c3b8e5f..3cecf5094d 100644
--- a/crates/openhuman-tinyhumans/src/session/README.md
+++ b/crates/openhuman-tinyhumans/src/session/README.md
@@ -12,6 +12,20 @@ in-process `CoreRuntime`). This module absorbed the former standalone
## How it works
+New session credentials carry the normalized backend origin used for exchange
+and validation as `issuingBackend`. Core stores this non-secret association in
+the existing profile metadata beside the encrypted JWT. Both core token release
+and host profile refresh refuse a bound session when the configured backend
+differs, before sending its credential. Restore the issuing backend or sign in
+again; a mismatch does not erase the stored session. API keys and local sessions
+retain their existing behavior. Legacy profiles without an association remain
+compatible and unbound because their issuing origin cannot be inferred.
+
+Browser hosts pass their captured origin to `login_with_token_for_backend` or
+`store_session_token_for_backend`. These reject a changed backend before any
+credential-bearing request and retain the accepted client through exchange,
+validation and persistence, so configuration changes cannot redirect a callback.
+
Four pieces stack up. `SessionManager` is the one hosts drive; it composes the
other three.
@@ -46,14 +60,14 @@ reads the stored token back through the link when it needs to refresh
then calls `store_session_token(jwt, None)`. Storing runs under a mutation
lock so two login or logout callbacks cannot interleave, and decides:
-| Case | Result |
-| --- | --- |
-| local offline token | stored as-is; a non-empty `user` payload is required |
-| JWT whose `exp` has passed | `SessionError::Expired`, nothing stored |
-| `/auth/me` confirms the JWT | pushed to the core with the backend's user; cache seeded |
-| `/auth/me` rejects the JWT | `SessionError::Rejected`, nothing stored |
+| Case | Result |
+| ------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
+| local offline token | stored as-is; a non-empty `user` payload is required |
+| JWT whose `exp` has passed | `SessionError::Expired`, nothing stored |
+| `/auth/me` confirms the JWT | pushed to the core with the backend's user; cache seeded |
+| `/auth/me` rejects the JWT | `SessionError::Rejected`, nothing stored |
| backend unreachable, JWT has a live `exp` and a user id | stored provisionally with `pendingBackendValidation: true`; a background loop revalidates |
-| backend unreachable, no live `exp` | `SessionError::Transient`, nothing stored |
+| backend unreachable, no live `exp` | `SessionError::Transient`, nothing stored |
Store-time validation (`SessionClient::validate_for_store`) bounds
`/auth/me` by a budget (12 s by default, `OPENHUMAN_AUTH_ME_TIMEOUT_MS`, with
@@ -101,16 +115,16 @@ attribution headers from `ClientHeaders` (`x-sdk-name`, plus
## Layout
-| Path | What it does |
-| --- | --- |
-| [`mod.rs`](mod.rs) | Module declarations and re-exports. |
-| [`manager.rs`](manager.rs) | `SessionManager`, `SessionState`, `SessionEvent`, `SessionError`; the login, store, logout, revalidation and current-user flows. |
-| [`client.rs`](client.rs) | `SessionClient` (login-token exchange, `GET /auth/me`, store-time validation), `ClientHeaders`, `SessionClientError`, `FetchMeError`, transient status and phrase classification. |
-| [`cache.rs`](cache.rs) | `CurrentUserCache`, `CachedUser`, TTL, backoff and fetch-timeout policy. |
-| [`link.rs`](link.rs) | `CoreLink`, `CoreAuthState`, the RPC method-name constants, and helpers (`push_credential`, `clear_credential`, `core_auth_state`, `core_session_token`, `resolve_backend_url`, `unwrap_envelope`). |
-| [`credential.rs`](credential.rs) | `Credential` and `CredentialKind` (`Session`, `ApiKey`, `Local`), `Credential::classify`, and the JWT and profile helpers (`decode_jwt_exp`, `jwt_is_live`, `user_id_from_jwt_claims`, `user_id_from_profile_payload`). |
-| [`identity.rs`](identity.rs) | Process-global user id (`set_user_id`, `peek_user_id`, `clear`) for Sentry `before_send` hooks that cannot await. Only the id is kept, never a token or profile. |
-| [`test_support.rs`](test_support.rs) | Axum stub backend and stub `CoreLink` for this module's tests (test builds only). |
+| Path | What it does |
+| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [`mod.rs`](mod.rs) | Module declarations and re-exports. |
+| [`manager.rs`](manager.rs) | `SessionManager`, `SessionState`, `SessionEvent`, `SessionError`; the login, store, logout, revalidation and current-user flows. |
+| [`client.rs`](client.rs) | `SessionClient` (login-token exchange, `GET /auth/me`, store-time validation), `ClientHeaders`, `SessionClientError`, `FetchMeError`, transient status and phrase classification. |
+| [`cache.rs`](cache.rs) | `CurrentUserCache`, `CachedUser`, TTL, backoff and fetch-timeout policy. |
+| [`link.rs`](link.rs) | `CoreLink`, `CoreAuthState`, the RPC method-name constants, and helpers (`push_credential`, `clear_credential`, `core_auth_state`, `core_session_token`, `resolve_backend_url`, `unwrap_envelope`). |
+| [`credential.rs`](credential.rs) | `Credential` and `CredentialKind` (`Session`, `ApiKey`, `Local`), `Credential::classify`, and the JWT and profile helpers (`decode_jwt_exp`, `jwt_is_live`, `user_id_from_jwt_claims`, `user_id_from_profile_payload`). |
+| [`identity.rs`](identity.rs) | Process-global user id (`set_user_id`, `peek_user_id`, `clear`) for Sentry `before_send` hooks that cannot await. Only the id is kept, never a token or profile. |
+| [`test_support.rs`](test_support.rs) | Axum stub backend and stub `CoreLink` for this module's tests (test builds only). |
## Key types and entry points
diff --git a/crates/openhuman-tinyhumans/src/session/client.rs b/crates/openhuman-tinyhumans/src/session/client.rs
index e780d0da6e..ee04a67685 100644
--- a/crates/openhuman-tinyhumans/src/session/client.rs
+++ b/crates/openhuman-tinyhumans/src/session/client.rs
@@ -238,18 +238,29 @@ pub struct SessionClient {
sdk: TinyHumansClient,
}
+/// Canonical non-secret backend origin shared by client construction and
+/// callers that pin the expected issuer before accepting a callback.
+pub(super) fn normalize_backend_origin(base_url: &str) -> Result<String, SessionClientError> {
+ let mut base = url::Url::parse(base_url.trim())
+ .map_err(|e| SessionClientError::InvalidBaseUrl(e.to_string()))?;
+ if !matches!(base.scheme(), "http" | "https")
+ || base.host_str().is_none()
+ || !base.username().is_empty()
+ || base.password().is_some()
+ {
+ return Err(SessionClientError::InvalidBaseUrl(
+ "must be an absolute http(s) URL with host".to_string(),
+ ));
+ }
+ base.set_path("");
+ base.set_query(None);
+ base.set_fragment(None);
+ Ok(base.as_str().trim_end_matches('/').to_string())
+}
+
impl SessionClient {
pub fn new(base_url: &str, headers: &ClientHeaders) -> Result<Self, SessionClientError> {
- let mut base = url::Url::parse(base_url.trim())
- .map_err(|e| SessionClientError::InvalidBaseUrl(e.to_string()))?;
- if !matches!(base.scheme(), "http" | "https") || base.host_str().is_none() {
- return Err(SessionClientError::InvalidBaseUrl(
- "must be an absolute http(s) URL with host".to_string(),
- ));
- }
- base.set_path("");
- base.set_query(None);
- base.set_fragment(None);
+ let base = normalize_backend_origin(base_url)?;
let http = openhuman_embed::__host::util::tls::tls_client_builder()
.http1_only()
@@ -261,10 +272,7 @@ impl SessionClient {
let sdk = TinyHumansClient::new(base.as_str())
.with_http_client(http)
.with_default_headers(headers.header_map());
- Ok(Self {
- base: base.as_str().trim_end_matches('/').to_string(),
- sdk,
- })
+ Ok(Self { base, sdk })
}
/// The normalised base URL (no trailing slash) — the cache key for
diff --git a/crates/openhuman-tinyhumans/src/session/client_tests.rs b/crates/openhuman-tinyhumans/src/session/client_tests.rs
index dc08ad8987..fa142dfffd 100644
--- a/crates/openhuman-tinyhumans/src/session/client_tests.rs
+++ b/crates/openhuman-tinyhumans/src/session/client_tests.rs
@@ -29,6 +29,10 @@ fn base_url_is_normalised_and_validated() {
SessionClient::new("ftp://x", &headers()),
Err(SessionClientError::InvalidBaseUrl(_))
));
+ assert!(matches!(
+ SessionClient::new("https://operator:[email protected]", &headers()),
+ Err(SessionClientError::InvalidBaseUrl(_))
+ ));
}
#[test]
diff --git a/crates/openhuman-tinyhumans/src/session/link.rs b/crates/openhuman-tinyhumans/src/session/link.rs
index 5085164992..adb7de441b 100644
--- a/crates/openhuman-tinyhumans/src/session/link.rs
+++ b/crates/openhuman-tinyhumans/src/session/link.rs
@@ -43,6 +43,9 @@ pub struct CoreAuthState {
/// RFC3339 expiry recorded from the JWT `exp`, when the core knows it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
+ /// Issuing backend for a bound session; absent for legacy sessions.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub issuing_backend: Option<String>,
}
impl CoreAuthState {
@@ -71,11 +74,26 @@ pub async fn push_credential<L: CoreLink + ?Sized>(
credential: &Credential,
user_id: Option<&str>,
user: Option<&Value>,
+) -> Result<CoreAuthState, String> {
+ push_bound_credential(link, credential, user_id, user, None).await
+}
+
+/// Hand over a credential with its issuing backend. Existing unbound callers
+/// remain compatible, and the core retains a prior association on refresh.
+pub async fn push_bound_credential<L: CoreLink + ?Sized>(
+ link: &L,
+ credential: &Credential,
+ user_id: Option<&str>,
+ user: Option<&Value>,
+ issuing_backend: Option<&str>,
) -> Result<CoreAuthState, String> {
let mut params = json!({
"token": credential.secret,
"kind": credential.kind.as_str(),
});
+ if let Some(backend) = issuing_backend {
+ params["issuingBackend"] = Value::String(backend.to_string());
+ }
if let Some(user_id) = user_id.map(str::trim).filter(|s| !s.is_empty()) {
params["userId"] = Value::String(user_id.to_string());
}
diff --git a/crates/openhuman-tinyhumans/src/session/link_tests.rs b/crates/openhuman-tinyhumans/src/session/link_tests.rs
index 94d18422d2..9e4968f190 100644
--- a/crates/openhuman-tinyhumans/src/session/link_tests.rs
+++ b/crates/openhuman-tinyhumans/src/session/link_tests.rs
@@ -23,6 +23,10 @@ fn core_auth_state_parses_camel_case_and_kind() {
assert!(state.is_authenticated);
assert_eq!(state.kind(), Some(CredentialKind::ApiKey));
assert_eq!(state.expires_at.as_deref(), Some("2100-01-01T00:00:00Z"));
+ assert!(
+ state.issuing_backend.is_none(),
+ "legacy DTOs remain compatible"
+ );
let signed_out: CoreAuthState =
serde_json::from_value(json!({ "isAuthenticated": false })).unwrap();
diff --git a/crates/openhuman-tinyhumans/src/session/manager.rs b/crates/openhuman-tinyhumans/src/session/manager.rs
index e906a48785..a6c00d7828 100644
--- a/crates/openhuman-tinyhumans/src/session/manager.rs
+++ b/crates/openhuman-tinyhumans/src/session/manager.rs
@@ -166,10 +166,17 @@ impl<L: CoreLink> SessionManager<L> {
credential: &Credential,
user_id: Option<&str>,
user: Option<&Value>,
+ issuing_backend: Option<&str>,
) -> Result<CoreAuthState, SessionError> {
- let state = link::push_credential(self.link.as_ref(), credential, user_id, user)
- .await
- .map_err(SessionError::Core)?;
+ let state = link::push_bound_credential(
+ self.link.as_ref(),
+ credential,
+ user_id,
+ user,
+ issuing_backend,
+ )
+ .await
+ .map_err(SessionError::Core)?;
identity::set_user_id(state.user_id.clone());
Ok(state)
}
@@ -186,11 +193,47 @@ impl<L: CoreLink> SessionManager<L> {
login_token: &str,
) -> Result<SessionState, SessionError> {
let client = self.client().await?;
+ self.login_with_client(login_token, client).await
+ }
+
+ /// Complete a browser callback only against its original backend.
+ /// The same captured client exchanges and validates the credential.
+ pub async fn login_with_token_for_backend(
+ self: &Arc<Self>,
+ login_token: &str,
+ expected_backend: &str,
+ ) -> Result<SessionState, SessionError> {
+ let client = self.client_for_expected_backend(expected_backend).await?;
+ self.login_with_client(login_token, client).await
+ }
+
+ async fn client_for_expected_backend(
+ &self,
+ expected_backend: &str,
+ ) -> Result<Arc<SessionClient>, SessionError> {
+ let expected = crate::session::client::normalize_backend_origin(expected_backend)
+ .map_err(|_| SessionError::Backend("invalid expected login backend".into()))?;
+ let client = self.client().await?;
+ if client.base_url() != expected {
+ return Err(SessionError::Backend(
+ "SESSION_BACKEND_MISMATCH: the backend changed during sign-in; start sign-in again"
+ .into(),
+ ));
+ }
+ Ok(client)
+ }
+
+ async fn login_with_client(
+ self: &Arc<Self>,
+ login_token: &str,
+ client: Arc<SessionClient>,
+ ) -> Result<SessionState, SessionError> {
let jwt = client
.consume_login_token(login_token)
.await
.map_err(|e| SessionError::ConsumeFailed(e.to_string()))?;
- self.store_session_token(&jwt, None).await
+ self.store_session_token_with_client(&jwt, None, Some(client))
+ .await
}
/// Store a session JWT (or a local offline token) after validating it.
@@ -206,6 +249,29 @@ impl<L: CoreLink> SessionManager<L> {
self: &Arc<Self>,
token: &str,
user: Option<Value>,
+ ) -> Result<SessionState, SessionError> {
+ self.store_session_token_with_client(token, user, None)
+ .await
+ }
+
+ /// Validate a browser callback against its expected issuer before sending
+ /// any credential. Configuration changes cannot change the captured client.
+ pub async fn store_session_token_for_backend(
+ self: &Arc<Self>,
+ token: &str,
+ user: Option<Value>,
+ expected_backend: &str,
+ ) -> Result<SessionState, SessionError> {
+ let client = self.client_for_expected_backend(expected_backend).await?;
+ self.store_session_token_with_client(token, user, Some(client))
+ .await
+ }
+
+ async fn store_session_token_with_client(
+ self: &Arc<Self>,
+ token: &str,
+ user: Option<Value>,
+ client: Option<Arc<SessionClient>>,
) -> Result<SessionState, SessionError> {
let guard = self.mutation.lock().await;
let credential = Credential::classify(token);
@@ -221,7 +287,7 @@ impl<L: CoreLink> SessionManager<L> {
));
}
self.cancel_revalidation();
- self.push(&credential, None, user.as_ref()).await?;
+ self.push(&credential, None, user.as_ref(), None).await?;
self.cache.forget();
drop(guard);
return self.changed().await;
@@ -234,7 +300,10 @@ impl<L: CoreLink> SessionManager<L> {
return Err(SessionError::Expired);
}
- let client = self.client().await?;
+ let client = match client {
+ Some(client) => client,
+ None => self.client().await?,
+ };
match client.validate_for_store(&credential).await {
Ok(me) => {
let user_id = user_id_from_profile_payload(&me)
@@ -251,8 +320,13 @@ impl<L: CoreLink> SessionManager<L> {
// provisional with nothing to confirm it, possibly
// indefinitely for an idle TUI or host (#6318 review
// follow-up).
- self.push(&credential, user_id.as_deref(), Some(&me))
- .await?;
+ self.push(
+ &credential,
+ user_id.as_deref(),
+ Some(&me),
+ Some(client.base_url()),
+ )
+ .await?;
self.cancel_revalidation();
self.cache.seed(&client, &credential, me);
drop(guard);
@@ -280,10 +354,15 @@ impl<L: CoreLink> SessionManager<L> {
);
let pending = json!({ PENDING_BACKEND_VALIDATION_FIELD: true });
self.cancel_revalidation();
- self.push(&credential, Some(&user_id), Some(&pending))
- .await?;
+ self.push(
+ &credential,
+ Some(&user_id),
+ Some(&pending),
+ Some(client.base_url()),
+ )
+ .await?;
self.cache.forget();
- self.spawn_revalidation(credential);
+ self.spawn_revalidation(credential, client.base_url().to_string());
drop(guard);
self.changed().await
}
@@ -298,12 +377,12 @@ impl<L: CoreLink> SessionManager<L> {
return Err(SessionError::Invalid("api key is required".to_string()));
}
self.cancel_revalidation();
- self.push(&credential, None, None).await?;
+ self.push(&credential, None, None, None).await?;
drop(guard);
self.changed().await
}
- fn spawn_revalidation(self: &Arc<Self>, credential: Credential) {
+ fn spawn_revalidation(self: &Arc<Self>, credential: Credential, issuing_backend: String) {
let manager = Arc::clone(self);
let handle = tokio::spawn(async move {
let mut delay = REVALIDATION_INITIAL_DELAY;
@@ -313,6 +392,11 @@ impl<L: CoreLink> SessionManager<L> {
delay = (delay * 2).min(REVALIDATION_MAX_DELAY);
continue;
};
+ if client.base_url() != issuing_backend {
+ // A pending credential must never be tested against a
+ // deployment other than the one it was submitted to.
+ return;
+ }
// The core is the store of record; if it no longer holds this
// token (logout, or a newer login), this loop is stale.
match link::core_session_token(manager.link.as_ref()).await {
@@ -345,7 +429,12 @@ impl<L: CoreLink> SessionManager<L> {
// forever despite a confirmed backend answer (#6318
// review follow-up).
match manager
- .push(&credential, user_id.as_deref(), Some(&me))
+ .push(
+ &credential,
+ user_id.as_deref(),
+ Some(&me),
+ Some(client.base_url()),
+ )
.await
{
Ok(_) => {
@@ -502,6 +591,14 @@ impl<L: CoreLink> SessionManager<L> {
if core.kind() != Some(CredentialKind::Session) {
return Ok(stored());
}
+ let client = self.client().await?;
+ if core
+ .issuing_backend
+ .as_deref()
+ .is_some_and(|issuing| issuing != client.base_url())
+ {
+ return Err(SessionError::Backend("SESSION_BACKEND_MISMATCH: stored session belongs to a different backend; restore its backend or sign in again".into()));
+ }
let Some(secret) = link::core_session_token(self.link.as_ref())
.await
.map_err(SessionError::Core)?
@@ -509,7 +606,6 @@ impl<L: CoreLink> SessionManager<L> {
return Ok(stored());
};
let credential = Credential::session(secret);
- let client = self.client().await?;
match self.cache.get_or_refresh(&client, &credential, force).await {
Ok(cached) => {
if cached.user.is_some() && user_is_pending(core.user.as_ref()) {
@@ -519,7 +615,12 @@ impl<L: CoreLink> SessionManager<L> {
if self.core_still_holds(&credential.secret).await {
let user_id = cached.user.as_ref().and_then(user_id_from_profile_payload);
if let Err(e) = self
- .push(&credential, user_id.as_deref(), cached.user.as_ref())
+ .push(
+ &credential,
+ user_id.as_deref(),
+ cached.user.as_ref(),
+ Some(client.base_url()),
+ )
.await
{
log::warn!(
diff --git a/crates/openhuman-tinyhumans/src/session/manager_tests.rs b/crates/openhuman-tinyhumans/src/session/manager_tests.rs
index 1689a1b01a..bdd7ca7122 100644
--- a/crates/openhuman-tinyhumans/src/session/manager_tests.rs
+++ b/crates/openhuman-tinyhumans/src/session/manager_tests.rs
@@ -7,10 +7,135 @@ use crate::session::test_support::{
};
use std::sync::Arc;
+#[tokio::test]
+async fn bound_session_restores_only_at_issuing_backend_without_forwarding() {
+ let _global = ENV_LOCK.lock().await;
+ let issuer = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
+ let other = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
+ let core = FakeCore::new(&issuer.url);
+ let first = manager(&core);
+ first.store_session_token(&LIVE_JWT, None).await.unwrap();
+ assert_eq!(
+ core.session().unwrap().issuing_backend.as_deref(),
+ Some(issuer.url.as_str())
+ );
+ let restored = manager(&core);
+ restored.current_user(true).await.unwrap();
+ assert_eq!(issuer.me_calls(), 2);
+ *core.api_url.lock().unwrap() = other.url.clone();
+ let error = restored.current_user(true).await.unwrap_err();
+ assert!(
+ matches!(error, SessionError::Backend(ref message) if message.contains("SESSION_BACKEND_MISMATCH"))
+ );
+ assert_eq!(
+ other.me_calls(),
+ 0,
+ "no Authorization may reach the changed backend"
+ );
+ assert!(other.consume_calls().is_empty());
+ assert!(
+ core.session().is_some(),
+ "restore does not erase a session for another deployment"
+ );
+}
+
+#[tokio::test]
+async fn expected_backend_rejects_changed_configuration_before_any_credential_send() {
+ let _global = ENV_LOCK.lock().await;
+ let issuer = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
+ let changed = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
+ let core = FakeCore::new(&changed.url);
+ let manager = manager(&core);
+ for result in [
+ manager
+ .login_with_token_for_backend("synthetic-one-time", &issuer.url)
+ .await,
+ manager
+ .store_session_token_for_backend(&LIVE_JWT, None, &issuer.url)
+ .await,
+ ] {
+ assert!(
+ matches!(result, Err(SessionError::Backend(ref message)) if message.starts_with("SESSION_BACKEND_MISMATCH"))
+ );
+ }
+ assert_eq!(changed.me_calls(), 0);
+ assert!(changed.consume_calls().is_empty());
+ assert_eq!(issuer.me_calls(), 0);
+ assert!(issuer.consume_calls().is_empty());
+ assert!(core.session().is_none());
+ *core.api_url.lock().unwrap() = issuer.url.clone();
+ manager
+ .store_session_token_for_backend(
+ &LIVE_JWT,
+ None,
+ &format!("{}/ignored-path?discarded=nonsecret#fragment", issuer.url),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ issuer.me_calls(),
+ 1,
+ "matching canonical origin accepts the callback"
+ );
+}
+
fn manager(core: &Arc<FakeCore>) -> Arc<SessionManager<FakeCore>> {
SessionManager::new(Arc::clone(core), ClientHeaders::new("openhuman"))
}
+#[tokio::test]
+async fn exchange_and_validation_use_one_backend_when_configuration_changes() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ struct SwitchingLink {
+ core: Arc<FakeCore>,
+ changed_url: String,
+ reads: AtomicUsize,
+ }
+ #[async_trait::async_trait]
+ impl CoreLink for SwitchingLink {
+ async fn invoke(&self, method: &str, params: Value) -> Result<Value, String> {
+ if method == link::CONFIG_RESOLVE_API_URL
+ && self.reads.fetch_add(1, Ordering::SeqCst) > 0
+ {
+ return Ok(json!({"api_url":self.changed_url}));
+ }
+ self.core.invoke(method, params).await
+ }
+ }
+ let _global = ENV_LOCK.lock().await;
+ let issuer = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
+ let other = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
+ let core = FakeCore::new(&issuer.url);
+ let manager = SessionManager::new(
+ Arc::new(SwitchingLink {
+ core: core.clone(),
+ changed_url: other.url.clone(),
+ reads: AtomicUsize::new(0),
+ }),
+ ClientHeaders::new("openhuman"),
+ );
+ assert!(matches!(
+ manager.login_with_token("synthetic-one-time").await,
+ Err(SessionError::Backend(_))
+ ));
+ assert_eq!(issuer.consume_calls().len(), 1);
+ assert_eq!(
+ issuer.me_calls(),
+ 1,
+ "validation stays with the exchange client"
+ );
+ assert_eq!(
+ other.me_calls(),
+ 0,
+ "the new JWT never reaches the changed backend"
+ );
+ assert!(other.consume_calls().is_empty());
+ assert_eq!(
+ core.session().unwrap().issuing_backend.as_deref(),
+ Some(issuer.url.as_str())
+ );
+}
+
async fn drain(rx: &mut tokio::sync::broadcast::Receiver<SessionEvent>) -> Vec<SessionEvent> {
let mut out = Vec::new();
while let Ok(event) = rx.try_recv() {
@@ -137,15 +262,15 @@ async fn failed_core_handoff_keeps_the_prior_pending_session_revalidation_runnin
// A is stored pending because the backend is unreachable; its own
// background revalidation loop starts.
- let core = FakeCore::new("http://127.0.0.1:9");
+ let backend = Backend::start(vec![MeAnswer::Status(503)]).await;
+ let core = FakeCore::new(&backend.url);
let m = manager(&core);
m.store_session_token(&LIVE_JWT, None).await.unwrap();
assert!(m.revalidation.lock().unwrap().is_some());
// The backend becomes reachable and confirms the token via /auth/me
// (the successful-validation arm), but the core handoff itself fails.
- let backend = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
- *core.api_url.lock().unwrap() = backend.url.clone();
+ *backend.state.me.lock().unwrap() = vec![MeAnswer::Ok(me_user())].into();
*core.fail_method.lock().unwrap() = Some(link::AUTH_SET_CREDENTIAL.to_string());
assert!(matches!(
@@ -170,15 +295,15 @@ async fn failed_core_handoff_keeps_the_prior_pending_session_revalidation_runnin
async fn a_failed_confirmation_handoff_keeps_the_revalidation_loop_retrying() {
let _global = ENV_LOCK.lock().await;
- let core = FakeCore::new("http://127.0.0.1:9");
+ let backend = Backend::start(vec![MeAnswer::Status(503)]).await;
+ let core = FakeCore::new(&backend.url);
let m = manager(&core);
m.store_session_token(&LIVE_JWT, None).await.unwrap();
assert!(m.revalidation.lock().unwrap().is_some());
// The backend becomes reachable and will confirm the token, but the
// core handoff itself fails.
- let backend = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
- *core.api_url.lock().unwrap() = backend.url.clone();
+ *backend.state.me.lock().unwrap() = vec![MeAnswer::Ok(me_user())].into();
*core.fail_method.lock().unwrap() = Some(link::AUTH_SET_CREDENTIAL.to_string());
// Let the loop's first attempt (after REVALIDATION_INITIAL_DELAY) run.
@@ -437,6 +562,7 @@ async fn clearing_a_rejected_session_reports_a_surviving_api_key() {
token: LIVE_JWT.clone(),
user_id: Some("user-123".to_string()),
user: Some(me_user()),
+ issuing_backend: None,
});
*core.api_key.lock().unwrap() = Some("sk-fallback".to_string());
let m = manager(&core);
@@ -475,6 +601,7 @@ async fn current_user_confirms_a_pending_session_once_the_backend_answers() {
token: LIVE_JWT.clone(),
user_id: Some("user-123".into()),
user: Some(serde_json::json!({ PENDING_BACKEND_VALIDATION_FIELD: true })),
+ issuing_backend: None,
});
let m = manager(&core);
let current = m.current_user(false).await.unwrap();
@@ -511,6 +638,7 @@ async fn rejection_of_a_superseded_token_leaves_the_new_session_alone() {
token: crate::session::test_support::LIVE_JWT_NO_SUB.clone(),
user_id: Some("user-456".into()),
user: Some(serde_json::json!({ "_id": "user-456" })),
+ issuing_backend: None,
};
*core.session.lock().unwrap() = Some(replacement.clone());
let current = refresh.await.unwrap().unwrap();
@@ -565,6 +693,7 @@ async fn pending_confirmation_after_logout_does_not_restore_the_session() {
token: LIVE_JWT.clone(),
user_id: Some("user-123".into()),
user: Some(serde_json::json!({ PENDING_BACKEND_VALIDATION_FIELD: true })),
+ issuing_backend: None,
});
let m = manager(&core);
let refresh = {
diff --git a/crates/openhuman-tinyhumans/src/session/test_support.rs b/crates/openhuman-tinyhumans/src/session/test_support.rs
index 9ab8420605..aeda0d556e 100644
--- a/crates/openhuman-tinyhumans/src/session/test_support.rs
+++ b/crates/openhuman-tinyhumans/src/session/test_support.rs
@@ -201,6 +201,7 @@ pub struct StoredCredential {
pub token: String,
pub user_id: Option<String>,
pub user: Option<Value>,
+ pub issuing_backend: Option<String>,
}
/// A [`CoreLink`] that behaves like the core's `auth.*` credential RPCs,
@@ -252,6 +253,7 @@ impl FakeCore {
"userId": s.user_id,
"user": s.user,
"profileId": "app-session:default",
+ "issuingBackend": s.issuing_backend,
}),
None => {
json!({ "isAuthenticated": false, "userId": null, "user": null, "profileId": null })
@@ -309,6 +311,10 @@ impl CoreLink for FakeCore {
.and_then(Value::as_str)
.map(str::to_string),
user: params.get("user").cloned(),
+ issuing_backend: params
+ .get("issuingBackend")
+ .and_then(Value::as_str)
+ .map(str::to_string),
});
}
Ok(self.state())
diff --git a/crates/openhuman-tui/Cargo.toml b/crates/openhuman-tui/Cargo.toml
index cb6e2be145..56f4dddbee 100644
--- a/crates/openhuman-tui/Cargo.toml
+++ b/crates/openhuman-tui/Cargo.toml
@@ -68,7 +68,7 @@ log = "0.4"
ratatui = "0.30"
serde_json = "1"
async-trait = "0.1"
-tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] }
+tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "net", "io-util"] }
unicode-width = "0.2"
uuid = { version = "1", features = ["v4"] }
zeroize = "1"
diff --git a/crates/openhuman-tui/README.md b/crates/openhuman-tui/README.md
index 9697a3308a..330dc70628 100644
--- a/crates/openhuman-tui/README.md
+++ b/crates/openhuman-tui/README.md
@@ -63,12 +63,24 @@ default background. Dark, Light, and Monochrome are selectable with `/themes`;
## Login, agents, and activity
-`/login` opens masked one-time-token entry in Settings. Credential exchange and
-validation remain in `openhuman_tinyhumans::SessionManager`; the frontend only
-hands it the token. Sign-in runs in the background with a deadline, and secret
-buffers are zeroized. Account changes clear the prior account's draft/cache and
-start a new account-owned conversation. Product login is distinct from an
-inference provider's key configuration.
+`/login` opens a provider picker (Google, GitHub, Twitter, Discord);
+`/login google` starts that provider directly. Like Medulla, this opens the
+TinyHumans browser flow with a nonce-protected, ephemeral loopback callback.
+Credential exchange, profile validation, encrypted persistence, and account
+adoption remain in `openhuman_tinyhumans::SessionManager`. The TUI never renders
+tokens. Login and saved-account validation run in the background; the callback
+expires after five minutes. Settings has mouse controls to reopen the browser,
+copy its link via OSC52 (terminal support required), or cancel. Esc also cancels.
+Already accepted callbacks finish their atomic session update.
+
+Over SSH, forward the callback port shown in Settings before opening the copied
+link locally: `ssh -L <port>:127.0.0.1:<port> <host>`. `/login-token` retains
+masked one-time-token entry as a fallback. New sessions record the issuing
+backend origin; changing backends cannot send that JWT to a different origin.
+Restore the original backend or sign in again. Legacy sessions without origin
+metadata remain compatible. Expired sessions clear the account display; account
+changes discard prior-account drafts and create an account-owned conversation.
+Product login is distinct from an inference provider's key configuration.
`/agents` loads runnable profiles and writes `config.update_agent_settings`'s
`chat_agent_id` after selection. This is the core's configured chat agent for
@@ -99,8 +111,9 @@ off; stored tiers have no enforcement effect until that policy is enabled.
## Rendering and input
-The loop redraws only dirty state or active animation. Streaming paints are
-coalesced. Settled blocks are wrapped once per content revision and width;
+The loop redraws only dirty state or active animation. Live paints are
+coalesced at 16 ms. The bottom-anchored composer reflows on resize while the
+transcript retains its scroll anchor. Settled blocks are wrapped once per content revision and width;
wide row offsets avoid 16-bit history overflow. Only viewport rows are copied
into the frame, and formatted blocks far from the viewport are evicted while
their height metadata and underlying transcript remain available.
@@ -112,6 +125,12 @@ Large tool previews are bounded; display truncation never deletes core history.
Absolute performance budgets in the design spec are targets, not benchmark
claims about every terminal or platform.
+`./target/debug/openhuman-tui --bench` measures the viewport and production
+renderer offline. `python3 scripts/debug/tui-profile.py --mode live` measures
+real terminal input-to-paint, idle CPU/output, and RSS in an isolated workspace
+without signing in or sending a model prompt. See
+[measured results and limits](../../docs/performance/tui-viewport.md).
+
## Source map
| Path under `src/` | Responsibility |
diff --git a/crates/openhuman-tui/src/account.rs b/crates/openhuman-tui/src/account.rs
new file mode 100644
index 0000000000..d4a5ff0bec
--- /dev/null
+++ b/crates/openhuman-tui/src/account.rs
@@ -0,0 +1,322 @@
+//! Asynchronous account UI over the shared TinyHumans session owner.
+use super::{
+ cockpit::{Overlay, OverlayKind},
+ session::{BrowserLogin, LoginCancellation, LoginProvider},
+ ui_state::{AppTab, UiState},
+};
+use openhuman_rpc::{embed::CoreRuntime, tinyhumans::SessionState};
+use std::{sync::Arc, time::Duration};
+use zeroize::Zeroizing;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum Operation {
+ Login,
+ Logout,
+ Refresh,
+}
+
+/// Messages carry display state only; credentials stay in SessionManager.
+pub enum Message {
+ BrowserReady {
+ generation: u64,
+ url: Zeroizing<String>,
+ port: u16,
+ cancel: LoginCancellation,
+ },
+ Finished {
+ generation: u64,
+ operation: Operation,
+ result: Result<SessionState, String>,
+ },
+}
+
+pub fn picker(ui: &mut UiState) {
+ if ui.auth_pending {
+ ui.active_tab = AppTab::Settings;
+ return;
+ }
+ let mut overlay = Overlay::new(OverlayKind::Login, "Sign in to TinyHumans");
+ overlay.rows = [
+ ("google", "Google"),
+ ("github", "GitHub"),
+ ("twitter", "Twitter / X"),
+ ("discord", "Discord"),
+ ]
+ .into_iter()
+ .map(|(id, label)| {
+ super::presentation::row(
+ id,
+ format!("Continue with {label}"),
+ "Opens your browser; returns securely to this TUI",
+ )
+ })
+ .collect();
+ overlay.status = "Select a provider · /login-token is the manual fallback · Esc closes".into();
+ ui.overlay = Some(overlay);
+ ui.focus = 0;
+}
+
+pub fn provider(id: &str) -> Option<LoginProvider> {
+ match id {
+ "google" => Some(LoginProvider::Google),
+ "github" => Some(LoginProvider::Github),
+ "twitter" => Some(LoginProvider::Twitter),
+ "discord" => Some(LoginProvider::Discord),
+ _ => None,
+ }
+}
+
+/// Open one account form without covering controls for an in-flight session update.
+pub fn form(ui: &mut UiState, logout: bool) {
+ ui.active_tab = AppTab::Settings;
+ if ui.auth_pending {
+ return;
+ }
+ ui.overlay = None;
+ ui.logout_confirm = logout;
+ ui.login_token = (!logout).then(String::new);
+}
+
+fn begin(
+ ui: &mut UiState,
+ operation: Operation,
+) -> Option<(u64, tokio::sync::mpsc::UnboundedSender<Message>)> {
+ if ui.auth_pending {
+ return None;
+ }
+ let tx = ui.auth_tx.clone()?;
+ ui.auth_generation = ui.auth_generation.wrapping_add(1);
+ if operation != Operation::Refresh {
+ ui.auth_pending = true;
+ ui.auth_browser = false;
+ ui.auth_operation = Some(operation);
+ }
+ Some((ui.auth_generation, tx))
+}
+
+pub fn browser(runtime: &Arc<CoreRuntime>, ui: &mut UiState, provider: LoginProvider) {
+ let Some((generation, tx)) = begin(ui, Operation::Login) else {
+ return;
+ };
+ ui.auth_browser = true;
+ ui.active_tab = AppTab::Settings;
+ ui.overlay = None;
+ ui.settings_status = "Starting secure browser sign-in…".into();
+ let manager = super::session::session_manager(runtime);
+ tokio::spawn(async move {
+ let result = match BrowserLogin::start(manager, provider).await {
+ Ok(login) => {
+ let cancel = login.cancellation();
+ if tx
+ .send(Message::BrowserReady {
+ generation,
+ url: Zeroizing::new(login.login_url().to_string()),
+ port: login.callback_port(),
+ cancel,
+ })
+ .is_err()
+ {
+ return;
+ }
+ login.wait(Duration::from_secs(300)).await
+ }
+ Err(error) => Err(error),
+ };
+ let _ = tx.send(Message::Finished {
+ generation,
+ operation: Operation::Login,
+ result,
+ });
+ });
+}
+
+pub fn token(runtime: &Arc<CoreRuntime>, ui: &mut UiState, token: Zeroizing<String>) {
+ let Some((generation, tx)) = begin(ui, Operation::Login) else {
+ return;
+ };
+ ui.settings_status = "Verifying sign-in…".into();
+ let manager = super::session::session_manager(runtime);
+ tokio::spawn(async move {
+ let result = manager
+ .login_with_token(token.trim())
+ .await
+ .map_err(|_| "The login token was not accepted. Please try again.".into());
+ let _ = tx.send(Message::Finished {
+ generation,
+ operation: Operation::Login,
+ result,
+ });
+ });
+}
+
+pub fn refresh(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {
+ let Some((generation, tx)) = begin(ui, Operation::Refresh) else {
+ return;
+ };
+ ui.settings_status = "Refreshing the saved account in the background…".into();
+ let manager = super::session::session_manager(runtime);
+ tokio::spawn(async move {
+ let result = super::session::refresh_session(&manager).await;
+ let _ = tx.send(Message::Finished {
+ generation,
+ operation: Operation::Refresh,
+ result,
+ });
+ });
+}
+
+pub fn logout(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {
+ let Some((generation, tx)) = begin(ui, Operation::Logout) else {
+ return;
+ };
+ ui.logout_confirm = false;
+ ui.settings_status = "Signing out…".into();
+ let manager = super::session::session_manager(runtime);
+ tokio::spawn(async move {
+ let result = manager
+ .logout()
+ .await
+ .map_err(|_| "Could not clear the saved session. Please retry.".into());
+ let _ = tx.send(Message::Finished {
+ generation,
+ operation: Operation::Logout,
+ result,
+ });
+ });
+}
+
+pub fn cancel(ui: &mut UiState) {
+ if let Some(cancel) = &ui.login_cancel {
+ cancel.cancel();
+ ui.settings_status =
+ "Cancellation requested. An already accepted callback finishes its session update."
+ .into();
+ } else if ui.auth_pending
+ && ui.auth_browser
+ && ui.auth_operation == Some(Operation::Login)
+ && ui.login_url.is_none()
+ {
+ ui.auth_generation = ui.auth_generation.wrapping_add(1);
+ ui.auth_pending = false;
+ ui.auth_operation = None;
+ ui.settings_status = "Sign-in cancelled.".into();
+ } else if ui.auth_pending {
+ ui.settings_status = "Session update already started; waiting for it to finish.".into();
+ }
+}
+
+pub fn apply_session(state: &SessionState, ui: &mut UiState) {
+ let changed = ui.auth_user_id != state.core.user_id
+ || ui.auth_profile_id != state.core.profile_id
+ || ui.authenticated != state.core.is_authenticated;
+ ui.auth_user_id = state.core.user_id.clone();
+ ui.auth_profile_id = state.core.profile_id.clone();
+ ui.authenticated = state.core.is_authenticated;
+ ui.identity_changed |= changed;
+ ui.auth_summary = if state.core.is_authenticated {
+ match state.core.credential.as_deref() {
+ Some("api-key") => "API key configured",
+ Some("local") => "Local session",
+ _ => {
+ if pending_validation(state) {
+ "Session saved · validation pending"
+ } else if state.current_user_stale {
+ "Signed in · cached profile"
+ } else {
+ "Signed in"
+ }
+ }
+ }
+ } else {
+ "Signed out"
+ }
+ .into();
+ let user = state
+ .core
+ .is_authenticated
+ .then(|| state.current_user.as_ref().or(state.core.user.as_ref()))
+ .flatten();
+ ui.account_detail = user
+ .map(super::controls::account_detail)
+ .unwrap_or_default();
+}
+
+pub fn apply(message: Message, ui: &mut UiState) {
+ match message {
+ Message::BrowserReady {
+ generation,
+ url,
+ port,
+ cancel,
+ } => {
+ if generation != ui.auth_generation || !ui.auth_pending {
+ cancel.cancel();
+ return;
+ }
+ ui.login_url = Some(url);
+ ui.login_port = Some(port);
+ ui.login_cancel = Some(cancel);
+ ui.settings_status=format!("Waiting for your browser (up to 5 minutes).\nCallback port: {port} on this machine. Over SSH, forward this port before opening the copied link.\nO opens the browser · C copies the link · Esc cancels.");
+ reopen(ui);
+ }
+ Message::Finished {
+ generation,
+ operation,
+ result,
+ } => {
+ if generation != ui.auth_generation {
+ return;
+ }
+ if operation != Operation::Refresh {
+ ui.auth_pending = false;
+ ui.auth_operation = None;
+ ui.login_url = None;
+ ui.login_port = None;
+ ui.login_cancel = None;
+ }
+ match result {
+ Ok(state) => {
+ apply_session(&state, ui);
+ ui.settings_status = if operation == Operation::Logout {
+ "Signed out. Your session was cleared.".into()
+ } else if pending_validation(&state) {
+ "Session saved. Backend validation will retry in the background.".into()
+ } else if state.current_user_stale {
+ "Using the saved account while the backend is unreachable.".into()
+ } else if state.core.is_authenticated {
+ "Account ready.".into()
+ } else {
+ "Sign in with a browser or use your configured local/provider access."
+ .into()
+ };
+ }
+ Err(error) => ui.settings_status = error,
+ }
+ }
+ }
+}
+
+fn pending_validation(state: &SessionState) -> bool {
+ state
+ .core
+ .user
+ .as_ref()
+ .and_then(|user| user.get("pendingBackendValidation"))
+ .and_then(serde_json::Value::as_bool)
+ == Some(true)
+}
+
+pub fn reopen(ui: &mut UiState) {
+ if let Some(url) = &ui.login_url {
+ if let Err(error) = super::session::open_browser(url) {
+ ui.settings_status = format!(
+ "{error}\nUse Copy link; if remote, forward callback port {}.",
+ ui.login_port.unwrap_or(0)
+ );
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "account_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-tui/src/account_tests.rs b/crates/openhuman-tui/src/account_tests.rs
new file mode 100644
index 0000000000..c17b97a2d4
--- /dev/null
+++ b/crates/openhuman-tui/src/account_tests.rs
@@ -0,0 +1,111 @@
+use super::*;
+use openhuman_rpc::tinyhumans::link::CoreAuthState;
+#[test]
+fn cached_profile_is_visible_without_leaking_credentials_or_resetting_same_account() {
+ let mut ui = UiState::new("t".into(), "c".into());
+ let state = SessionState {
+ core: CoreAuthState {
+ is_authenticated: true,
+ user_id: Some("user".into()),
+ credential: Some("session".into()),
+ ..Default::default()
+ },
+ current_user: Some(
+ serde_json::json!({"firstName":"Ada","email":"[email protected]","token":"must-not-display"}),
+ ),
+ current_user_stale: true,
+ ..Default::default()
+ };
+ apply_session(&state, &mut ui);
+ assert!(ui.identity_changed);
+ assert!(ui.auth_summary.contains("cached"));
+ assert!(!ui.account_detail.contains("must-not-display"));
+ ui.identity_changed = false;
+ apply_session(&state, &mut ui);
+ assert!(!ui.identity_changed);
+}
+#[test]
+fn stale_login_completion_cannot_replace_a_newer_account_operation() {
+ let mut ui = UiState::new("t".into(), "c".into());
+ ui.auth_generation = 2;
+ apply(
+ Message::Finished {
+ generation: 1,
+ operation: Operation::Login,
+ result: Ok(SessionState::default()),
+ },
+ &mut ui,
+ );
+ assert!(!ui.identity_changed);
+}
+#[test]
+fn signout_clears_visible_account_and_requests_context_reset() {
+ let mut ui = UiState::new("t".into(), "c".into());
+ ui.authenticated = true;
+ ui.auth_user_id = Some("old".into());
+ ui.account_detail = "old profile".into();
+ apply_session(&SessionState::default(), &mut ui);
+ assert!(ui.identity_changed);
+ assert!(ui.account_detail.is_empty());
+ assert_eq!(ui.auth_summary, "Signed out");
+}
+
+#[test]
+fn signed_out_state_does_not_display_a_leftover_cached_profile() {
+ let mut ui = UiState::new("t".into(), "c".into());
+ let state = SessionState {
+ current_user: Some(serde_json::json!({"email":"[email protected]"})),
+ ..Default::default()
+ };
+ apply_session(&state, &mut ui);
+ assert!(ui.account_detail.is_empty());
+ assert_eq!(ui.auth_summary, "Signed out");
+}
+#[test]
+fn cancellation_does_not_detach_an_inflight_token_session_update() {
+ let mut ui = UiState::new("t".into(), "c".into());
+ ui.auth_pending = true;
+ ui.auth_operation = Some(Operation::Login);
+ ui.auth_generation = 4;
+ cancel(&mut ui);
+ assert!(ui.auth_pending);
+ assert_eq!(ui.auth_generation, 4);
+ ui.auth_browser = true;
+ cancel(&mut ui);
+ assert!(!ui.auth_pending);
+ assert_eq!(ui.auth_generation, 5);
+}
+#[test]
+fn pending_browser_forms_cannot_block_mouse_login_controls() {
+ let mut ui = UiState::new("t".into(), "c".into());
+ ui.auth_pending = true;
+ ui.auth_browser = true;
+ for logout in [false, true] {
+ form(&mut ui, logout);
+ assert_eq!(ui.active_tab, AppTab::Settings);
+ assert!(ui.login_token.is_none());
+ assert!(!ui.logout_confirm);
+ }
+ ui.auth_pending = false;
+ form(&mut ui, false);
+ assert_eq!(ui.login_token.as_deref(), Some(""));
+ form(&mut ui, true);
+ assert!(ui.logout_confirm);
+ assert!(ui.login_token.is_none());
+}
+#[test]
+fn provisional_offline_session_is_not_presented_as_a_verified_account() {
+ let mut ui = UiState::new("t".into(), "c".into());
+ let state = SessionState {
+ core: CoreAuthState {
+ is_authenticated: true,
+ credential: Some("session".into()),
+ user: Some(serde_json::json!({"pendingBackendValidation":true})),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ apply_session(&state, &mut ui);
+ assert_eq!(ui.auth_summary, "Session saved · validation pending");
+ assert!(ui.account_detail.is_empty());
+}
diff --git a/crates/openhuman-tui/src/app.rs b/crates/openhuman-tui/src/app.rs
index 0942048e3d..2a51a131a1 100644
--- a/crates/openhuman-tui/src/app.rs
+++ b/crates/openhuman-tui/src/app.rs
@@ -66,6 +66,8 @@ pub async fn run(
let mut state = TranscriptState::new(client_id.clone());
state.set_thread(thread_id.clone());
let mut ui = UiState::new(thread_id, client_id.clone());
+ let manager = super::session::session_manager(&runtime);
+ let mut session_rx = manager.subscribe();
let (overlay_tx, mut overlay_rx) = tokio::sync::mpsc::unbounded_channel();
ui.overlay_tx = Some(overlay_tx);
let (auth_tx, mut auth_rx) = tokio::sync::mpsc::unbounded_channel();
@@ -77,6 +79,7 @@ pub async fn run(
}
super::controls::refresh_config(&runtime, &mut ui).await;
super::controls::refresh_auth(&runtime, &mut ui).await;
+ ui.identity_changed = false; // Startup is already bound to this persisted identity.
refresh_agent_paths(&runtime, &mut ui).await;
if options.resume_picker {
open_rpc_overlay(
@@ -96,6 +99,7 @@ pub async fn run(
// locked config must never strand the user on a blank raw-mode screen.
let mut guard = TerminalGuard::enter_with_options(!options.no_alt_screen)?;
guard.set_mouse(ui.mouse_enabled)?;
+ super::account::refresh(&runtime, &mut ui);
if let Some(prompt) = options.initial_prompt {
ui.composer.set_text(prompt);
@@ -130,7 +134,7 @@ pub async fn run(
let mut last_draw = std::time::Instant::now() - Duration::from_secs(1);
while !quit {
- if dirty && last_draw.elapsed() >= Duration::from_millis(33) {
+ if dirty && last_draw.elapsed() >= Duration::from_millis(16) {
guard.set_mouse(ui.mouse_enabled)?;
guard
.terminal()
@@ -140,12 +144,14 @@ pub async fn run(
}
tokio::select! {
- _ = tokio::time::sleep_until(tokio::time::Instant::from_std(last_draw+Duration::from_millis(33))), if dirty => {},
- Some(result)=auth_rx.recv()=>{
- ui.auth_pending=false;
- match result {
- Ok(())=>{ui.settings_status="Signed in.".into();super::controls::refresh_auth(&runtime,&mut ui).await;ui.identity_changed=true;},
- Err(error)=>{ui.settings_status=format!("Sign-in failed: {error}");ui.login_token=Some(String::new());ui.active_tab=AppTab::Settings;}
+ _ = tokio::time::sleep_until(tokio::time::Instant::from_std(last_draw+Duration::from_millis(16))), if dirty => {},
+ Some(message)=auth_rx.recv()=>{super::account::apply(message,&mut ui);dirty=true;},
+ event=session_rx.recv()=>{
+ match event {
+ Ok(openhuman_rpc::tinyhumans::SessionEvent::Changed(session))=>super::account::apply_session(&session,&mut ui),
+ Ok(openhuman_rpc::tinyhumans::SessionEvent::Expired {..})=>{ui.auth_summary="Session expired".into();ui.auth_user_id=None;ui.auth_profile_id=None;ui.authenticated=false;ui.account_detail.clear();ui.identity_changed=true;ui.settings_status="Your saved session was rejected. Sign in again.".into();},
+ Err(broadcast::error::RecvError::Lagged(_))=>super::account::refresh(&runtime,&mut ui),
+ Err(broadcast::error::RecvError::Closed)=>{},
} dirty=true;
},
Some(reply)=overlay_rx.recv()=>{super::effects::apply(reply,&mut ui);dirty=true;},
@@ -192,8 +198,12 @@ pub async fn run(
ui.model_override = None;
ui.viewport = Default::default();
ui.overlay = None;
+ ui.thread_id.clear();
+ ui.action_dir.clear();
+ ui.scroll_from_bottom = 0;
state = TranscriptState::new(client_id.clone());
super::controls::refresh_config(&runtime, &mut ui).await;
+ refresh_agent_paths(&runtime, &mut ui).await;
new_thread(&runtime, &mut state, &mut ui).await;
dirty = true;
}
@@ -219,6 +229,10 @@ async fn handle_key(
return false;
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
+ if ui.auth_pending && key.code == KeyCode::Esc {
+ super::account::cancel(ui);
+ return false;
+ }
if ui.active_tab == AppTab::Chat
&& ui.overlay.is_none()
@@ -553,7 +567,11 @@ async fn send_or_command(
}
let text = ui.composer.text().trim().to_string();
if let Some(command) = text.strip_prefix('/') {
- let _ = ui.composer.take_for_send();
+ if command.starts_with("login") {
+ ui.composer.clear();
+ } else {
+ let _ = ui.composer.take_for_send();
+ }
return execute_command(command, runtime, client_id, state, ui).await;
}
let mode = if state.is_streaming() {
diff --git a/crates/openhuman-tui/src/app/commands.rs b/crates/openhuman-tui/src/app/commands.rs
index 4a9d873e57..7fdc979912 100644
--- a/crates/openhuman-tui/src/app/commands.rs
+++ b/crates/openhuman-tui/src/app/commands.rs
@@ -262,14 +262,21 @@ pub(super) async fn execute_command(
"config" => ui.active_tab = AppTab::Config,
"settings" => ui.active_tab = AppTab::Settings,
"login" => {
- ui.active_tab = AppTab::Settings;
- ui.login_token = Some(String::new());
- ui.overlay = None;
+ if let Some(provider) = crate::account::provider(&argument) {
+ crate::account::browser(runtime, ui, provider);
+ } else {
+ crate::account::picker(ui);
+ }
+ }
+ "login-token" => {
+ crate::account::form(ui, false);
}
+ "login-cancel" => crate::account::cancel(ui),
+ "login-open" => crate::account::reopen(ui),
+ "login-copy" => crate::controls::copy_login_link(ui),
"plan" => present_pending_plan_review(ui),
"logout" => {
- ui.active_tab = AppTab::Settings;
- ui.logout_confirm = true;
+ crate::account::form(ui, true);
}
_ => state.push_system(format!("Unknown command /{command}. Type /help.")),
}
diff --git a/crates/openhuman-tui/src/app/events.rs b/crates/openhuman-tui/src/app/events.rs
index 4532b4e106..7c9a3fa2a1 100644
--- a/crates/openhuman-tui/src/app/events.rs
+++ b/crates/openhuman-tui/src/app/events.rs
@@ -6,7 +6,8 @@ pub(super) fn handle_web_event(
state: &mut TranscriptState,
ui: &mut UiState,
) {
- if ev.client_id != state.client_id() || ev.thread_id != ui.thread_id {
+ if ui.thread_id.is_empty() || ev.client_id != state.client_id() || ev.thread_id != ui.thread_id
+ {
return;
}
if matches!(ev.event.as_str(), "chat_done" | "chat_error") {
diff --git a/crates/openhuman-tui/src/app/overlays.rs b/crates/openhuman-tui/src/app/overlays.rs
index 6e314f6267..32dd4cd118 100644
--- a/crates/openhuman-tui/src/app/overlays.rs
+++ b/crates/openhuman-tui/src/app/overlays.rs
@@ -196,6 +196,13 @@ pub(super) async fn handle_overlay_key(
.cloned()
.cloned();
match kind {
+ OverlayKind::Login => {
+ if let Some(row) = selected {
+ if let Some(provider) = crate::account::provider(&row.id) {
+ crate::account::browser(runtime, ui, provider);
+ }
+ }
+ }
OverlayKind::Threads => {
if let Some(row) = selected {
switch_thread(runtime, state, ui, row.id).await;
diff --git a/crates/openhuman-tui/src/app/thread_actions.rs b/crates/openhuman-tui/src/app/thread_actions.rs
index 9eeb0527cc..59aae18ab6 100644
--- a/crates/openhuman-tui/src/app/thread_actions.rs
+++ b/crates/openhuman-tui/src/app/thread_actions.rs
@@ -10,6 +10,10 @@ pub(super) fn send_message(
ui: &mut UiState,
queue_mode: &str,
) {
+ if ui.thread_id.is_empty() {
+ state.push_system("Create or select a conversation first; your draft is preserved.");
+ return;
+ }
if ui.auth_pending {
state.push_system("Authentication is still in progress; your draft is preserved.");
return;
diff --git a/crates/openhuman-tui/src/app_tests.rs b/crates/openhuman-tui/src/app_tests.rs
index 3131ec3b31..675c880933 100644
--- a/crates/openhuman-tui/src/app_tests.rs
+++ b/crates/openhuman-tui/src/app_tests.rs
@@ -141,3 +141,39 @@ fn inbound_plan_review_waits_for_typed_overlay_to_close() {
Some("review-1")
);
}
+#[test]
+fn failed_account_thread_replacement_rejects_old_and_unscoped_activity() {
+ let mut state = TranscriptState::new("client");
+ let mut ui = UiState::new(String::new(), "client".into());
+ // Identity reset clears the binding before replacement. A failed local
+ // threads_create_new leaves it empty, so neither scoped nor legacy blank
+ // events may repopulate another account's newly cleared conversation.
+ state.push_system("Could not create a new thread (see logs).");
+ for thread in ["previous-account-thread", ""] {
+ handle_web_event(
+ &WebChannelEvent {
+ event: "text_delta".into(),
+ client_id: "client".into(),
+ thread_id: thread.into(),
+ delta: Some("old secret".into()),
+ ..Default::default()
+ },
+ &mut state,
+ &mut ui,
+ );
+ handle_web_event(
+ &WebChannelEvent {
+ event: "approval_request".into(),
+ client_id: "client".into(),
+ thread_id: thread.into(),
+ request_id: "old-approval".into(),
+ ..Default::default()
+ },
+ &mut state,
+ &mut ui,
+ );
+ }
+ assert_eq!(state.entries().len(), 1);
+ assert!(!state.is_streaming());
+ assert!(ui.pending_approvals.is_empty());
+}
diff --git a/crates/openhuman-tui/src/benchmark.rs b/crates/openhuman-tui/src/benchmark.rs
new file mode 100644
index 0000000000..fbaddeb64b
--- /dev/null
+++ b/crates/openhuman-tui/src/benchmark.rs
@@ -0,0 +1,89 @@
+//! Deterministic, offline measurements of the real viewport and TestBackend renderer.
+use super::{render, state::TranscriptState, ui_state::UiState, viewport::ViewportCache};
+use openhuman_rpc::embed::chat_surface::WebChannelEvent;
+use ratatui::{backend::TestBackend, Terminal};
+use serde_json::{json, Value};
+use std::{hint::black_box, time::Instant};
+
+const SAMPLES: usize = 200;
+
+fn measure(mut operation: impl FnMut(usize)) -> Value {
+ for i in 0..20 {
+ operation(i);
+ }
+ let mut samples = Vec::with_capacity(SAMPLES);
+ for i in 0..SAMPLES {
+ let start = Instant::now();
+ operation(i);
+ samples.push(start.elapsed().as_nanos() as u64);
+ }
+ samples.sort_unstable();
+ json!({"samples": SAMPLES, "p50_us": samples[SAMPLES / 2] as f64 / 1000.0,
+ "p95_us": samples[SAMPLES * 95 / 100] as f64 / 1000.0})
+}
+
+/// Emit reproducible measurements without starting a core, logging in, or reading a profile.
+pub(crate) fn run() -> anyhow::Result<()> {
+ let mut results = Vec::new();
+ for (width, height) in [(80, 24), (120, 40)] {
+ for entries in [250, 500, 5_000, 10_000, 20_000, 40_000] {
+ let mut state = TranscriptState::new("benchmark");
+ for index in 0..entries {
+ state.push_system(format!(
+ "Settled entry {index:05}: deterministic ASCII text."
+ ));
+ }
+ let mut cache = ViewportCache::default();
+ cache.rows(&state, width - 4, height - 9, 0);
+ let idle = measure(|_| {
+ black_box(cache.rows(&state, width - 4, height - 9, 0));
+ });
+ let scroll = measure(|i| {
+ black_box(cache.rows(&state, width - 4, height - 9, i * 3));
+ });
+ let mut terminal = Terminal::new(TestBackend::new(width, height))?;
+ let mut ui = UiState::new("benchmark".into(), "benchmark".into());
+ let render_idle = measure(|_| {
+ terminal
+ .draw(|frame| render::draw(frame, &state, &mut ui))
+ .unwrap();
+ });
+ let streaming = measure(|_| {
+ state.apply_event(&WebChannelEvent {
+ event: "text_delta".into(),
+ client_id: "benchmark".into(),
+ delta: Some(" streamed token".into()),
+ ..Default::default()
+ });
+ black_box(cache.rows(&state, width - 4, height - 9, 0));
+ });
+ results.push(json!({"width":width,"height":height,"entries":entries,
+ "settled_rows": entries * 2,"viewport_idle":idle,"viewport_scroll":scroll,
+ "render_idle":render_idle,"streaming_tail":streaming}));
+ }
+ }
+ let mut tool = TranscriptState::new("benchmark");
+ tool.apply_event(&WebChannelEvent {
+ event: "tool_result".into(),
+ client_id: "benchmark".into(),
+ tool_call_id: Some("large-output".into()),
+ tool_name: Some("benchmark".into()),
+ output: Some("deterministic tool output\n".repeat(40_000)),
+ success: Some(true),
+ ..Default::default()
+ });
+ tool.toggle_entry(0);
+ let mut cache = ViewportCache::default();
+ let large_tool = measure(|_| {
+ black_box(cache.rows(&tool, 76, 15, 0));
+ });
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&json!({
+ "schema":1,"profile":if cfg!(debug_assertions) {"debug"} else {"release"},
+ "backend":"ratatui TestBackend; no terminal I/O", "warmup":20,
+ "results":results,"large_tool_output":large_tool
+ }))?
+ );
+ Ok(())
+}
diff --git a/crates/openhuman-tui/src/browser_login.rs b/crates/openhuman-tui/src/browser_login.rs
new file mode 100644
index 0000000000..71851d0856
--- /dev/null
+++ b/crates/openhuman-tui/src/browser_login.rs
@@ -0,0 +1,324 @@
+//! Browser login transport for the TUI. Backend exchange, validation and
+//! persistence remain in the shared TinyHumans session owner.
+
+use std::{sync::Arc, time::Duration};
+
+use openhuman_rpc::tinyhumans::{CoreLink, SessionManager, SessionState};
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::{TcpListener, TcpStream},
+ sync::watch,
+};
+use zeroize::Zeroizing;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum LoginProvider {
+ #[default]
+ Google,
+ Github,
+ Twitter,
+ Discord,
+}
+
+impl LoginProvider {
+ fn slug(self) -> &'static str {
+ match self {
+ Self::Google => "google",
+ Self::Github => "github",
+ Self::Twitter => "twitter",
+ Self::Discord => "discord",
+ }
+ }
+}
+
+/// A cloneable handle which interrupts the callback wait without logging secrets.
+#[derive(Clone)]
+pub struct LoginCancellation(watch::Sender<bool>);
+
+impl LoginCancellation {
+ pub fn cancel(&self) {
+ self.0.send_replace(true);
+ }
+}
+
+/// One browser round trip. Dropping it closes its loopback callback listener.
+pub struct BrowserLogin<L: CoreLink> {
+ listener: TcpListener,
+ state: String,
+ login_url: String,
+ backend_url: String,
+ port: u16,
+ manager: Arc<SessionManager<L>>,
+ cancelled: watch::Receiver<bool>,
+ cancellation: LoginCancellation,
+}
+
+impl<L: CoreLink> BrowserLogin<L> {
+ /// Bind before opening a browser so an immediate redirect cannot be lost.
+ pub async fn start(
+ manager: Arc<SessionManager<L>>,
+ provider: LoginProvider,
+ ) -> Result<Self, String> {
+ let client = manager
+ .client()
+ .await
+ .map_err(|_| "Could not resolve the login backend.".to_string())?;
+ let listener = TcpListener::bind("127.0.0.1:0")
+ .await
+ .map_err(|_| "Could not start the login callback listener.".to_string())?;
+ let port = listener
+ .local_addr()
+ .map_err(|_| "Could not read the login callback address.".to_string())?
+ .port();
+ let state = uuid::Uuid::new_v4().simple().to_string();
+ let redirect = format!("http://127.0.0.1:{port}/auth?state={state}");
+ let login_url = format!(
+ "{}/auth/{}/login?redirect=app&redirectUri={}",
+ client.base_url().trim_end_matches('/'),
+ provider.slug(),
+ percent_encode(&redirect)
+ );
+ let (sender, cancelled) = watch::channel(false);
+ Ok(Self {
+ listener,
+ state,
+ login_url,
+ backend_url: client.base_url().to_string(),
+ port,
+ manager,
+ cancelled,
+ cancellation: LoginCancellation(sender),
+ })
+ }
+
+ pub fn login_url(&self) -> &str {
+ &self.login_url
+ }
+ /// Port to forward when running the TUI over SSH.
+ pub fn callback_port(&self) -> u16 {
+ self.port
+ }
+ pub fn cancellation(&self) -> LoginCancellation {
+ self.cancellation.clone()
+ }
+
+ /// Wait for a valid callback, then let the manager exchange or validate the
+ /// credential. Cancellation interrupts the browser wait; once accepted,
+ /// storage completes atomically under the manager's mutation lock.
+ pub async fn wait(mut self, timeout: Duration) -> Result<SessionState, String> {
+ if *self.cancelled.borrow() {
+ return Err("Login cancelled.".into());
+ }
+ let token = tokio::select! {
+ biased;
+ _ = self.cancelled.changed() => return Err("Login cancelled.".into()),
+ result = tokio::time::timeout(timeout, accept_callback(&self.listener, &self.state)) => {
+ result.map_err(|_| "Timed out waiting for browser login.".to_string())??
+ }
+ };
+ let result = if is_login_token(&token) {
+ self.manager
+ .login_with_token_for_backend(&token, &self.backend_url)
+ .await
+ } else {
+ self.manager
+ .store_session_token_for_backend(&token, None, &self.backend_url)
+ .await
+ };
+ result.map_err(|error| {
+ super::safe_session_error(
+ error,
+ "The backend could not complete sign-in. Please try again.",
+ )
+ })
+ }
+}
+
+fn is_login_token(token: &str) -> bool {
+ token.len() == 64
+ && token
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+}
+
+fn percent_encode(value: &str) -> String {
+ value
+ .bytes()
+ .map(|b| match b {
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
+ (b as char).to_string()
+ }
+ _ => format!("%{b:02X}"),
+ })
+ .collect()
+}
+
+fn percent_decode(value: &str) -> Option<String> {
+ let mut result = Vec::new();
+ let mut bytes = value.bytes();
+ while let Some(b) = bytes.next() {
+ result.push(match b {
+ b'+' => b' ',
+ b'%' => {
+ let a = (bytes.next()? as char).to_digit(16)?;
+ let b = (bytes.next()? as char).to_digit(16)?;
+ (a * 16 + b) as u8
+ }
+ _ => b,
+ });
+ }
+ String::from_utf8(result).ok()
+}
+
+enum Callback {
+ Ignore(&'static str),
+ Rejected,
+ Token(Zeroizing<String>),
+}
+
+fn classify(head: &str, expected_state: &str, port: u16) -> Callback {
+ let mut hosts = head
+ .lines()
+ .skip(1)
+ .filter_map(|line| line.split_once(':'))
+ .filter(|(key, _)| key.eq_ignore_ascii_case("host"));
+ if hosts.next().map(|(_, value)| value.trim()) != Some(format!("127.0.0.1:{port}").as_str())
+ || hosts.next().is_some()
+ {
+ return Callback::Ignore("400 Bad Request");
+ }
+ // Top-level browser redirects carry no Origin. Cross-origin fetches are
+ // not the browser round trip we initiated.
+ if head
+ .lines()
+ .skip(1)
+ .filter_map(|line| line.split_once(':'))
+ .any(|(key, _)| key.eq_ignore_ascii_case("origin"))
+ {
+ return Callback::Ignore("400 Bad Request");
+ }
+ let mut parts = head.lines().next().unwrap_or_default().split_whitespace();
+ if parts.next() != Some("GET") {
+ return Callback::Ignore("405 Method Not Allowed");
+ }
+ let target = parts.next().unwrap_or_default();
+ let (path, query) = target.split_once('?').unwrap_or((target, ""));
+ if path != "/auth" {
+ return Callback::Ignore("404 Not Found");
+ }
+ let mut params = std::collections::HashMap::new();
+ for pair in query.split('&') {
+ let Some((key, value)) = pair.split_once('=') else {
+ continue;
+ };
+ let Some(key) = percent_decode(key) else {
+ return Callback::Ignore("400 Bad Request");
+ };
+ let Some(value) = percent_decode(value) else {
+ return Callback::Ignore("400 Bad Request");
+ };
+ if params.insert(key, Zeroizing::new(value)).is_some() {
+ return Callback::Ignore("400 Bad Request");
+ }
+ }
+ if params.get("state").map(|s| s.as_str()) != Some(expected_state) {
+ return Callback::Ignore("400 Bad Request");
+ }
+ if params.contains_key("error") {
+ return Callback::Rejected;
+ }
+ match params.remove("token").filter(|t| !t.trim().is_empty()) {
+ Some(token) => Callback::Token(token),
+ None => Callback::Ignore("400 Bad Request"),
+ }
+}
+
+async fn accept_callback(listener: &TcpListener, state: &str) -> Result<Zeroizing<String>, String> {
+ loop {
+ let (mut stream, peer) = listener
+ .accept()
+ .await
+ .map_err(|_| "The login callback listener failed.".to_string())?;
+ if !peer.ip().is_loopback() {
+ continue;
+ }
+ let head = match tokio::time::timeout(Duration::from_secs(5), read_head(&mut stream)).await
+ {
+ Ok(Some(head)) => head,
+ _ => continue,
+ };
+ let port = listener
+ .local_addr()
+ .map_err(|_| "Could not read the login callback address.".to_string())?
+ .port();
+ let outcome = classify(&head, state, port);
+ let (status, body) = match &outcome {
+ Callback::Ignore(status) => (*status, "Invalid login callback."),
+ Callback::Rejected => ("200 OK", "Login failed. Return to OpenHuman to try again."),
+ Callback::Token(_) => (
+ "200 OK",
+ "Login received. Return to OpenHuman to finish signing in. You can close this tab.",
+ ),
+ };
+ let response = format!("HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer\r\n\r\n{body}", body.len());
+ let _ = tokio::time::timeout(
+ Duration::from_secs(2),
+ stream.write_all(response.as_bytes()),
+ )
+ .await;
+ match outcome {
+ Callback::Token(token) => return Ok(token),
+ Callback::Rejected => {
+ return Err("The provider rejected sign-in. Please try again.".into())
+ }
+ Callback::Ignore(_) => {}
+ }
+ }
+}
+
+async fn read_head(stream: &mut TcpStream) -> Option<Zeroizing<String>> {
+ let mut bytes = Zeroizing::new(Vec::new());
+ while bytes.len() < 8192 {
+ let mut buffer = [0; 1024];
+ let count = stream.read(&mut buffer).await.ok()?;
+ if count == 0 {
+ return None;
+ }
+ bytes.extend_from_slice(&buffer[..count]);
+ if bytes.windows(4).any(|b| b == b"\r\n\r\n") {
+ return String::from_utf8(bytes.to_vec()).ok().map(Zeroizing::new);
+ }
+ }
+ None
+}
+
+/// Open the system browser without shell interpolation or terminal output.
+pub fn open_browser(url: &str) -> Result<(), String> {
+ #[cfg(target_os = "macos")]
+ let mut command = std::process::Command::new("open");
+ #[cfg(target_os = "linux")]
+ let mut command = std::process::Command::new("xdg-open");
+ #[cfg(target_os = "windows")]
+ let mut command = {
+ let mut command = std::process::Command::new("rundll32");
+ command.arg("url.dll,FileProtocolHandler");
+ command
+ };
+ let mut child = command
+ .arg(url)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .map_err(|_| {
+ "Could not open the browser. Open the displayed login URL manually.".to_string()
+ })?;
+ std::thread::spawn(move || {
+ let _ = child.wait();
+ });
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "browser_login_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-tui/src/browser_login_tests.rs b/crates/openhuman-tui/src/browser_login_tests.rs
new file mode 100644
index 0000000000..f040473b4b
--- /dev/null
+++ b/crates/openhuman-tui/src/browser_login_tests.rs
@@ -0,0 +1,356 @@
+use super::*;
+use async_trait::async_trait;
+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
+use openhuman_rpc::tinyhumans::{link::CoreAuthState, ClientHeaders};
+use serde_json::{json, Value};
+use std::sync::{
+ atomic::{AtomicUsize, Ordering},
+ Mutex,
+};
+
+fn jwt() -> String {
+ format!(
+ "{}.{}.sig",
+ URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#),
+ URL_SAFE_NO_PAD.encode(json!({"sub":"test-user","exp":4102444800_u64}).to_string())
+ )
+}
+
+struct FakeCore {
+ base: Mutex<String>,
+ token: Mutex<Option<String>>,
+ state: Mutex<CoreAuthState>,
+}
+
+#[async_trait]
+impl CoreLink for FakeCore {
+ async fn invoke(&self, method: &str, params: Value) -> Result<Value, String> {
+ let mut state = self.state.lock().unwrap();
+ match method {
+ "openhuman.config_resolve_api_url" => {
+ Ok(json!({"api_url":self.base.lock().unwrap().clone()}))
+ }
+ "openhuman.auth_get_state" => Ok(serde_json::to_value(&*state).unwrap()),
+ "openhuman.auth_get_session_token" => {
+ Ok(json!({"token":self.token.lock().unwrap().clone()}))
+ }
+ "openhuman.auth_set_credential" => {
+ *self.token.lock().unwrap() = params["token"].as_str().map(str::to_owned);
+ *state = CoreAuthState {
+ is_authenticated: true,
+ credential: Some("session".into()),
+ user_id: params["userId"].as_str().map(str::to_owned),
+ user: Some(params["user"].clone()),
+ issuing_backend: params["issuingBackend"].as_str().map(str::to_owned),
+ ..Default::default()
+ };
+ Ok(serde_json::to_value(&*state).unwrap())
+ }
+ "openhuman.auth_clear_credential" => {
+ *state = CoreAuthState::default();
+ *self.token.lock().unwrap() = None;
+ Ok(json!({}))
+ }
+ _ => Err("Unsupported test method".into()),
+ }
+ }
+}
+
+struct Backend {
+ task: tokio::task::JoinHandle<()>,
+ base: String,
+ exchanges: Arc<AtomicUsize>,
+ profiles: Arc<AtomicUsize>,
+}
+impl Drop for Backend {
+ fn drop(&mut self) {
+ self.task.abort();
+ }
+}
+
+impl Backend {
+ async fn start(reject: bool) -> Self {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let exchanges = Arc::new(AtomicUsize::new(0));
+ let profiles = Arc::new(AtomicUsize::new(0));
+ let calls = exchanges.clone();
+ let me_calls = profiles.clone();
+ let task = tokio::spawn(async move {
+ loop {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let head = read_head(&mut stream).await.unwrap();
+ let consume = head.starts_with("POST /auth/login-token/consume ");
+ if consume {
+ calls.fetch_add(1, Ordering::SeqCst);
+ } else {
+ assert!(head.starts_with("GET /auth/me "));
+ me_calls.fetch_add(1, Ordering::SeqCst);
+ }
+ let body = if consume {
+ json!({"success":true,"data":{"jwt":jwt()}})
+ } else if reject {
+ json!({"success":false,"message":"rejected"})
+ } else {
+ json!({"success":true,"data":{"_id":"test-user","name":"Test account"}})
+ }
+ .to_string();
+ let status = if reject && !consume {
+ "401 Unauthorized"
+ } else {
+ "200 OK"
+ };
+ let response = format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
+ stream.write_all(response.as_bytes()).await.unwrap();
+ }
+ });
+ Self {
+ task,
+ base,
+ exchanges,
+ profiles,
+ }
+ }
+
+ fn manager(&self) -> Arc<SessionManager<FakeCore>> {
+ SessionManager::new(
+ Arc::new(FakeCore {
+ base: Mutex::new(self.base.clone()),
+ token: Mutex::new(None),
+ state: Mutex::new(CoreAuthState::default()),
+ }),
+ ClientHeaders::new("openhuman-test"),
+ )
+ }
+}
+
+fn request(port: u16, target: &str) -> String {
+ format!("GET {target} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\r\n")
+}
+
+async fn callback(port: u16, target: &str) -> String {
+ let mut stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
+ stream
+ .write_all(request(port, target).as_bytes())
+ .await
+ .unwrap();
+ let mut response = String::new();
+ stream.read_to_string(&mut response).await.unwrap();
+ response
+}
+
+#[test]
+fn callback_rejects_wrong_nonce_method_path_origin_host_and_duplicate_params() {
+ let valid = request(1234, "/auth?state=expected&token=a%2Eb%2Bc");
+ assert!(
+ matches!(classify(&valid, "expected", 1234), Callback::Token(token) if token.as_str()=="a.b+c")
+ );
+ for invalid in [
+ valid.replace("expected", "wrong"),
+ valid.replace("GET", "POST"),
+ valid.replace("/auth?", "/else?"),
+ valid.replace("Host:", "Origin: https://example.invalid\r\nHost:"),
+ valid.replace("127.0.0.1", "example.invalid"),
+ request(1234, "/auth?state=expected&state=wrong&token=test"),
+ request(1234, "/auth?state=expected&token="),
+ request(1234, "/auth?state=expected&token=%ZZ"),
+ ] {
+ assert!(matches!(
+ classify(&invalid, "expected", 1234),
+ Callback::Ignore(_)
+ ));
+ }
+ assert!(matches!(
+ classify(
+ &request(1234, "/auth?state=expected&error=secret"),
+ "expected",
+ 1234
+ ),
+ Callback::Rejected
+ ));
+}
+
+#[test]
+fn token_classification_and_url_encoding_match_backend_contract() {
+ assert!(is_login_token(&"a".repeat(64)));
+ for token in [jwt(), "A".repeat(64), "a".repeat(63), "g".repeat(64)] {
+ assert!(!is_login_token(&token));
+ }
+ assert_eq!(
+ percent_encode("http://127.0.0.1:1234/auth?state=abc"),
+ "http%3A%2F%2F127.0.0.1%3A1234%2Fauth%3Fstate%3Dabc"
+ );
+}
+
+#[tokio::test]
+async fn browser_login_exchanges_one_time_token_and_stores_verified_account() {
+ let backend = Backend::start(false).await;
+ let manager = backend.manager();
+ let flow = BrowserLogin::start(manager.clone(), LoginProvider::Github)
+ .await
+ .unwrap();
+ let port = flow.listener.local_addr().unwrap().port();
+ assert_eq!(flow.callback_port(), port);
+ assert_eq!(
+ flow.login_url(),
+ format!(
+ "{}/auth/github/login?redirect=app&redirectUri={}",
+ backend.base,
+ percent_encode(&format!(
+ "http://127.0.0.1:{port}/auth?state={}",
+ flow.state
+ ))
+ )
+ );
+ let target = format!("/auth?state={}&token={}", flow.state, "a".repeat(64));
+ let wait = tokio::spawn(flow.wait(Duration::from_secs(5)));
+ assert!(callback(port, "/auth?state=wrong&token=untrusted")
+ .await
+ .starts_with("HTTP/1.1 400"));
+ assert!(callback(port, &target).await.starts_with("HTTP/1.1 200"));
+ let state = wait.await.unwrap().unwrap();
+ assert!(state.core.is_authenticated);
+ assert_eq!(state.core.user_id.as_deref(), Some("test-user"));
+ assert_eq!(backend.exchanges.load(Ordering::SeqCst), 1);
+ manager.logout().await.unwrap();
+ assert!(manager.link().token.lock().unwrap().is_none());
+}
+
+#[tokio::test]
+async fn jwt_callback_validates_without_exchange_and_restores_in_new_manager() {
+ let backend = Backend::start(false).await;
+ let manager = backend.manager();
+ let flow = BrowserLogin::start(manager.clone(), LoginProvider::Google)
+ .await
+ .unwrap();
+ let port = flow.listener.local_addr().unwrap().port();
+ let target = format!(
+ "/auth?state={}&token={}",
+ flow.state,
+ percent_encode(&jwt())
+ );
+ let wait = tokio::spawn(flow.wait(Duration::from_secs(5)));
+ callback(port, &target).await;
+ wait.await.unwrap().unwrap();
+ assert_eq!(backend.exchanges.load(Ordering::SeqCst), 0);
+ let restored =
+ SessionManager::new(manager.link().clone(), ClientHeaders::new("openhuman-test"));
+ let calls = backend.profiles.load(Ordering::SeqCst);
+ let state = crate::session::refresh_session(&restored).await.unwrap();
+ assert_eq!(state.current_user.unwrap()["name"], "Test account");
+ assert!(backend.profiles.load(Ordering::SeqCst) > calls);
+}
+
+#[tokio::test]
+async fn rejected_callback_and_rejected_backend_never_store_credentials() {
+ let backend = Backend::start(true).await;
+ let manager = backend.manager();
+ for token in [Some(jwt()), None] {
+ let flow = BrowserLogin::start(manager.clone(), LoginProvider::Google)
+ .await
+ .unwrap();
+ let port = flow.listener.local_addr().unwrap().port();
+ let target = match token {
+ Some(token) => format!("/auth?state={}&token={token}", flow.state),
+ None => format!(
+ "/auth?state={}&error=sensitive-provider-message",
+ flow.state
+ ),
+ };
+ let wait = tokio::spawn(flow.wait(Duration::from_secs(5)));
+ callback(port, &target).await;
+ let error = wait.await.unwrap().unwrap_err();
+ assert!(!error.contains("sensitive-provider-message"));
+ assert!(!error.contains(&jwt()));
+ assert!(manager.link().token.lock().unwrap().is_none());
+ }
+}
+
+#[tokio::test]
+async fn rejected_persisted_session_is_cleared_on_restore() {
+ let backend = Backend::start(true).await;
+ let manager = backend.manager();
+ *manager.link().token.lock().unwrap() = Some(jwt());
+ *manager.link().state.lock().unwrap() = CoreAuthState {
+ is_authenticated: true,
+ credential: Some("session".into()),
+ user_id: Some("test-user".into()),
+ ..Default::default()
+ };
+ let state = crate::session::refresh_session(&manager).await.unwrap();
+ assert!(!state.core.is_authenticated);
+ assert!(manager.link().token.lock().unwrap().is_none());
+}
+
+#[tokio::test]
+async fn cancellation_and_timeout_close_listener_without_storing() {
+ let backend = Backend::start(false).await;
+ let manager = backend.manager();
+ let flow = BrowserLogin::start(manager.clone(), LoginProvider::Google)
+ .await
+ .unwrap();
+ let port = flow.listener.local_addr().unwrap().port();
+ let cancel = flow.cancellation();
+ let wait = tokio::spawn(flow.wait(Duration::from_secs(30)));
+ cancel.cancel();
+ assert_eq!(wait.await.unwrap().unwrap_err(), "Login cancelled.");
+ assert!(TcpStream::connect(("127.0.0.1", port)).await.is_err());
+ let flow = BrowserLogin::start(manager.clone(), LoginProvider::Google)
+ .await
+ .unwrap();
+ assert_eq!(
+ flow.wait(Duration::ZERO).await.unwrap_err(),
+ "Timed out waiting for browser login."
+ );
+ assert!(manager.link().token.lock().unwrap().is_none());
+}
+
+#[tokio::test]
+async fn browser_callback_cannot_send_credentials_to_a_changed_backend() {
+ let issuer = Backend::start(false).await;
+ let changed = Backend::start(false).await;
+ let manager = issuer.manager();
+ for token in [jwt(), "a".repeat(64)] {
+ *manager.link().base.lock().unwrap() = issuer.base.clone();
+ let flow = BrowserLogin::start(manager.clone(), LoginProvider::Google)
+ .await
+ .unwrap();
+ let target = format!(
+ "/auth?state={}&token={}",
+ flow.state,
+ percent_encode(&token)
+ );
+ let port = flow.callback_port();
+ *manager.link().base.lock().unwrap() = changed.base.clone();
+ let wait = tokio::spawn(flow.wait(Duration::from_secs(5)));
+ callback(port, &target).await;
+ let error = wait.await.unwrap().unwrap_err();
+ assert!(error.starts_with("SESSION_BACKEND_MISMATCH"));
+ assert!(!error.contains(&token));
+ assert!(manager.link().token.lock().unwrap().is_none());
+ }
+ for backend in [&issuer, &changed] {
+ assert_eq!(backend.exchanges.load(Ordering::SeqCst), 0);
+ assert_eq!(backend.profiles.load(Ordering::SeqCst), 0);
+ }
+}
+
+#[tokio::test]
+async fn persisted_restore_preserves_safe_actionable_backend_mismatch() {
+ let issuer = Backend::start(false).await;
+ let changed = Backend::start(false).await;
+ let manager = issuer.manager();
+ *manager.link().token.lock().unwrap() = Some(jwt());
+ *manager.link().state.lock().unwrap() = CoreAuthState {
+ is_authenticated: true,
+ credential: Some("session".into()),
+ issuing_backend: Some(issuer.base.clone()),
+ ..Default::default()
+ };
+ *manager.link().base.lock().unwrap() = changed.base.clone();
+ let error = crate::session::refresh_session(&manager).await.unwrap_err();
+ assert!(error.starts_with("SESSION_BACKEND_MISMATCH"));
+ assert!(error.contains("Restore that backend or start sign-in again"));
+ assert!(!error.contains(&jwt()));
+ assert_eq!(changed.profiles.load(Ordering::SeqCst), 0);
+}
diff --git a/crates/openhuman-tui/src/cockpit.rs b/crates/openhuman-tui/src/cockpit.rs
index 80ee354744..9c539bf6ad 100644
--- a/crates/openhuman-tui/src/cockpit.rs
+++ b/crates/openhuman-tui/src/cockpit.rs
@@ -24,6 +24,7 @@ pub enum OverlayKind {
HistorySearch,
Files,
Themes,
+ Login,
Tools,
Subagents,
ToolDetail,
diff --git a/crates/openhuman-tui/src/composer.rs b/crates/openhuman-tui/src/composer.rs
index f1ca7bcf9a..5efe9a5543 100644
--- a/crates/openhuman-tui/src/composer.rs
+++ b/crates/openhuman-tui/src/composer.rs
@@ -6,7 +6,9 @@ use unicode_width::UnicodeWidthChar;
/// OpenHuman-native: commands either map to a stable core RPC or a local view.
pub const COMMANDS: &[(&str, &str)] = &[
("help", "show commands and keyboard shortcuts"),
- ("login", "sign in with a one-time token"),
+ ("login", "sign in to TinyHumans with your browser"),
+ ("login-token", "paste a one-time token as a fallback"),
+ ("login-cancel", "cancel a pending browser sign-in"),
("sessions", "browse saved conversations"),
("subagents", "inspect child agent activity"),
("tools", "inspect tool calls and output"),
diff --git a/crates/openhuman-tui/src/controls.rs b/crates/openhuman-tui/src/controls.rs
index 6dd6bc4fc7..4ec86e4a1e 100644
--- a/crates/openhuman-tui/src/controls.rs
+++ b/crates/openhuman-tui/src/controls.rs
@@ -124,8 +124,12 @@ pub async fn refresh_config(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {
pub async fn handle_settings_key(key: KeyEvent, runtime: &Arc<CoreRuntime>, ui: &mut UiState) {
if ui.auth_pending {
- ui.settings_status =
- "Signing in… You can browse views while authentication completes.".into();
+ match key.code {
+ KeyCode::Esc => super::account::cancel(ui),
+ KeyCode::Char('o' | 'O') => super::account::reopen(ui),
+ KeyCode::Char('c' | 'C') => copy_login_link(ui),
+ _ => {}
+ }
return;
}
if let Some(token) = ui.login_token.as_mut() {
@@ -146,7 +150,7 @@ pub async fn handle_settings_key(key: KeyEvent, runtime: &Arc<CoreRuntime>, ui:
if ui.logout_confirm {
match key.code {
KeyCode::Esc | KeyCode::Char('n') => ui.logout_confirm = false,
- KeyCode::Char('y') | KeyCode::Enter => logout(runtime, ui).await,
+ KeyCode::Char('y') | KeyCode::Enter => super::account::logout(runtime, ui),
_ => {}
}
return;
@@ -157,8 +161,9 @@ pub async fn handle_settings_key(key: KeyEvent, runtime: &Arc<CoreRuntime>, ui:
ui.settings_selected = (ui.settings_selected + 1).min(SettingsAction::ALL.len() - 1)
}
KeyCode::Enter => match SettingsAction::ALL[ui.settings_selected] {
- SettingsAction::ViewAccount => view_account(runtime, ui).await,
- SettingsAction::Login => ui.login_token = Some(String::new()),
+ SettingsAction::ViewAccount => super::account::refresh(runtime, ui),
+ SettingsAction::Login => super::account::picker(ui),
+ SettingsAction::LoginToken => ui.login_token = Some(String::new()),
SettingsAction::Logout => ui.logout_confirm = true,
},
_ => {}
@@ -166,106 +171,47 @@ pub async fn handle_settings_key(key: KeyEvent, runtime: &Arc<CoreRuntime>, ui:
}
pub async fn refresh_auth(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {
- match runtime.invoke("openhuman.auth_get_state", json!({})).await {
- Ok(value) => {
- let state = rpc_payload(&value);
- if state
- .get("isAuthenticated")
- .and_then(serde_json::Value::as_bool)
- .unwrap_or(false)
- {
- let identity = string_at(state, &["userId"]);
- ui.auth_summary = if identity.is_empty() {
- "Signed in".to_string()
- } else {
- format!("Signed in · {identity}")
- };
- } else {
- ui.auth_summary = "Signed out".to_string();
- ui.account_detail.clear();
- }
- }
- Err(err) => ui.auth_summary = format!("Account status unavailable: {err}"),
- }
-}
-
-async fn view_account(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {
- ui.settings_status = "Refreshing account…".to_string();
- match crate::session::session_manager(runtime)
- .current_user(true)
- .await
- {
- Ok(current) => {
- ui.account_detail = current
- .user
- .as_ref()
- .map(account_detail)
- .unwrap_or_else(|| "No account details available.".to_string());
- ui.settings_status = if current.stale {
- "Account refreshed from the stored copy (backend unreachable).".to_string()
- } else {
- "Account refreshed.".to_string()
+ match super::session::session_manager(runtime).core_state().await {
+ Ok(core) => {
+ let stale = core.credential.as_deref() == Some("session");
+ let state = openhuman_rpc::tinyhumans::SessionState {
+ current_user: core.user.clone(),
+ current_user_stale: stale,
+ core,
+ ..Default::default()
};
- refresh_auth(runtime, ui).await;
+ super::account::apply_session(&state, ui);
}
- Err(err) => ui.settings_status = format!("Account refresh failed: {err}"),
+ Err(_) => ui.auth_summary = "Account status unavailable".into(),
}
}
async fn login_with_token(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {
- let mut token = ui.login_token.take().unwrap_or_default();
+ let token = zeroize::Zeroizing::new(ui.login_token.take().unwrap_or_default());
if token.trim().is_empty() {
- ui.settings_status = "Login token cannot be empty.".to_string();
- token.zeroize();
+ ui.settings_status = "Login token cannot be empty.".into();
+ ui.login_token = Some(String::new());
return;
}
- ui.settings_status = "Signing in…".to_string();
- if let Some(tx) = ui.auth_tx.clone() {
- ui.auth_pending = true;
- let manager = crate::session::session_manager(runtime);
- let token = zeroize::Zeroizing::new(token);
- tokio::spawn(async move {
- let result = match tokio::time::timeout(
- std::time::Duration::from_secs(30),
- manager.login_with_token(token.trim()),
- )
- .await
- {
- Ok(result) => result.map(|_| ()).map_err(|error| error.to_string()),
- Err(_) => Err("Sign-in timed out. Check Account before retrying.".into()),
- };
- let _ = tx.send(result);
- });
- return;
- }
- // Exchange, validate against `/auth/me`, and install in the core — all
- // owned by `openhuman-tinyhumans`; the JWT never passes through this module.
- let result = crate::session::session_manager(runtime)
- .login_with_token(token.trim())
- .await;
- token.zeroize();
- match result {
- Ok(_) => {
- ui.settings_status = "Signed in.".to_string();
- refresh_auth(runtime, ui).await;
- ui.identity_changed = true;
- }
- Err(err) => ui.settings_status = format!("Login failed: {err}"),
- }
+ super::account::token(runtime, ui, token);
}
-async fn logout(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {
- ui.logout_confirm = false;
- match crate::session::session_manager(runtime).logout().await {
- Ok(_) => {
- ui.settings_status = "Signed out.".to_string();
- refresh_auth(runtime, ui).await;
- ui.identity_changed = true;
+pub(crate) fn copy_login_link(ui: &mut UiState) {
+ use std::io::Write;
+ if let Some(url) = &ui.login_url {
+ match std::io::stdout().write_all(login_clipboard_sequence(url).as_bytes()).and_then(|_|std::io::stdout().flush()) {
+ Ok(())=>ui.settings_status=format!("Terminal clipboard copy requested. Forward port {} when remote. O reopens · Esc cancels.",ui.login_port.unwrap_or(0)),
+ Err(_)=>ui.settings_status="The terminal clipboard is unavailable. Use O to open the browser.".into()
}
- Err(err) => ui.settings_status = format!("Logout failed: {err}"),
}
}
+fn login_clipboard_sequence(url: &str) -> String {
+ use base64::Engine as _;
+ let encoded = base64::engine::general_purpose::STANDARD.encode(url.as_bytes());
+ format!("\u{1b}]52;c;{encoded}\u{7}")
+}
+
fn rpc_payload(value: &serde_json::Value) -> &serde_json::Value {
openhuman_rpc::unwrap_rpc(value)
}
@@ -300,7 +246,9 @@ fn string_at(value: &serde_json::Value, path: &[&str]) -> String {
.to_string()
}
-fn account_detail(user: &serde_json::Value) -> String {
+pub(crate) fn account_detail(user: &serde_json::Value) -> String {
+ let user = user.get("data").unwrap_or(user);
+ let user = user.get("user").unwrap_or(user);
let name = [
string_at(user, &["firstName"]),
string_at(user, &["lastName"]),
diff --git a/crates/openhuman-tui/src/controls_tests.rs b/crates/openhuman-tui/src/controls_tests.rs
index d056dee791..1def79004b 100644
--- a/crates/openhuman-tui/src/controls_tests.rs
+++ b/crates/openhuman-tui/src/controls_tests.rs
@@ -77,3 +77,26 @@ fn curated_config_fields_map_to_safe_specific_updates() {
assert_eq!(params, expected_params);
}
}
+#[test]
+fn login_clipboard_sequence_uses_real_osc52_control_bytes() {
+ use base64::Engine as _;
+ let url = "https://example.test/auth/google/login?redirect=app";
+ let sequence = login_clipboard_sequence(url);
+ let payload = sequence
+ .strip_prefix("\u{1b}]52;c;")
+ .unwrap()
+ .strip_suffix('\u{7}')
+ .unwrap();
+ assert_eq!(
+ base64::engine::general_purpose::STANDARD
+ .decode(payload)
+ .unwrap(),
+ url.as_bytes()
+ );
+}
+
+#[test]
+fn account_detail_unwraps_profile_without_displaying_secret_fields() {
+ let user = serde_json::json!({"data":{"user":{"firstName":"Ada","email":"[email protected]","token":"secret"}}});
+ assert_eq!(account_detail(&user), "Ada · [email protected]");
+}
diff --git a/crates/openhuman-tui/src/lib.rs b/crates/openhuman-tui/src/lib.rs
index f7a90fcf64..66e10dda56 100644
--- a/crates/openhuman-tui/src/lib.rs
+++ b/crates/openhuman-tui/src/lib.rs
@@ -30,9 +30,11 @@
//!
//! See `README.md` for build/run instructions and the packaging story.
+mod account;
mod actions;
mod activity;
mod app;
+mod benchmark;
mod cockpit;
mod composer;
mod controls;
diff --git a/crates/openhuman-tui/src/main.rs b/crates/openhuman-tui/src/main.rs
index b8b59d4397..7f36b75098 100644
--- a/crates/openhuman-tui/src/main.rs
+++ b/crates/openhuman-tui/src/main.rs
@@ -6,7 +6,10 @@ fn main() {
// installs the tracing layer, while this creates the client that receives
// its events and installs Sentry's panic integration.
let args = std::env::args().skip(1).collect::<Vec<_>>();
- let _sentry_guard = if args.iter().any(|arg| arg == "--demo") {
+ let _sentry_guard = if args
+ .iter()
+ .any(|arg| matches!(arg.as_str(), "--demo" | "--bench" | "--no-telemetry"))
+ {
None
} else {
Some(openhuman_tui::init_crash_reporting())
diff --git a/crates/openhuman-tui/src/render.rs b/crates/openhuman-tui/src/render.rs
index 7e50860885..992ec713d9 100644
--- a/crates/openhuman-tui/src/render.rs
+++ b/crates/openhuman-tui/src/render.rs
@@ -24,6 +24,8 @@ pub fn draw(frame: &mut Frame, state: &TranscriptState, ui: &mut UiState) {
area,
);
if area.width < 24 || area.height < 8 {
+ ui.transcript_area = Rect::default();
+ ui.composer_area = Rect::default();
text(
frame,
area,
@@ -143,8 +145,8 @@ fn chat(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &mut UiState
.display(area.width.saturating_sub(3).max(1) as usize);
let count = ui.composer.command_matches().len().min(4);
let height = ((rows.len().min(5) + 3 + count) as u16)
- .min(area.height.saturating_sub(3))
- .max(3);
+ .min(area.height.saturating_sub(1))
+ .max(4);
let transcript_height = area.height.saturating_sub(height + 1);
ui.transcript_area = Rect::new(area.x + 1, area.y, area.width - 2, transcript_height);
let (visible, max_scroll) = ui.viewport.rows(
@@ -153,8 +155,8 @@ fn chat(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &mut UiState
transcript_height,
ui.scroll_from_bottom,
);
- ui.scroll_from_bottom = ui.scroll_from_bottom.min(max_scroll);
- if visible.is_empty() {
+ ui.scroll_from_bottom = ui.viewport.resolved_offset().min(max_scroll);
+ if visible.is_empty() && transcript_height >= 5 {
text(
frame,
Rect::new(area.x + 3, area.y + 2, area.width.saturating_sub(6), 1),
@@ -247,7 +249,12 @@ fn chat(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &mut UiState
}
composer(
frame,
- Rect::new(area.x, y + 1, area.width, height),
+ Rect::new(
+ area.x,
+ area.bottom().saturating_sub(height),
+ area.width,
+ height,
+ ),
state,
ui,
p,
@@ -320,8 +327,16 @@ fn composer(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &mut UiS
}
let y = inner.bottom().saturating_sub(1);
let agent = format!("{} ▾", ui.agent_name);
+ let reserved = if inner.width >= 64 {
+ 30
+ } else if state.is_streaming() {
+ 19
+ } else {
+ 10
+ };
+ let selectors_width = inner.width.saturating_sub(reserved);
let aw = (UnicodeWidthStr::width(agent.as_str()) as u16)
- .min(inner.width / 3)
+ .min(selectors_width / 2)
.max(1);
button(
frame,
@@ -333,7 +348,12 @@ fn composer(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &mut UiS
);
button(
frame,
- Rect::new(inner.x + aw + 1, y, (inner.width / 3).min(28), 1),
+ Rect::new(
+ inner.x + aw + 1,
+ y,
+ selectors_width.saturating_sub(aw + 1).min(28),
+ 1,
+ ),
&format!(
"{} ▾",
ui.model_override.as_deref().unwrap_or(&ui.effective_model)
diff --git a/crates/openhuman-tui/src/render/views.rs b/crates/openhuman-tui/src/render/views.rs
index 1e45cb03ae..7099f209c3 100644
--- a/crates/openhuman-tui/src/render/views.rs
+++ b/crates/openhuman-tui/src/render/views.rs
@@ -130,7 +130,31 @@ pub(super) fn settings(frame: &mut Frame, area: Rect, ui: &mut UiState, p: Palet
),
);
}
- if ui.login_token.is_some() || ui.logout_confirm {
+ if ui.login_url.is_some() && area.height > 12 {
+ for (index, (label, command)) in [
+ ("Open browser", "login-open"),
+ ("Copy link", "login-copy"),
+ ("Cancel", "login-cancel"),
+ ]
+ .iter()
+ .enumerate()
+ {
+ let width = area.width.saturating_sub(4) / 3;
+ button(
+ frame,
+ Rect::new(
+ area.x + 2 + index as u16 * width,
+ area.bottom().saturating_sub(2),
+ width,
+ 1,
+ ),
+ label,
+ Action::Command(command),
+ ui,
+ p,
+ );
+ }
+ } else if ui.login_token.is_some() || ui.logout_confirm {
button(
frame,
Rect::new(area.x + 2, area.bottom().saturating_sub(2), 12, 1),
diff --git a/crates/openhuman-tui/src/render_tests.rs b/crates/openhuman-tui/src/render_tests.rs
index 0981172b1c..6fc67d3638 100644
--- a/crates/openhuman-tui/src/render_tests.rs
+++ b/crates/openhuman-tui/src/render_tests.rs
@@ -1,5 +1,5 @@
use super::*;
-use ratatui::backend::TestBackend;
+use ratatui::backend::{Backend, TestBackend};
use ratatui::Terminal;
fn rendered(width: u16, height: u16, state: &TranscriptState, ui: &mut UiState) -> String {
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
@@ -61,3 +61,78 @@ fn small_terminal_and_unicode_do_not_panic() {
rendered(width, height, &TranscriptState::new("client"), &mut ui);
}
}
+
+#[test]
+fn composer_stays_above_status_on_resize_with_cursor_and_controls_inside_it() {
+ let state = TranscriptState::new("client");
+ let mut ui = UiState::new("thread".into(), "client".into());
+ for draft in ["short", "/", "界e\u{301}\nlong draft\n".repeat(20).as_str()] {
+ ui.composer.set_text(draft);
+ for (width, height) in [(80, 24), (120, 40), (40, 12), (24, 8), (80, 24)] {
+ let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
+ terminal.draw(|f| draw(f, &state, &mut ui)).unwrap();
+ let send = ui
+ .hits
+ .iter()
+ .find(|hit| hit.action == Action::Send)
+ .unwrap();
+ assert_eq!(send.area.y, height - 3);
+ assert!(ui.composer_area.bottom() <= send.area.y);
+ assert!(ui.transcript_area.bottom() <= ui.composer_area.y);
+ let (x, y) = terminal.backend_mut().get_cursor_position().unwrap().into();
+ assert!(x >= ui.composer_area.x && x < ui.composer_area.right());
+ assert!(y >= ui.composer_area.y && y < ui.composer_area.bottom());
+ assert!(ui
+ .hits
+ .iter()
+ .all(|hit| hit.area.right() <= width && hit.area.bottom() < height));
+ }
+ }
+ rendered(20, 5, &state, &mut ui);
+ assert_eq!(ui.composer_area, Rect::default());
+ assert!(ui.hits.is_empty());
+}
+
+#[test]
+fn long_selectors_do_not_overlap_send_or_stream_controls_in_narrow_terminals() {
+ let mut state = TranscriptState::new("client");
+ let mut ui = UiState::new("thread".into(), "client".into());
+ ui.agent_name = "A very long named agent".repeat(4);
+ ui.model_override = Some("A very long model".repeat(4));
+ for streaming in [false, true] {
+ if streaming {
+ state.begin_user_turn("work");
+ }
+ for width in [24, 40, 80, 120] {
+ rendered(width, 24, &state, &mut ui);
+ let controls: Vec<_> = ui.hits.iter().filter(|hit| hit.area.y == 21).collect();
+ for (index, left) in controls.iter().enumerate() {
+ for right in controls.iter().skip(index + 1) {
+ assert!(
+ left.area.intersection(right.area).is_empty(),
+ "overlapping actions {:?} and {:?} at width {width}",
+ left.action,
+ right.action
+ );
+ }
+ }
+ }
+ }
+}
+#[test]
+fn pending_browser_signin_has_mouse_actions_without_rendering_its_link() {
+ let mut ui = UiState::new("thread".into(), "client".into());
+ ui.active_tab = AppTab::Settings;
+ ui.auth_pending = true;
+ ui.login_url = Some(zeroize::Zeroizing::new(
+ "https://example.test/private-nonce".into(),
+ ));
+ let output = rendered(80, 24, &TranscriptState::new("client"), &mut ui);
+ assert!(!output.contains("private-nonce"));
+ for action in ["login-open", "login-copy", "login-cancel"] {
+ assert!(ui
+ .hits
+ .iter()
+ .any(|hit| hit.action == Action::Command(action)));
+ }
+}
diff --git a/crates/openhuman-tui/src/runner.rs b/crates/openhuman-tui/src/runner.rs
index c99c94c444..e11626d9a5 100644
--- a/crates/openhuman-tui/src/runner.rs
+++ b/crates/openhuman-tui/src/runner.rs
@@ -37,6 +37,7 @@ pub fn run_from_cli(args: &[String]) -> anyhow::Result<()> {
let mut no_alt_screen = false;
let mut no_mouse = false;
let mut demo = false;
+ let mut bench = false;
let mut provider: Option<String> = None;
let mut model: Option<String> = None;
let mut prompt_parts = Vec::new();
@@ -44,6 +45,13 @@ pub fn run_from_cli(args: &[String]) -> anyhow::Result<()> {
let mut i = 0usize;
while i < args.len() {
match args[i].as_str() {
+ "--no-telemetry" => {
+ i += 1;
+ }
+ "--bench" => {
+ bench = true;
+ i += 1;
+ }
"--demo" => {
demo = true;
i += 1;
@@ -110,6 +118,9 @@ pub fn run_from_cli(args: &[String]) -> anyhow::Result<()> {
}
}
+ if bench {
+ return super::benchmark::run();
+ }
if demo {
return super::demo::run(no_mouse);
}
@@ -284,6 +295,8 @@ fn print_help() {
println!("and account settings. Runs the core in-process — no server, no ports.");
println!();
println!(" --demo Offline interactive UI preview (no model calls).");
+ println!(" --bench Reproducible offline viewport/render benchmark (JSON).");
+ println!(" --no-telemetry Skip the host crash-report client for isolated profiling.");
println!(" --no-mouse Keep native terminal mouse selection.");
println!(" --thread <id> Attach to an existing conversation thread.");
println!(" --new Force a new thread (default when --thread is omitted).");
diff --git a/crates/openhuman-tui/src/session.rs b/crates/openhuman-tui/src/session.rs
index 85cb0089a7..eee2b37ab9 100644
--- a/crates/openhuman-tui/src/session.rs
+++ b/crates/openhuman-tui/src/session.rs
@@ -9,6 +9,40 @@ use async_trait::async_trait;
use openhuman_rpc::embed::CoreRuntime;
use openhuman_rpc::tinyhumans::{ClientHeaders, CoreLink, SessionManager};
+#[path = "browser_login.rs"]
+mod browser_login;
+pub use browser_login::{open_browser, BrowserLogin, LoginCancellation, LoginProvider};
+
+/// Restore the persisted account and refresh its backend profile. The manager
+/// clears a rejected session and retains cached identity during an outage.
+pub async fn refresh_session<L: CoreLink>(
+ manager: &Arc<SessionManager<L>>,
+) -> Result<openhuman_rpc::tinyhumans::SessionState, String> {
+ match manager.current_user(true).await {
+ Ok(_) | Err(openhuman_rpc::tinyhumans::SessionError::Rejected(_)) => {}
+ Err(error) => {
+ return Err(safe_session_error(
+ error,
+ "Could not refresh the signed-in account.",
+ ))
+ }
+ }
+ manager
+ .state()
+ .await
+ .map_err(|error| safe_session_error(error, "Could not read the signed-in account."))
+}
+
+fn safe_session_error(error: openhuman_rpc::tinyhumans::SessionError, fallback: &str) -> String {
+ match error {
+ openhuman_rpc::tinyhumans::SessionError::Backend(message)
+ | openhuman_rpc::tinyhumans::SessionError::Core(message)
+ if message.contains("SESSION_BACKEND_MISMATCH") =>
+ "SESSION_BACKEND_MISMATCH: This session belongs to another backend. Restore that backend or start sign-in again.".into(),
+ _ => fallback.to_string(),
+ }
+}
+
/// `CoreLink` over `CoreRuntime::invoke` — no HTTP, no bearer.
pub struct InProcessLink(pub Arc<CoreRuntime>);
diff --git a/crates/openhuman-tui/src/state.rs b/crates/openhuman-tui/src/state.rs
index b59b3f73cc..83b1fa9282 100644
--- a/crates/openhuman-tui/src/state.rs
+++ b/crates/openhuman-tui/src/state.rs
@@ -12,7 +12,7 @@
use super::activity::{Activity, Status};
use openhuman_rpc::embed::chat_surface::WebChannelEvent;
-use std::collections::HashMap;
+use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
static REVISION: AtomicU64 = AtomicU64::new(1);
@@ -78,11 +78,14 @@ pub struct TranscriptState {
cur_thinking: Option<usize>,
activity_index: HashMap<String, usize>,
sequences: HashMap<String, u64>,
+ viewport_revision: u64,
+ viewport_changes: VecDeque<(u64, usize)>,
}
impl TranscriptState {
/// Create an empty transcript bound to `client_id`.
pub fn new(client_id: impl Into<String>) -> Self {
+ let viewport_revision = revision();
Self {
client_id: client_id.into(),
thread_id: String::new(),
@@ -92,6 +95,8 @@ impl TranscriptState {
cur_thinking: None,
activity_index: HashMap::new(),
sequences: HashMap::new(),
+ viewport_revision,
+ viewport_changes: VecDeque::from([(viewport_revision, 0)]),
}
}
@@ -100,6 +105,44 @@ impl TranscriptState {
&self.entries
}
+ pub(crate) fn viewport_revision(&self) -> u64 {
+ self.viewport_revision
+ }
+
+ /// Changes after a known snapshot; an expired or foreign snapshot requires rebuilding.
+ pub(crate) fn viewport_changes_since(&self, prior: u64) -> Option<Vec<usize>> {
+ if prior == self.viewport_revision {
+ return Some(Vec::new());
+ }
+ let position = self
+ .viewport_changes
+ .iter()
+ .position(|(token, _)| *token == prior)?;
+ let mut indices: Vec<_> = self
+ .viewport_changes
+ .iter()
+ .skip(position + 1)
+ .map(|(_, index)| *index)
+ .collect();
+ indices.sort_unstable();
+ indices.dedup();
+ Some(indices)
+ }
+
+ fn viewport_changed(&mut self, index: usize) {
+ self.viewport_revision = revision();
+ self.viewport_changes
+ .push_back((self.viewport_revision, index));
+ if self.viewport_changes.len() > 128 {
+ self.viewport_changes.pop_front();
+ }
+ }
+
+ fn viewport_reset(&mut self) {
+ self.viewport_changes.clear();
+ self.viewport_changed(0);
+ }
+
/// Whether a turn is currently streaming.
pub fn is_streaming(&self) -> bool {
self.streaming
@@ -115,6 +158,7 @@ impl TranscriptState {
}
pub fn clear(&mut self) {
+ self.viewport_reset();
self.entries.clear();
self.activity_index.clear();
self.cur_assistant = None;
@@ -154,6 +198,7 @@ impl TranscriptState {
/// Replace the view with a newest-first `threads.transcript_get` page.
pub fn load_transcript(&mut self, value: &serde_json::Value) {
+ self.viewport_reset();
self.entries.clear();
self.activity_index.clear();
self.sequences.clear();
@@ -172,6 +217,7 @@ impl TranscriptState {
/// Resets the streaming cursors so the next `text_delta` / `thinking_delta`
/// opens fresh assistant / thinking entries for this turn.
pub fn begin_user_turn(&mut self, message: impl Into<String>) {
+ self.viewport_changed(self.entries.len());
let text = message.into();
log::debug!("[tui] state: begin_user_turn len={}", text.len());
self.entries.push(Entry::new(EntryKind::User, text));
@@ -182,6 +228,7 @@ impl TranscriptState {
/// Push a local system/status note (e.g. "Cancelled", connection info).
pub fn push_system(&mut self, text: impl Into<String>) {
+ self.viewport_changed(self.entries.len());
let text = text.into();
log::debug!("[tui] state: push_system len={}", text.len());
self.entries.push(Entry::new(EntryKind::System, text));
@@ -231,6 +278,7 @@ impl TranscriptState {
"tool_call" | "tool_result" | "tool_args_delta" => self.apply_activity(ev, false),
event if event.starts_with("subagent_") => self.apply_activity(ev, true),
"artifact_pending" | "artifact_ready" | "artifact_failed" => {
+ self.viewport_changed(self.entries.len());
let status = ev.event.trim_start_matches("artifact_");
let detail = ev
.message
@@ -256,6 +304,7 @@ impl TranscriptState {
// `full_response` is authoritative — it replaces whatever the
// streamed text deltas accumulated (they can lag / be partial).
if let Some(full) = ev.full_response.as_deref() {
+ self.viewport_changed(self.cur_assistant.unwrap_or(self.entries.len()));
match self.cur_assistant {
Some(idx) => {
self.entries[idx].text = full.to_string();
@@ -269,6 +318,7 @@ impl TranscriptState {
self.finish_turn();
}
"chat_error" => {
+ self.viewport_changed(self.entries.len());
let mut msg = ev.message.as_deref().unwrap_or("Unknown error").to_string();
if ev.error_retryable == Some(true) {
msg.push_str(" · retryable");
@@ -278,7 +328,8 @@ impl TranscriptState {
}
log::debug!("[tui] state: chat_error {msg}");
self.entries.push(Entry::new(EntryKind::Error, msg));
- for entry in &mut self.entries {
+ let mut changed = Vec::new();
+ for (index, entry) in self.entries.iter_mut().enumerate() {
if let Some(activity) = &mut entry.activity {
if activity.status == Status::Running && !activity.child {
activity.status = if ev.error_type.as_deref() == Some("cancelled") {
@@ -288,9 +339,13 @@ impl TranscriptState {
};
entry.text = activity.summary();
entry.revision = revision();
+ changed.push(index);
}
}
}
+ for index in changed {
+ self.viewport_changed(index);
+ }
self.finish_turn();
}
other => {
@@ -300,6 +355,7 @@ impl TranscriptState {
}
fn append_assistant(&mut self, delta: &str) {
+ self.viewport_changed(self.cur_assistant.unwrap_or(self.entries.len()));
match self.cur_assistant {
Some(idx) => {
self.entries[idx].text.push_str(delta);
@@ -314,6 +370,7 @@ impl TranscriptState {
}
fn append_thinking(&mut self, delta: &str) {
+ self.viewport_changed(self.cur_thinking.unwrap_or(self.entries.len()));
match self.cur_thinking {
Some(idx) => {
self.entries[idx].text.push_str(delta);
@@ -337,6 +394,7 @@ impl TranscriptState {
if let Some(entry) = self.entries.get_mut(index) {
entry.expanded = !entry.expanded;
entry.revision = revision();
+ self.viewport_changed(index);
}
}
@@ -394,6 +452,7 @@ impl TranscriptState {
activity.update(ev);
entry.text = activity.summary();
entry.revision = revision();
+ self.viewport_changed(index);
}
fn push_projected_item(&mut self, item: &serde_json::Value) {
diff --git a/crates/openhuman-tui/src/state_tests.rs b/crates/openhuman-tui/src/state_tests.rs
index 33eca8235d..cc7fc85010 100644
--- a/crates/openhuman-tui/src/state_tests.rs
+++ b/crates/openhuman-tui/src/state_tests.rs
@@ -1,5 +1,28 @@
use super::*;
+#[test]
+fn viewport_journal_is_bounded_and_identifies_non_tail_changes_and_resets() {
+ let mut state = TranscriptState::new("client");
+ state.push_system("first");
+ state.push_system("second");
+ let snapshot = state.viewport_revision();
+ assert_eq!(state.viewport_changes_since(snapshot), Some(vec![]));
+ state.toggle_entry(0);
+ state.push_system("third");
+ assert_eq!(state.viewport_changes_since(snapshot), Some(vec![0, 2]));
+ for _ in 0..140 {
+ state.push_system("more");
+ }
+ assert_eq!(state.viewport_changes.len(), 128);
+ assert_eq!(state.viewport_changes_since(snapshot), None);
+ let snapshot = state.viewport_revision();
+ state.load_transcript(&serde_json::json!({"items":[]}));
+ assert_eq!(state.viewport_changes_since(snapshot), None);
+ let snapshot = state.viewport_revision();
+ state.clear();
+ assert_eq!(state.viewport_changes_since(snapshot), None);
+}
+
const CLIENT: &str = "tui-abc123";
fn ev(event: &str) -> WebChannelEvent {
diff --git a/crates/openhuman-tui/src/ui_state.rs b/crates/openhuman-tui/src/ui_state.rs
index 6d93a84ddb..bc0b9a624b 100644
--- a/crates/openhuman-tui/src/ui_state.rs
+++ b/crates/openhuman-tui/src/ui_state.rs
@@ -67,16 +67,23 @@ impl ConfigItem {
pub enum SettingsAction {
ViewAccount,
Login,
+ LoginToken,
Logout,
}
impl SettingsAction {
- pub const ALL: [Self; 3] = [Self::ViewAccount, Self::Login, Self::Logout];
+ pub const ALL: [Self; 4] = [
+ Self::ViewAccount,
+ Self::Login,
+ Self::LoginToken,
+ Self::Logout,
+ ];
pub fn label(self) -> &'static str {
match self {
Self::ViewAccount => "View account",
- Self::Login => "Log in with one-time token",
+ Self::Login => "Sign in with your browser",
+ Self::LoginToken => "Paste a one-time login token",
Self::Logout => "Log out",
}
}
@@ -123,11 +130,20 @@ pub struct UiState {
pub effective_model: String,
pub overlay_generation: u64,
pub overlay_tx: Option<tokio::sync::mpsc::UnboundedSender<super::effects::OverlayReply>>,
- pub auth_tx: Option<tokio::sync::mpsc::UnboundedSender<Result<(), String>>>,
+ pub auth_tx: Option<tokio::sync::mpsc::UnboundedSender<super::account::Message>>,
pub auth_pending: bool,
+ pub auth_browser: bool,
pub policy_enabled: bool,
pub overlay_area: ratatui::layout::Rect,
pub suggestion_selected: usize,
+ pub auth_generation: u64,
+ pub auth_user_id: Option<String>,
+ pub auth_profile_id: Option<String>,
+ pub authenticated: bool,
+ pub auth_operation: Option<super::account::Operation>,
+ pub login_url: Option<zeroize::Zeroizing<String>>,
+ pub login_port: Option<u16>,
+ pub login_cancel: Option<super::session::LoginCancellation>,
}
impl UiState {
@@ -204,9 +220,18 @@ impl UiState {
overlay_tx: None,
auth_tx: None,
auth_pending: false,
+ auth_browser: false,
policy_enabled: false,
overlay_area: Default::default(),
suggestion_selected: 0,
+ auth_generation: 0,
+ auth_user_id: None,
+ auth_profile_id: None,
+ authenticated: false,
+ auth_operation: None,
+ login_url: None,
+ login_port: None,
+ login_cancel: None,
}
}
@@ -220,6 +245,9 @@ impl UiState {
impl Drop for UiState {
fn drop(&mut self) {
+ if let Some(cancel) = &self.login_cancel {
+ cancel.cancel();
+ }
if let Some(token) = &mut self.login_token {
token.zeroize();
}
diff --git a/crates/openhuman-tui/src/viewport.rs b/crates/openhuman-tui/src/viewport.rs
index da0841eefa..e02769b376 100644
--- a/crates/openhuman-tui/src/viewport.rs
+++ b/crates/openhuman-tui/src/viewport.rs
@@ -1,13 +1,21 @@
//! Cached cell-wrapped blocks and indexed viewport lookup.
use super::state::{EntryKind, TranscriptState};
use super::theme::safe_text;
+use std::collections::BTreeSet;
use unicode_width::UnicodeWidthChar;
#[derive(Default)]
pub struct ViewportCache {
width: u16,
blocks: Vec<CachedBlock>,
- ends: Vec<usize>,
+ heights: HeightIndex,
+ resident: BTreeSet<usize>,
+ revision: u64,
+ height: u16,
+ offset: usize,
+ anchor: Option<(usize, usize)>,
+ #[cfg(test)]
+ recomputed: usize,
}
struct CachedBlock {
revision: u64,
@@ -23,6 +31,51 @@ pub struct VisibleRow {
pub kind: EntryKind,
}
+/// Dynamic Fenwick tree: append and point updates preserve logarithmic row lookup.
+#[derive(Default)]
+struct HeightIndex {
+ tree: Vec<usize>,
+ total: usize,
+}
+impl HeightIndex {
+ fn prefix(&self, mut count: usize) -> usize {
+ let mut sum = 0;
+ while count > 0 {
+ sum += self.tree[count - 1];
+ count &= count - 1;
+ }
+ sum
+ }
+ fn push(&mut self, height: usize) {
+ let index = self.tree.len() + 1;
+ let start = index - (index & index.wrapping_neg());
+ self.tree.push(height + self.total - self.prefix(start));
+ self.total += height;
+ }
+ fn update(&mut self, index: usize, before: usize, after: usize) {
+ self.total = self.total - before + after;
+ let mut index = index + 1;
+ while index <= self.tree.len() {
+ self.tree[index - 1] = self.tree[index - 1] - before + after;
+ index += index & index.wrapping_neg();
+ }
+ }
+ fn containing(&self, row: usize) -> usize {
+ let mut index = 0;
+ let mut sum = 0;
+ let mut bit = self.tree.len().checked_next_power_of_two().unwrap_or(0);
+ while bit != 0 {
+ let next = index + bit;
+ if next <= self.tree.len() && sum + self.tree[next - 1] <= row {
+ sum += self.tree[next - 1];
+ index = next;
+ }
+ bit >>= 1;
+ }
+ index
+ }
+}
+
impl ViewportCache {
pub fn rows(
&mut self,
@@ -32,67 +85,119 @@ impl ViewportCache {
offset: usize,
) -> (Vec<VisibleRow>, usize) {
let width = width.max(1);
- if self.width != width {
+ let changes = state.viewport_changes_since(self.revision);
+ let anchor = if offset > 0
+ && offset == self.offset
+ && changes.is_some()
+ && (self.width != width || self.height != height)
+ {
+ self.anchor
+ } else {
+ None
+ };
+ if self.width != width || changes.is_none() || self.blocks.len() > state.entries().len() {
self.blocks.clear();
+ self.heights = HeightIndex::default();
+ self.resident.clear();
self.width = width;
}
- self.blocks.truncate(state.entries().len());
- self.ends.clear();
- let mut total = 0usize;
- for (index, entry) in state.entries().iter().enumerate() {
- let fresh = self
- .blocks
- .get(index)
- .is_none_or(|block| block.revision != entry.revision);
- if fresh {
+ #[cfg(test)]
+ {
+ self.recomputed = 0;
+ }
+ for index in changes.unwrap_or_default() {
+ if index < self.blocks.len() {
+ let entry = &state.entries()[index];
+ if self.blocks[index].revision == entry.revision {
+ continue;
+ }
let rows = entry_rows(entry, width);
- let block = CachedBlock {
+ self.heights
+ .update(index, self.blocks[index].height, rows.len());
+ self.blocks[index] = CachedBlock {
revision: entry.revision,
height: rows.len(),
rows,
};
- if index == self.blocks.len() {
- self.blocks.push(block);
- } else {
- self.blocks[index] = block;
+ self.resident.insert(index);
+ #[cfg(test)]
+ {
+ self.recomputed += 1;
}
}
- total += self.blocks[index].height;
- self.ends.push(total);
}
- let max_scroll = total.saturating_sub(height as usize);
- let top = max_scroll.saturating_sub(offset.min(max_scroll));
- let mut index = self.ends.partition_point(|end| *end <= top);
+ for entry in &state.entries()[self.blocks.len()..] {
+ let rows = entry_rows(entry, width);
+ let block = CachedBlock {
+ revision: entry.revision,
+ height: rows.len(),
+ rows,
+ };
+ self.heights.push(block.height);
+ self.resident.insert(self.blocks.len());
+ self.blocks.push(block);
+ #[cfg(test)]
+ {
+ self.recomputed += 1;
+ }
+ }
+ self.revision = state.viewport_revision();
+ let max_scroll = self.heights.total.saturating_sub(height as usize);
+ let top = anchor
+ .filter(|(entry, _)| *entry < self.blocks.len())
+ .map(|(entry, line)| {
+ self.heights.prefix(entry) + line.min(self.blocks[entry].height.saturating_sub(1))
+ })
+ .unwrap_or_else(|| max_scroll.saturating_sub(offset.min(max_scroll)))
+ .min(max_scroll);
+ self.offset = max_scroll - top;
+ self.height = height;
+ let mut index = self.heights.containing(top);
let first_visible = index;
- let mut absolute = if index == 0 { 0 } else { self.ends[index - 1] };
+ let mut absolute = self.heights.prefix(index);
+ self.anchor = (index < self.blocks.len()).then_some((index, top - absolute));
let mut rows = Vec::with_capacity(height as usize);
while index < self.blocks.len() && rows.len() < height as usize {
if self.blocks[index].rows.is_empty() {
self.blocks[index].rows = entry_rows(&state.entries()[index], width);
+ self.resident.insert(index);
}
- for (line, text) in self.blocks[index].rows.iter().enumerate() {
- if absolute >= top && rows.len() < height as usize {
- rows.push(VisibleRow {
- text: text.clone(),
- entry: index,
- first: line == 0,
- kind: state.entries()[index].kind,
- });
- }
- absolute += 1;
+ for (line, text) in self.blocks[index]
+ .rows
+ .iter()
+ .enumerate()
+ .skip(top.saturating_sub(absolute))
+ .take(height as usize - rows.len())
+ {
+ rows.push(VisibleRow {
+ text: text.clone(),
+ entry: index,
+ first: line == 0,
+ kind: state.entries()[index].kind,
+ });
}
+ absolute += self.blocks[index].height;
index += 1;
}
- for (index, block) in self.blocks.iter_mut().enumerate() {
- if index < first_visible.saturating_sub(64) || index > first_visible + 128 {
- block.rows.clear();
- block.rows.shrink_to_fit();
- }
+ let stale: Vec<_> = self
+ .resident
+ .iter()
+ .copied()
+ .filter(|index| {
+ *index < first_visible.saturating_sub(64) || *index > first_visible + 128
+ })
+ .collect();
+ for index in stale {
+ self.blocks[index].rows = Vec::new();
+ self.resident.remove(&index);
}
(rows, max_scroll)
}
pub fn total_rows(&self) -> usize {
- self.ends.last().copied().unwrap_or(0)
+ self.heights.total
+ }
+ pub fn resolved_offset(&self) -> usize {
+ self.offset
}
}
diff --git a/crates/openhuman-tui/src/viewport_tests.rs b/crates/openhuman-tui/src/viewport_tests.rs
index 8e1ed2d0fc..d52e59244b 100644
--- a/crates/openhuman-tui/src/viewport_tests.rs
+++ b/crates/openhuman-tui/src/viewport_tests.rs
@@ -37,4 +37,180 @@ fn changing_a_message_invalidates_only_its_cached_block() {
state.push_system("new");
let (rows, _) = cache.rows(&state, 80, 20, 0);
assert!(rows.iter().any(|row| row.text == "new"));
+ assert_eq!(cache.recomputed, 1);
+}
+
+#[test]
+fn idle_and_old_entry_edits_do_not_revisit_settled_history() {
+ let mut state = TranscriptState::new("test");
+ for _ in 0..10_000 {
+ state.push_system("one line");
+ }
+ let mut cache = ViewportCache::default();
+ cache.rows(&state, 80, 20, 0);
+ assert_eq!(cache.recomputed, 10_000);
+ cache.rows(&state, 80, 20, 0);
+ assert_eq!(cache.recomputed, 0);
+ state.toggle_entry(1);
+ cache.rows(&state, 80, 20, 0);
+ assert_eq!(cache.recomputed, 1);
+ assert!(cache.resident.len() <= 193);
+ state.push_system("tail");
+ cache.rows(&state, 80, 20, 0);
+ assert_eq!(cache.recomputed, 1);
+}
+
+#[test]
+fn indexed_rows_equal_full_wrapping_after_updates_resizes_and_expired_journal() {
+ use openhuman_rpc::embed::chat_surface::WebChannelEvent;
+ let mut state = TranscriptState::new("test");
+ state.apply_event(&WebChannelEvent {
+ event: "tool_call".into(),
+ client_id: "test".into(),
+ tool_call_id: Some("first".into()),
+ tool_name: Some("tool".into()),
+ ..Default::default()
+ });
+ for index in 0..150 {
+ state.push_system(format!("entry {index} 界e\u{301}\nnext"));
+ }
+ let mut cache = ViewportCache::default();
+ for step in 0..12 {
+ if step == 3 {
+ state.toggle_entry(0);
+ }
+ if step == 4 {
+ state.apply_event(&WebChannelEvent {
+ event: "tool_result".into(),
+ client_id: "test".into(),
+ tool_call_id: Some("first".into()),
+ output: Some("a\nb\nc".into()),
+ success: Some(true),
+ ..Default::default()
+ });
+ }
+ if step == 5 {
+ for _ in 0..140 {
+ state.push_system("new tail");
+ }
+ }
+ if step == 10 {
+ state.clear();
+ state.push_system("replacement");
+ }
+ let width = [7, 30, 80][step % 3];
+ let reference: Vec<_> = state
+ .entries()
+ .iter()
+ .enumerate()
+ .flat_map(|(index, entry)| {
+ entry_rows(entry, width)
+ .into_iter()
+ .map(move |text| (index, text))
+ })
+ .collect();
+ for offset in [0, 5, 71, usize::MAX] {
+ // A new explicit offset disables resize anchoring for this reference comparison.
+ cache.offset = offset.wrapping_add(1);
+ let (rows, max) = cache.rows(&state, width, 13, offset);
+ assert_eq!(max, reference.len().saturating_sub(13));
+ let top = max.saturating_sub(offset.min(max));
+ assert_eq!(
+ rows.iter()
+ .map(|row| (row.entry, row.text.clone()))
+ .collect::<Vec<_>>(),
+ reference
+ .iter()
+ .skip(top)
+ .take(13)
+ .cloned()
+ .collect::<Vec<_>>()
+ );
+ assert!(cache.resident.len() <= 193);
+ }
+ }
+}
+
+#[test]
+fn resize_keeps_scrolled_entry_visible_and_latest_follows_bottom() {
+ let mut state = TranscriptState::new("test");
+ for index in 0..100 {
+ state.push_system(format!("entry {index}: {}", "long text ".repeat(8)));
+ }
+ let mut cache = ViewportCache::default();
+ let (before, _) = cache.rows(&state, 80, 15, 100);
+ let (after, _) = cache.rows(&state, 40, 31, 100);
+ assert_eq!(before[0].entry, after[0].entry);
+ assert_ne!(cache.resolved_offset(), 100);
+ let (latest, _) = cache.rows(&state, 120, 15, 0);
+ assert_eq!(latest.last().unwrap().entry, 99);
+ assert_eq!(cache.resolved_offset(), 0);
+}
+
+#[test]
+fn switching_between_cloned_transcripts_does_not_reuse_a_foreign_snapshot() {
+ let mut state = TranscriptState::new("test");
+ state.push_system("original");
+ let mut fork = state.clone();
+ let mut cache = ViewportCache::default();
+ state.push_system("left");
+ cache.rows(&state, 80, 20, 0);
+ fork.push_system("right");
+ let (rows, _) = cache.rows(&fork, 80, 20, 0);
+ assert!(rows.iter().any(|row| row.text == "right"));
+ assert!(!rows.iter().any(|row| row.text == "left"));
+}
+
+#[test]
+fn changing_an_old_tools_height_updates_prefix_lookup_without_rebuilding_history() {
+ use openhuman_rpc::embed::chat_surface::WebChannelEvent;
+ let mut state = TranscriptState::new("test");
+ let event = |name: &str| WebChannelEvent {
+ event: name.into(),
+ client_id: "test".into(),
+ tool_call_id: Some("old".into()),
+ tool_name: Some("tool".into()),
+ ..Default::default()
+ };
+ state.apply_event(&event("tool_call"));
+ for _ in 0..300 {
+ state.push_system("settled");
+ }
+ let mut cache = ViewportCache::default();
+ cache.rows(&state, 40, 20, 0);
+ let before = cache.total_rows();
+ state.apply_event(&WebChannelEvent {
+ output: Some("first\nsecond\nthird\nfourth".into()),
+ success: Some(true),
+ ..event("tool_result")
+ });
+ state.toggle_entry(0);
+ cache.rows(&state, 40, 20, 0);
+ assert_eq!(cache.recomputed, 1);
+ assert!(cache.total_rows() > before);
+ for offset in [0, 5, 589, usize::MAX] {
+ let (rows, max) = cache.rows(&state, 40, 20, offset);
+ assert_eq!(cache.recomputed, 0);
+ let reference: Vec<_> = state
+ .entries()
+ .iter()
+ .enumerate()
+ .flat_map(|(index, entry)| {
+ entry_rows(entry, 40)
+ .into_iter()
+ .map(move |text| (index, text))
+ })
+ .collect();
+ let top = max.saturating_sub(offset.min(max));
+ assert_eq!(
+ rows.into_iter()
+ .map(|row| (row.entry, row.text))
+ .collect::<Vec<_>>(),
+ reference.into_iter().skip(top).take(20).collect::<Vec<_>>()
+ );
+ }
+ state.toggle_entry(0);
+ cache.rows(&state, 40, 20, 0);
+ assert_eq!(cache.recomputed, 1);
+ assert_eq!(cache.total_rows(), before);
}
diff --git a/docs/performance/tui-viewport.md b/docs/performance/tui-viewport.md
new file mode 100644
index 0000000000..be1fb46f02
--- /dev/null
+++ b/docs/performance/tui-viewport.md
@@ -0,0 +1,205 @@
+# TUI viewport measurements
+
+Measured 2026-10-10 on an Apple M2 Pro, x86_64 macOS process, using the
+same warm Cargo development profile before and after the viewport change.
+These are actual elapsed measurements, not timing assertions in tests.
+
+Reproduce from the checkout root:
+
+```sh
+scripts/ci-cancel-aware.sh cargo build -p openhuman-tui
+target/debug/openhuman-tui --bench
+```
+
+The command creates deterministic synthetic transcripts, uses the production
+viewport and renderer, and prints JSON. It neither boots the core nor reads
+operator conversations or credentials. Each measurement has 20 warmups and
+200 timed samples. The initial comparison used 500, 10,000, or 40,000 settled
+entries, each occupying two rows at both tested widths. The JSON calls these
+`entries` and separately reports `settled_rows` (1,000, 20,000, and 80,000).
+The viewport workload uses width minus four and height minus nine, matching
+the empty-composer chat geometry. Scroll samples advance three rows at a time.
+Streaming samples append the same 15-byte delta and redraw the growing tail;
+they include reducer processing. Full frames use ratatui's TestBackend.
+
+Raw runs are stored locally in
+`target/debug-logs/tui-performance/{before,after}.json`.
+Times below are microseconds, shown as p50 / p95.
+
+| Terminal | Entries | Viewport idle before | Viewport idle after | Scroll before | Scroll after |
+| -------- | ------: | -------------------: | ------------------: | ----------------: | --------------: |
+| 80x24 | 500 | 12.209 / 27.291 | 11.750 / 12.208 | 15.250 / 18.208 | 15.208 / 32.708 |
+| 80x24 | 10,000 | 210.334 / 235.334 | 3.917 / 4.041 | 215.083 / 234.458 | 9.917 / 13.417 |
+| 80x24 | 40,000 | 838.375 / 859.916 | 4.250 / 4.375 | 843.042 / 964.208 | 10.583 / 14.333 |
+| 120x40 | 500 | 11.875 / 12.000 | 5.125 / 5.250 | 14.166 / 16.792 | 11.042 / 15.708 |
+| 120x40 | 10,000 | 210.584 / 224.125 | 5.334 / 5.500 | 216.250 / 248.417 | 11.208 / 14.750 |
+| 120x40 | 40,000 | 840.500 / 933.166 | 5.375 / 5.667 | 842.667 / 891.667 | 11.292 / 14.917 |
+
+| Terminal | Entries | Full frame before | Full frame after | Streaming tail before | Streaming tail after |
+| -------- | ------: | ------------------: | ------------------: | --------------------: | -------------------: |
+| 80x24 | 500 | 562.709 / 758.958 | 555.042 / 751.167 | 111.000 / 157.542 | 83.833 / 142.375 |
+| 80x24 | 10,000 | 758.750 / 868.000 | 590.833 / 707.667 | 290.916 / 350.459 | 87.625 / 150.084 |
+| 80x24 | 40,000 | 1384.750 / 1432.416 | 566.125 / 632.500 | 926.792 / 1062.959 | 86.667 / 148.417 |
+| 120x40 | 500 | 1074.833 / 1095.875 | 1112.417 / 1145.500 | 88.917 / 145.000 | 85.125 / 144.208 |
+| 120x40 | 10,000 | 1277.250 / 1330.959 | 1117.250 / 1175.833 | 290.417 / 345.416 | 85.417 / 145.042 |
+| 120x40 | 40,000 | 1936.625 / 2056.208 | 1124.250 / 1162.542 | 923.125 / 1009.958 | 88.000 / 146.042 |
+
+An expanded tool entry originating from 40,000 lines (approximately 1 MB)
+measured 0.958 / 1.000 before and 1.083 / 1.250 after in warm viewport
+rendering. This exercises the existing bounded activity projection and
+20-line expanded display. Ingesting the original output is outside that
+measurement; these numbers do not claim 1 MB of text can be parsed in 1 us.
+
+The runner also includes 250, 5,000, and 20,000 entries to cover exactly 500,
+10,000, and 40,000 settled rows. A supplemental optimized run, saved in
+`target/debug-logs/tui-performance/after-exact-rows.json`, measured:
+
+| Terminal | Settled rows | Viewport idle | Scroll | Full frame | Streaming tail |
+| -------- | -----------: | ------------: | --------------: | ------------------: | ---------------: |
+| 80x24 | 500 | 4.542 / 5.375 | 11.125 / 15.958 | 583.541 / 761.209 | 85.833 / 145.417 |
+| 80x24 | 10,000 | 4.000 / 4.125 | 9.834 / 13.417 | 556.042 / 613.625 | 81.625 / 141.542 |
+| 80x24 | 40,000 | 4.000 / 4.167 | 9.834 / 13.375 | 547.333 / 561.291 | 82.042 / 140.000 |
+| 120x40 | 500 | 5.208 / 5.417 | 9.709 / 13.875 | 1070.042 / 1110.125 | 81.291 / 136.583 |
+| 120x40 | 10,000 | 5.208 / 5.334 | 10.708 / 14.333 | 1068.292 / 1097.167 | 80.625 / 136.708 |
+| 120x40 | 40,000 | 5.209 / 5.375 | 10.625 / 14.125 | 1077.125 / 1176.166 | 80.667 / 140.000 |
+
+## Finding and change
+
+Although wrapped text was cached, every frame still visited every entry to
+check its revision and rebuild cumulative heights, then visited every cached
+block again to evict rows. At 40,000 entries this cost about 0.84 ms even when
+the conversation had not changed. Separately timed viewport and full-frame
+measurements show that history scan accounting for most of the frame cost
+increase between 500 and 40,000 entries.
+
+The reducer now supplies a bounded 128-change journal. Unchanged snapshots
+need no history scan; point changes identify exact blocks, including older
+tool entries. A dynamic Fenwick tree updates heights and locates the visible
+entry in logarithmic time. Eviction visits only resident formatted blocks,
+bounded to a window of at most 193 entries. Rendering skips the offscreen
+prefix inside a large block. At 40,000 entries the measured idle viewport
+p50 improves about 197 times at 80x24; the full frame improves 2.45 times.
+
+The composer is anchored to the bottom of the chat area with its status line
+below it. Its minimum height reserves separate editor and control rows even
+at 24x8. Resize reflows the editor and preserves a scrolled transcript's top
+entry and relative wrapped line; following the latest message stays at the
+bottom. Too-small terminals clear stale hit geometry.
+
+## Actual terminal measurements
+
+The separate POSIX PTY runner exercises the real binary and crossterm input:
+
+```sh
+python3 scripts/debug/tui-profile.py --columns 80 --rows 24 --samples 40 \
+ --output target/debug-logs/tui-performance/pty-after-80x24.json
+python3 scripts/debug/tui-profile.py --columns 120 --rows 40 --samples 40 \
+ --output target/debug-logs/tui-performance/pty-after-120x40.json
+```
+
+It starts an isolated `--demo` child, uses fresh workspace and action directories
+plus an explicit empty dotenv file under `target/debug-logs`, and allowlists inherited
+environment variables so keys, sessions, telemetry settings, and restart
+delays cannot leak into the run. It answers cursor-position queries if a
+terminal backend emits them (the measured binary emitted none). Teardown
+drains escape output before waiting for the child to exit. Synthetic input
+uses bracketed paste, with changing text so ratatui's differential output
+still contains an observable marker. A small cursor/erase screen tracker
+recognizes the completed marker even when individual key frames omit unchanged
+cells. Each paste follows a clear operation
+by 10 ms. Both measured processes exited normally with code zero.
+
+| Terminal | Startup to footer paint | Idle output over 2 s | Idle CPU | RSS | Input p50 / p95 | Input max |
+| -------- | ----------------------: | -------------------: | -------: | ---------: | ---------------: | --------: |
+| 80x24 | 62.178 ms | 0 bytes | 0 ms | 16,208 KiB | 3.726 / 4.354 ms | 4.764 ms |
+| 120x40 | 60.245 ms | 0 bytes | 0 ms | 16,480 KiB | 3.856 / 6.452 ms | 6.495 ms |
+
+A supplemental 80x24 run with `--input-mode keys --samples 20` sent 21 or
+22 individual key events per burst. It measured 13.043 / 13.568 ms p50 / p95
+and 19,300 total output bytes, compared with 4,720 bytes for 40 paste samples.
+This reflects the demo loop painting after each key; paste is one event.
+
+CPU is measured with `ps` and has 10 ms resolution on macOS: a zero reading
+does not prove zero instructions executed. RSS is a process snapshot rather
+than a peak allocation counter. Input measurements include event parsing,
+rendering, terminal writes, and the profiler's scheduling. Startup has one
+sample per terminal and includes process spawn and library initialization.
+These are optimized-binary observations with no PTY baseline; no terminal
+before/after improvement is claimed. Demo mode boots neither core nor model
+and does not measure the live loop's 16 ms frame coalescing.
+
+The screen parser has four deterministic tests for differential paints,
+placeholder erasure, split cursor/OSC sequences, styles, and split UTF-8 with
+wide and combining characters. Run them with:
+
+```sh
+python3 scripts/debug/tui-profile_tests.py
+```
+
+### Live event loop
+
+Four further runs use `--mode live`, which starts the real in-process core and
+event loop with `--new --no-telemetry`. Workspace, action directory, credential
+scope, and dotenv are fresh; no sign-in or model request is initiated. Each
+case has 40 input samples and a two-second idle window. The final binary uses
+a 16 ms minimum frame interval while dirty and draws no idle frames. All four
+saved reports have the same SHA-256
+`97d86f1428e49e5e534654278c04d4c79939fb498e8cb4c072814d496ae39850`,
+report no binary change during the run, and exited normally with code zero.
+
+```sh
+python3 scripts/debug/tui-profile.py --mode live --input-mode paste \
+ --columns 80 --rows 24 --samples 40 \
+ --output target/debug-logs/tui-performance/pty-live-paste-80x24.json
+```
+
+Repeat with `--input-mode keys` and/or `--columns 120 --rows 40` for the other
+cases. Paste supplies one event; keys supplies 21 or 22 individual events.
+The 80x24 paste case was repeated after a concurrent offline benchmark ended;
+the table uses that quiet repeat.
+
+| Terminal | Input | Startup | Idle output | Idle CPU | RSS | Input p50 / p95 | Input max | Total input output |
+| -------- | ----- | ---------: | ----------: | -------: | ---------: | -----------------: | --------: | -----------------: |
+| 80x24 | Paste | 410.989 ms | 0 bytes | 0 ms | 78,976 KiB | 7.509 / 8.688 ms | 8.988 ms | 2,716 bytes |
+| 120x40 | Paste | 428.299 ms | 0 bytes | 10 ms | 80,176 KiB | 11.620 / 15.032 ms | 15.603 ms | 2,756 bytes |
+| 80x24 | Keys | 400.491 ms | 0 bytes | 0 ms | 79,712 KiB | 10.323 / 13.254 ms | 13.614 ms | 2,716 bytes |
+| 120x40 | Keys | 399.581 ms | 0 bytes | 0 ms | 79,552 KiB | 11.241 / 18.511 ms | 33.412 ms | 2,803 bytes |
+
+The live key bursts emit about as many bytes as single paste events because
+the dirty-frame interval coalesces individual key paints. The interval is
+not a hard input latency guarantee: parser delivery, draw time, and operating
+system scheduling remain outside that interval, and the 120x40 key run shows
+a 33.412 ms outlier. These measurements include actual terminal I/O and core
+startup; the viewport/TestBackend tables measure separate renderer work with
+synthetic settled history. No PTY baseline or network/auth responsiveness
+improvement is claimed. Credential-free startup is not a benchmark of restoring
+an existing user's account.
+
+The final offline binary was also checked for consistency: at 80x24 and 40,000
+settled rows (20,000 entries), viewport idle measured 4.208 / 5.459 us and full
+frame idle measured 575.084 / 622.625 us; at 80,000 settled rows (40,000 entries),
+the values were 4.291 / 4.584 us and 576.000 / 602.792 us. These final observations
+support the earlier scaling result; they do not replace the paired before/after
+measurements.
+
+## Verification and limits
+
+Behavior tests compare indexed output to full reference wrapping across
+widths, old tool updates, expansion, journal expiry, clear, and replacement.
+They also verify idle recomputation is zero, an append or point edit
+recomputes one block, the resident window is bounded, cloned transcripts
+cannot reuse another branch's snapshot, and resize preserves the viewed
+entry. Composer tests resize through 80x24, 120x40, 40x12, and 24x8 and
+verify cursor and hit targets remain inside the current editor geometry.
+There are no flaky elapsed-time assertions.
+
+These results are development-profile measurements, with no login, model
+inference, or release-performance claim. Viewport/TestBackend measurements
+exclude terminal I/O; the PTY measurements include it. Concurrent development
+on the same machine adds noise; the 500-entry scrolling p95 and 120x40 small
+full-frame case show small regressions in this run. Cold initialization,
+width changes, transcript replacement, and expired journals still rebuild
+history and are not covered by the warm figures. Metadata scales with entry
+count, while formatted row retention is bounded by entry count rather than
+bytes. A very large assistant message remains one block and streaming it
+rewraps that block; increasing its length can still increase streaming cost.
diff --git a/docs/plans/2026-10-10-02-minimal-terminal-ui-spec.md b/docs/plans/2026-10-10-02-minimal-terminal-ui-spec.md
index 0a1e848819..1790cccccb 100644
--- a/docs/plans/2026-10-10-02-minimal-terminal-ui-spec.md
+++ b/docs/plans/2026-10-10-02-minimal-terminal-ui-spec.md
@@ -216,4 +216,6 @@ The initial implementation now covers the conversation shell, shared actions and
Verified locally: baseline tests, TUI unit/CLI tests, build, scoped Clippy, crate-chain/layout checks, and live/demo startup plus terminal mouse navigation in macOS tmux. The broader dependency Clippy command encounters a pre-existing `type_complexity` lint in the core relay store. Windows/Linux terminal behavior, real provider execution, and successful backend login were not exercised in this implementation session.
-Remaining extensions: browser/device-code login, session branching/older-page loading, scoped child steering/cancellation, interactive question forms, persistent appearance preferences, and Markdown/diff-specific rich formatting. Current themes are process-local; child/output inspectors show stored bounded previews. The performance budgets above remain measurement targets; the implementation does not claim every budget has been met on every platform.
+Follow-up implementation adds Medulla-style browser login through the shared TinyHumans session owner, background saved-session validation, issuing-backend binding for new sessions, mouse login controls, and a bottom-anchored responsive composer. The indexed viewport avoids full-history scans on settled paints and point edits. Offline benchmarks and isolated real-PTY profiling are documented in [the performance report](../performance/tui-viewport.md); these are development-profile observations on one machine, not cross-platform guarantees. Successful interactive provider sign-in is still an operator validation step.
+
+Remaining extensions: device-code login, session branching/older-page loading, scoped child steering/cancellation, interactive question forms, persistent appearance preferences, and Markdown/diff-specific rich formatting. Current themes are process-local; child/output inspectors show stored bounded previews. The performance budgets above remain measurement targets; the implementation does not claim every budget has been met on every platform.
diff --git a/scripts/debug/tui-profile.py b/scripts/debug/tui-profile.py
new file mode 100644
index 0000000000..d8115002c8
--- /dev/null
+++ b/scripts/debug/tui-profile.py
@@ -0,0 +1,302 @@
+#!/usr/bin/env python3
+"""Measure synthetic input in an isolated POSIX PTY with no operator credentials."""
+import argparse
+import codecs
+import errno
+import fcntl
+import hashlib
+import json
+import os
+import platform
+import re
+import selectors
+import struct
+import subprocess
+import termios
+import time
+import tempfile
+import unicodedata
+from pathlib import Path
+
+CSI = re.compile(rb"\x1b\[[0-?]*[ -/]*[@-~]")
+
+
+class Screen:
+ """Track the cursor/erase subset emitted by crossterm's differential renderer.
+
+ Searching stripped bytes alone fails for individual key events: unchanged
+ cells are omitted, and erasing a placeholder can interrupt the marker.
+ """
+
+ def __init__(self, columns, rows):
+ self.columns, self.rows = columns, rows
+ self.x = self.y = 0
+ self.cells = {}
+ self.pending = b""
+ self.decoder = codecs.getincrementaldecoder("utf-8")("replace")
+
+ def contains(self, marker):
+ marker = marker.decode("ascii")
+ return any(marker in "".join(self.cells.get((x,y), " ")
+ for x in range(self.columns)) for y in range(self.rows))
+
+ def feed(self, raw):
+ self.pending += raw
+ while self.pending:
+ if self.pending.startswith(b"\x1b["):
+ match = CSI.match(self.pending)
+ if not match:
+ return
+ sequence = match.group()
+ self.pending = self.pending[len(sequence):]
+ params = sequence[2:-1].decode("ascii")
+ if params.startswith(("?",">","<")):
+ continue
+ values = [int(part) if part.isdigit() else 0 for part in params.split(";")]
+ first = values[0] or 1
+ command = sequence[-1:]
+ if command in (b"H",b"f"):
+ self.y = first - 1
+ self.x = (values[1] if len(values)>1 and values[1] else 1) - 1
+ elif command == b"G": self.x = first - 1
+ elif command == b"d": self.y = first - 1
+ elif command == b"A": self.y = max(0,self.y-first)
+ elif command == b"B": self.y += first
+ elif command == b"C": self.x += first
+ elif command == b"D": self.x = max(0,self.x-first)
+ elif command == b"J":
+ mode = values[0]
+ for position in list(self.cells):
+ if mode in (2,3) or (mode == 0 and (position[1],position[0]) >= (self.y,self.x)) \
+ or (mode == 1 and (position[1],position[0]) <= (self.y,self.x)):
+ del self.cells[position]
+ elif command == b"K":
+ mode = values[0]
+ for x in range(self.columns):
+ if mode == 2 or (mode == 0 and x >= self.x) or (mode == 1 and x <= self.x):
+ self.cells.pop((x,self.y),None)
+ continue
+ if self.pending.startswith(b"\x1b]"):
+ endings = [index for index in (self.pending.find(b"\x07"),self.pending.find(b"\x1b\\"))
+ if index >= 0]
+ if not endings:
+ return
+ end = min(endings)
+ self.pending = self.pending[end+(1 if self.pending[end:end+1] == b"\x07" else 2):]
+ continue
+ if self.pending.startswith(b"\x1b"):
+ if len(self.pending)<2:
+ return
+ self.pending = self.pending[2:]
+ continue
+ end = self.pending.find(b"\x1b")
+ end = end if end >= 0 else len(self.pending)
+ plain = self.decoder.decode(self.pending[:end])
+ self.pending = self.pending[end:]
+ for char in plain:
+ if char == "\r": self.x = 0
+ elif char == "\n": self.y = min(self.rows-1,self.y+1)
+ elif char == "\b": self.x = max(0,self.x-1)
+ elif ord(char) >= 32 and not unicodedata.combining(char):
+ if self.x >= self.columns:
+ self.x = 0
+ self.y = min(self.rows-1,self.y+1)
+ self.cells[self.x,self.y] = char
+ self.x += 2 if unicodedata.east_asian_width(char) in ("W","F") else 1
+
+
+def percentile(values, fraction):
+ ordered = sorted(values)
+ return round(ordered[min(int(len(ordered) * fraction), len(ordered) - 1)], 3)
+
+
+def process_stats(pid):
+ values = subprocess.check_output(
+ ["ps", "-p", str(pid), "-o", "time=,rss="], text=True
+ ).split()
+ clock, rss = values[-2:]
+ seconds = sum(float(part) * (60 ** index) for index, part in enumerate(reversed(clock.split(":"))))
+ return seconds, int(rss)
+
+
+def profile(binary, columns, rows, samples, idle_seconds, mode, clear_gap, input_mode):
+ import pty
+
+ master, slave = pty.openpty()
+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", rows, columns, 0, 0))
+
+ def child_terminal():
+ os.setsid()
+ fcntl.ioctl(slave, termios.TIOCSCTTY, 0)
+
+ scratch_root = Path(__file__).resolve().parents[2] / "target/debug-logs/tui-profile"
+ scratch_root.mkdir(parents=True, exist_ok=True)
+ scratch = tempfile.TemporaryDirectory(prefix="isolated-", dir=scratch_root)
+ # An allowlist avoids inheriting API keys, session tokens, debug delays, or
+ # telemetry configuration. CWD and workspace are fresh and contain no .env.
+ environment = {key: os.environ[key] for key in ("PATH", "LANG", "LC_ALL", "TMPDIR")
+ if key in os.environ}
+ dotenv = Path(scratch.name) / "empty.env"
+ dotenv.touch()
+ workspace = Path(scratch.name) / "workspace"
+ workspace.mkdir()
+ action_dir = Path(scratch.name) / "actions"
+ action_dir.mkdir()
+ environment.update({"TERM": "xterm-256color", "OPENHUMAN_WORKSPACE":str(workspace),
+ "OPENHUMAN_ACTION_DIR":str(action_dir),
+ "OPENHUMAN_DOTENV_PATH":str(dotenv)})
+ if mode == "live":
+ # Demo suppresses telemetry even when checking an older binary that
+ # has not yet gained --no-telemetry. --help returns before demo starts.
+ help_output = subprocess.run([str(binary), "--demo", "--help"], env=environment,
+ cwd=scratch.name, capture_output=True, timeout=10, check=True)
+ if b"--no-telemetry" not in help_output.stdout:
+ os.close(master)
+ os.close(slave)
+ scratch.cleanup()
+ raise RuntimeError("--mode live requires a binary advertising --no-telemetry; rebuild first")
+ started = time.perf_counter()
+ process = subprocess.Popen(
+ [str(binary), "--demo"] if mode == "demo" else [str(binary), "--no-telemetry", "--new"],
+ stdin=slave, stdout=slave, stderr=slave,
+ preexec_fn=child_terminal, close_fds=True,
+ env=environment, cwd=scratch.name,
+ )
+ os.close(slave)
+ os.set_blocking(master, False)
+ selector = selectors.DefaultSelector()
+ selector.register(master, selectors.EVENT_READ)
+ query_tail = b""
+ cursor_queries = 0
+ screen = Screen(columns, rows)
+
+ def collect(duration, marker=None):
+ nonlocal query_tail, cursor_queries
+ data = bytearray()
+ deadline = time.perf_counter() + duration
+ while time.perf_counter() < deadline:
+ for _key, _events in selector.select(max(0, deadline - time.perf_counter())):
+ try:
+ chunk = os.read(master, 65536)
+ except OSError as error:
+ if error.errno == errno.EIO:
+ return bytes(data)
+ raise
+ if not chunk:
+ return bytes(data)
+ data.extend(chunk)
+ screen.feed(chunk)
+ # A PTY is a byte pipe, not a terminal emulator. ratatui asks
+ # for the cursor position while constructing its Terminal;
+ # crossterm waits for a DSR reply before it can paint a frame.
+ pending = query_tail + chunk
+ cursor_queries += pending.count(b"\x1b[6n")
+ for _ in range(pending.count(b"\x1b[6n")):
+ os.write(master, b"\x1b[1;1R")
+ query_tail = pending[-3:]
+ if marker is not None and screen.contains(marker):
+ return bytes(data)
+ if marker is not None:
+ raise RuntimeError("TUI did not acknowledge synthetic input before deadline; "
+ f"child exit={process.poll()}, synthetic output tail={bytes(data[-512:])!r}")
+ return bytes(data)
+
+ try:
+ collect(30, b"Offline preview" if mode == "demo" else b"Signed out")
+ startup_ms = (time.perf_counter() - started) * 1000
+ collect(0.2) # Drain initial paint before measuring idle output.
+ before_cpu, before_rss = process_stats(process.pid)
+ idle_output = collect(idle_seconds)
+ after_cpu, after_rss = process_stats(process.pid)
+ latency = []
+ output_bytes = 0
+ for sample in range(samples):
+ os.write(master, b"\x03")
+ collect(clear_gap)
+ # Different full text each time makes a ratatui diff observable
+ # even if clearing and pasting coalesce into a single frame.
+ suffix = str(sample).encode("ascii")
+ marker = bytes([65 + sample % 26]) * min(20, columns - 5 - len(suffix)) + suffix
+ began = time.perf_counter_ns()
+ os.write(master, b"\x1b[200~" + marker + b"\x1b[201~"
+ if input_mode == "paste" else marker)
+ response = collect(2, marker)
+ latency.append((time.perf_counter_ns() - began) / 1_000_000)
+ output_bytes += len(response)
+ os.write(master, b"\x04")
+ collect(0.5) # Drain teardown escapes so the PTY cannot block a final write.
+ process.wait(timeout=3)
+ return {
+ "schema": 1, "mode": ("offline demo in POSIX PTY; no core or model calls"
+ if mode == "demo" else "live event loop in POSIX PTY; fresh workspace; no login or model calls"),
+ "terminal": {"columns": columns, "rows": rows},
+ "startup_first_frame_ms": round(startup_ms, 3),
+ "idle": {"seconds": idle_seconds, "terminal_output_bytes": len(idle_output),
+ "cpu_ms": round((after_cpu - before_cpu) * 1000, 3),
+ "cpu_counter_resolution_ms": 10 if platform.system() == "Darwin" else 1000,
+ "rss_kib": max(before_rss, after_rss)},
+ "input_to_paint": {"samples": samples, "p50_ms": percentile(latency, 0.5),
+ "p95_ms": percentile(latency, 0.95),
+ "input_mode":input_mode,
+ "clear_to_input_gap_ms":clear_gap * 1000,
+ "max_ms": round(max(latency), 3), "output_bytes": output_bytes},
+ "exit_code": process.returncode,
+ "terminal_emulation": {"cursor_position_replies":cursor_queries,
+ "marker_detection":"screen cells after cursor and erase processing"},
+ }
+ finally:
+ selector.close()
+ os.close(master)
+ try:
+ if process.poll() is None:
+ # Closing this isolated controlling PTY delivers SIGHUP first.
+ # Signals below always target this exact child, never a group
+ # containing another developer's shell or terminal session.
+ try:
+ process.wait(timeout=0.5)
+ except subprocess.TimeoutExpired:
+ process.terminate()
+ try:
+ process.wait(timeout=2)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ finally:
+ scratch.cleanup()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--binary", type=Path, default=Path("target/debug/openhuman-tui"))
+ parser.add_argument("--columns", type=int, default=80)
+ parser.add_argument("--rows", type=int, default=24)
+ parser.add_argument("--samples", type=int, default=40)
+ parser.add_argument("--idle-seconds", type=float, default=2)
+ parser.add_argument("--mode", choices=("demo","live"), default="demo")
+ parser.add_argument("--clear-gap-ms", type=float, default=10)
+ parser.add_argument("--input-mode", choices=("paste","keys"), default="paste")
+ parser.add_argument("--output", type=Path)
+ args = parser.parse_args()
+ if args.samples < 1 or args.idle_seconds <= 0 or args.columns < 24 or args.rows < 8 or args.clear_gap_ms < 0:
+ parser.error("Use at least one sample, positive idle time, and a terminal >=24x8")
+ binary = args.binary.resolve(strict=True)
+ binary_before = binary.stat()
+ with binary.open("rb") as binary_file:
+ binary_sha256 = hashlib.file_digest(binary_file, "sha256").hexdigest()
+ result = profile(binary, args.columns, args.rows, args.samples, args.idle_seconds,
+ args.mode, args.clear_gap_ms / 1000, args.input_mode)
+ result["environment"] = {"platform": platform.platform(), "machine": platform.machine(),
+ "python": platform.python_version()}
+ result["binary_sha256"] = binary_sha256
+ binary_after = binary.stat()
+ result["binary_changed_during_run"] = (binary_before.st_ino,binary_before.st_mtime_ns,binary_before.st_size) \
+ != (binary_after.st_ino,binary_after.st_mtime_ns,binary_after.st_size)
+ text = json.dumps(result, indent=2) + "\n"
+ if args.output:
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(text)
+ print(text, end="")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/debug/tui-profile_tests.py b/scripts/debug/tui-profile_tests.py
new file mode 100644
index 0000000000..c3df48c5dc
--- /dev/null
+++ b/scripts/debug/tui-profile_tests.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python3
+"""Deterministic parser checks; run with python3 scripts/debug/tui-profile_tests.py."""
+import importlib.util
+import unittest
+from pathlib import Path
+
+SPEC = importlib.util.spec_from_file_location("tui_profile", Path(__file__).with_name("tui-profile.py"))
+MODULE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(MODULE)
+
+
+class ScreenTests(unittest.TestCase):
+ def test_differential_frames_reconstruct_marker_and_erase_placeholder(self):
+ screen = MODULE.Screen(80,24)
+ screen.feed(b"\x1b[21;2HDescribe a task")
+ screen.feed(b"\x1b[21;2HAAA\x1b[0K")
+ screen.feed(b"\x1b[21;5HBBB")
+ self.assertTrue(screen.contains(b"AAABBB"))
+ self.assertFalse(screen.contains(b"Describe a task"))
+
+ def test_split_cursor_sequence_styles_and_osc_do_not_add_visible_text(self):
+ screen = MODULE.Screen(80,24)
+ screen.feed(b"\x1b]title;hidden")
+ screen.feed(b"\x1b\\\x1b[21;")
+ screen.feed(b"2H\x1b[38;2;10;20;30mvisible\x1b[0m")
+ self.assertTrue(screen.contains(b"visible"))
+ self.assertFalse(screen.contains(b"hidden"))
+ self.assertEqual(screen.cells[(1,20)],"v")
+
+ def test_split_utf8_wide_and_combining_characters_preserve_cell_positions(self):
+ screen = MODULE.Screen(80,24)
+ raw = "界e\u0301X".encode("utf-8")
+ for byte in raw:
+ screen.feed(bytes([byte]))
+ self.assertEqual(screen.cells[(0,0)],"界")
+ self.assertEqual(screen.cells[(2,0)],"e")
+ self.assertEqual(screen.cells[(3,0)],"X")
+
+ def test_cursor_motion_and_screen_clear_remove_old_marker(self):
+ screen = MODULE.Screen(80,24)
+ screen.feed(b"\x1b[4;3Hfirst\x1b[5G\x1b[1DXY")
+ self.assertEqual(screen.cells[(3,3)],"X")
+ self.assertEqual(screen.cells[(4,3)],"Y")
+ screen.feed(b"\x1b[2J\x1b[1;1Hnext")
+ self.assertFalse(screen.contains(b"first"))
+ self.assertTrue(screen.contains(b"next"))
+
+
+if __name__ == "__main__":
+ unittest.main()