The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: add test modules for all TUI components
Steven Enamakel0a6856dffb1c
diff --git a/crates/openhuman-tui/src/app.rs b/crates/openhuman-tui/src/app.rsindex 8ffe2b6846..0fb0b20030 100644--- a/crates/openhuman-tui/src/app.rs+++ b/crates/openhuman-tui/src/app.rs@@ -1367,148 +1367,5 @@ fn copy_latest_answer(state: &mut TranscriptState) {}#[cfg(test)]-mod tests {- use super::*;-- fn key(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {- KeyEvent::new(code, modifiers)- }-- #[test]- fn plain_digits_remain_chat_input_and_alt_digits_switch_tabs() {- for digit in ['1', '2', '3', '4'] {- assert_eq!(- tab_shortcut(key(KeyCode::Char(digit), KeyModifiers::NONE), AppTab::Chat),- None- );- }- assert_eq!(- tab_shortcut(key(KeyCode::Char('3'), KeyModifiers::ALT), AppTab::Chat),- Some(AppTab::Config)- );- }-- #[test]- fn paste_routes_only_to_the_active_editable_surface() {- let mut ui = UiState::new("thread".into(), "client".into());- ui.active_tab = AppTab::Chat;- handle_paste("model-4", &mut ui);- assert_eq!(ui.composer.text(), "model-4");-- ui.active_tab = AppTab::Settings;- ui.login_token = Some(String::new());- handle_paste("one-time-token", &mut ui);- assert_eq!(ui.login_token.as_deref(), Some("one-time-token"));- }-- #[test]- fn workspace_file_picker_is_bounded_filtered_and_skips_heavy_trees() {- let root = tempfile::tempdir().unwrap();- std::fs::create_dir_all(root.path().join("src")).unwrap();- std::fs::create_dir_all(root.path().join("target")).unwrap();- std::fs::write(root.path().join("src/main.rs"), "fn main() {}").unwrap();- std::fs::write(root.path().join("target/hidden.rs"), "").unwrap();- let files = collect_files(root.path().to_str().unwrap(), "main", 10).unwrap();- assert_eq!(files, vec!["src/main.rs"]);- }-- #[test]- fn workspace_file_picker_stops_at_the_depth_limit() {- let root = tempfile::tempdir().unwrap();- let mut deep = root.path().to_path_buf();- for level in 0..10 {- deep.push(format!("level-{level}"));- }- std::fs::create_dir_all(&deep).unwrap();- std::fs::write(deep.join("too-deep.txt"), "hidden").unwrap();- let files = collect_files(root.path().to_str().unwrap(), "too-deep", 10).unwrap();- assert!(files.is_empty());- }-- #[test]- fn decision_shortcuts_do_not_treat_filter_text_as_deny() {- assert_eq!(- decision_shortcut(OverlayKind::Approvals, false, KeyCode::Char('d')),- None- );- assert_eq!(- decision_shortcut(OverlayKind::Approvals, false, KeyCode::Delete),- Some("deny")- );- assert_eq!(- decision_shortcut(OverlayKind::PlanReview, true, KeyCode::Char('a')),- None- );- }-- #[test]- fn inbound_approval_preserves_typed_overlay_input() {- let mut state = TranscriptState::new("client");- state.set_thread("thread");- let mut ui = UiState::new("thread".into(), "client".into());- let mut overlay = Overlay::new(OverlayKind::Rename, "Rename");- overlay.input = Some("draft title".into());- ui.overlay = Some(overlay);- handle_web_event(- &WebChannelEvent {- event: "approval_request".into(),- client_id: "client".into(),- thread_id: "thread".into(),- request_id: "approval-1".into(),- tool_name: Some("shell".into()),- ..Default::default()- },- &mut state,- &mut ui,- );- assert_eq!(- ui.overlay- .as_ref()- .and_then(|overlay| overlay.input.as_deref()),- Some("draft title")- );- assert_eq!(ui.pending_approvals.len(), 1);- }-- #[test]- fn inbound_plan_review_waits_for_typed_overlay_to_close() {- let mut state = TranscriptState::new("client");- state.set_thread("thread");- let mut ui = UiState::new("thread".into(), "client".into());- let mut overlay = Overlay::new(OverlayKind::Rename, "Rename");- overlay.input = Some("draft title".into());- ui.overlay = Some(overlay);- handle_web_event(- &WebChannelEvent {- event: "plan_review_request".into(),- client_id: "client".into(),- thread_id: "thread".into(),- request_id: "review-1".into(),- message: Some("Review this plan".into()),- args: Some(json!({"steps": ["Inspect", "Implement"]})),- ..Default::default()- },- &mut state,- &mut ui,- );- assert_eq!(- ui.overlay- .as_ref()- .and_then(|overlay| overlay.input.as_deref()),- Some("draft title")- );-- ui.overlay = None;- present_pending_plan_review(&mut ui);- assert_eq!(- ui.overlay.as_ref().map(|overlay| overlay.kind),- Some(OverlayKind::PlanReview)- );- assert_eq!(- ui.pending_plan_review- .as_ref()- .map(|review| review.request_id.as_str()),- Some("review-1")- );- }-}+#[path = "app_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/app_tests.rs b/crates/openhuman-tui/src/app_tests.rsnew file mode 100644index 0000000000..3131ec3b31--- /dev/null+++ b/crates/openhuman-tui/src/app_tests.rs@@ -0,0 +1,143 @@+use super::*;++fn key(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {+ KeyEvent::new(code, modifiers)+}++#[test]+fn plain_digits_remain_chat_input_and_alt_digits_switch_tabs() {+ for digit in ['1', '2', '3', '4'] {+ assert_eq!(+ tab_shortcut(key(KeyCode::Char(digit), KeyModifiers::NONE), AppTab::Chat),+ None+ );+ }+ assert_eq!(+ tab_shortcut(key(KeyCode::Char('3'), KeyModifiers::ALT), AppTab::Chat),+ Some(AppTab::Config)+ );+}++#[test]+fn paste_routes_only_to_the_active_editable_surface() {+ let mut ui = UiState::new("thread".into(), "client".into());+ ui.active_tab = AppTab::Chat;+ handle_paste("model-4", &mut ui);+ assert_eq!(ui.composer.text(), "model-4");++ ui.active_tab = AppTab::Settings;+ ui.login_token = Some(String::new());+ handle_paste("one-time-token", &mut ui);+ assert_eq!(ui.login_token.as_deref(), Some("one-time-token"));+}++#[test]+fn workspace_file_picker_is_bounded_filtered_and_skips_heavy_trees() {+ let root = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(root.path().join("src")).unwrap();+ std::fs::create_dir_all(root.path().join("target")).unwrap();+ std::fs::write(root.path().join("src/main.rs"), "fn main() {}").unwrap();+ std::fs::write(root.path().join("target/hidden.rs"), "").unwrap();+ let files = collect_files(root.path().to_str().unwrap(), "main", 10).unwrap();+ assert_eq!(files, vec!["src/main.rs"]);+}++#[test]+fn workspace_file_picker_stops_at_the_depth_limit() {+ let root = tempfile::tempdir().unwrap();+ let mut deep = root.path().to_path_buf();+ for level in 0..10 {+ deep.push(format!("level-{level}"));+ }+ std::fs::create_dir_all(&deep).unwrap();+ std::fs::write(deep.join("too-deep.txt"), "hidden").unwrap();+ let files = collect_files(root.path().to_str().unwrap(), "too-deep", 10).unwrap();+ assert!(files.is_empty());+}++#[test]+fn decision_shortcuts_do_not_treat_filter_text_as_deny() {+ assert_eq!(+ decision_shortcut(OverlayKind::Approvals, false, KeyCode::Char('d')),+ None+ );+ assert_eq!(+ decision_shortcut(OverlayKind::Approvals, false, KeyCode::Delete),+ Some("deny")+ );+ assert_eq!(+ decision_shortcut(OverlayKind::PlanReview, true, KeyCode::Char('a')),+ None+ );+}++#[test]+fn inbound_approval_preserves_typed_overlay_input() {+ let mut state = TranscriptState::new("client");+ state.set_thread("thread");+ let mut ui = UiState::new("thread".into(), "client".into());+ let mut overlay = Overlay::new(OverlayKind::Rename, "Rename");+ overlay.input = Some("draft title".into());+ ui.overlay = Some(overlay);+ handle_web_event(+ &WebChannelEvent {+ event: "approval_request".into(),+ client_id: "client".into(),+ thread_id: "thread".into(),+ request_id: "approval-1".into(),+ tool_name: Some("shell".into()),+ ..Default::default()+ },+ &mut state,+ &mut ui,+ );+ assert_eq!(+ ui.overlay+ .as_ref()+ .and_then(|overlay| overlay.input.as_deref()),+ Some("draft title")+ );+ assert_eq!(ui.pending_approvals.len(), 1);+}++#[test]+fn inbound_plan_review_waits_for_typed_overlay_to_close() {+ let mut state = TranscriptState::new("client");+ state.set_thread("thread");+ let mut ui = UiState::new("thread".into(), "client".into());+ let mut overlay = Overlay::new(OverlayKind::Rename, "Rename");+ overlay.input = Some("draft title".into());+ ui.overlay = Some(overlay);+ handle_web_event(+ &WebChannelEvent {+ event: "plan_review_request".into(),+ client_id: "client".into(),+ thread_id: "thread".into(),+ request_id: "review-1".into(),+ message: Some("Review this plan".into()),+ args: Some(json!({"steps": ["Inspect", "Implement"]})),+ ..Default::default()+ },+ &mut state,+ &mut ui,+ );+ assert_eq!(+ ui.overlay+ .as_ref()+ .and_then(|overlay| overlay.input.as_deref()),+ Some("draft title")+ );++ ui.overlay = None;+ present_pending_plan_review(&mut ui);+ assert_eq!(+ ui.overlay.as_ref().map(|overlay| overlay.kind),+ Some(OverlayKind::PlanReview)+ );+ assert_eq!(+ ui.pending_plan_review+ .as_ref()+ .map(|review| review.request_id.as_str()),+ Some("review-1")+ );+}diff --git a/crates/openhuman-tui/src/cockpit.rs b/crates/openhuman-tui/src/cockpit.rsindex 4367ae4165..87fd4d94e5 100644--- a/crates/openhuman-tui/src/cockpit.rs+++ b/crates/openhuman-tui/src/cockpit.rs@@ -125,27 +125,5 @@ pub fn row_from_value(value: &Value, id_keys: &[&str], label_keys: &[&str]) -> O}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn overlay_filter_matches_label_and_detail() {- let mut overlay = Overlay::new(OverlayKind::Threads, "Threads");- overlay.rows.push(OverlayRow {- id: "1".into(),- label: "Release prep".into(),- detail: "yesterday".into(),- payload: Value::Null,- });- overlay.filter = "yester".into();- assert_eq!(overlay.visible_rows().len(), 1);- overlay.filter = "missing".into();- assert!(overlay.visible_rows().is_empty());- }-- #[test]- fn unwrap_rpc_handles_nested_envelopes() {- let value = serde_json::json!({"result":{"data":{"threads":[]}}});- assert!(unwrap_rpc(&value).get("threads").is_some());- }-}+#[path = "cockpit_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/cockpit_tests.rs b/crates/openhuman-tui/src/cockpit_tests.rsnew file mode 100644index 0000000000..e11ff49326--- /dev/null+++ b/crates/openhuman-tui/src/cockpit_tests.rs@@ -0,0 +1,22 @@+use super::*;++#[test]+fn overlay_filter_matches_label_and_detail() {+ let mut overlay = Overlay::new(OverlayKind::Threads, "Threads");+ overlay.rows.push(OverlayRow {+ id: "1".into(),+ label: "Release prep".into(),+ detail: "yesterday".into(),+ payload: Value::Null,+ });+ overlay.filter = "yester".into();+ assert_eq!(overlay.visible_rows().len(), 1);+ overlay.filter = "missing".into();+ assert!(overlay.visible_rows().is_empty());+}++#[test]+fn unwrap_rpc_handles_nested_envelopes() {+ let value = serde_json::json!({"result":{"data":{"threads":[]}}});+ assert!(unwrap_rpc(&value).get("threads").is_some());+}diff --git a/crates/openhuman-tui/src/composer.rs b/crates/openhuman-tui/src/composer.rsindex 3255e7c9d8..33099a7dc9 100644--- a/crates/openhuman-tui/src/composer.rs+++ b/crates/openhuman-tui/src/composer.rs@@ -300,61 +300,5 @@ fn fuzzy_match(candidate: &str, query: &str) -> bool {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn unicode_editing_uses_character_indices() {- let mut c = Composer::default();- c.insert_str("a🦀b");- c.move_left();- c.backspace();- assert_eq!(c.text(), "ab");- assert_eq!(c.cursor(), 1);- }-- #[test]- fn multiline_home_end_and_wrapping() {- let mut c = Composer::default();- c.set_text("one\ntwo long");- c.move_home();- assert_eq!(c.cursor(), 4);- c.move_end();- assert_eq!(c.cursor(), 12);- let (rows, row, col) = c.display(5);- assert_eq!(rows, vec!["one", "two l", "ong"]);- assert_eq!((row, col), (2, 3));- }-- #[test]- fn history_preserves_draft_and_deduplicates() {- let mut c = Composer::default();- c.set_text("first");- assert_eq!(c.take_for_send().as_deref(), Some("first"));- c.set_text("first");- c.take_for_send();- c.set_text("draft");- c.history_previous();- assert_eq!(c.text(), "first");- c.history_next();- assert_eq!(c.text(), "draft");- }-- #[test]- fn slash_commands_filter_fuzzily() {- let mut c = Composer::default();- c.set_text("/perm");- assert_eq!(c.command_matches()[0].0, "permissions");- c.set_text("/rsm");- assert_eq!(c.command_matches()[0].0, "resume");- }-- #[test]- fn file_mentions_replace_only_the_current_token() {- let mut composer = Composer::default();- composer.set_text("review @src/ma");- assert_eq!(composer.file_query().as_deref(), Some("src/ma"));- composer.replace_current_token("@src/main.rs");- assert_eq!(composer.text(), "review @src/main.rs");- }-}+#[path = "composer_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/composer_tests.rs b/crates/openhuman-tui/src/composer_tests.rsnew file mode 100644index 0000000000..f72efad973--- /dev/null+++ b/crates/openhuman-tui/src/composer_tests.rs@@ -0,0 +1,56 @@+use super::*;++#[test]+fn unicode_editing_uses_character_indices() {+ let mut c = Composer::default();+ c.insert_str("a🦀b");+ c.move_left();+ c.backspace();+ assert_eq!(c.text(), "ab");+ assert_eq!(c.cursor(), 1);+}++#[test]+fn multiline_home_end_and_wrapping() {+ let mut c = Composer::default();+ c.set_text("one\ntwo long");+ c.move_home();+ assert_eq!(c.cursor(), 4);+ c.move_end();+ assert_eq!(c.cursor(), 12);+ let (rows, row, col) = c.display(5);+ assert_eq!(rows, vec!["one", "two l", "ong"]);+ assert_eq!((row, col), (2, 3));+}++#[test]+fn history_preserves_draft_and_deduplicates() {+ let mut c = Composer::default();+ c.set_text("first");+ assert_eq!(c.take_for_send().as_deref(), Some("first"));+ c.set_text("first");+ c.take_for_send();+ c.set_text("draft");+ c.history_previous();+ assert_eq!(c.text(), "first");+ c.history_next();+ assert_eq!(c.text(), "draft");+}++#[test]+fn slash_commands_filter_fuzzily() {+ let mut c = Composer::default();+ c.set_text("/perm");+ assert_eq!(c.command_matches()[0].0, "permissions");+ c.set_text("/rsm");+ assert_eq!(c.command_matches()[0].0, "resume");+}++#[test]+fn file_mentions_replace_only_the_current_token() {+ let mut composer = Composer::default();+ composer.set_text("review @src/ma");+ assert_eq!(composer.file_query().as_deref(), Some("src/ma"));+ composer.replace_current_token("@src/main.rs");+ assert_eq!(composer.text(), "review @src/main.rs");+}diff --git a/crates/openhuman-tui/src/controls.rs b/crates/openhuman-tui/src/controls.rsindex 238d79aff3..c13a657814 100644--- a/crates/openhuman-tui/src/controls.rs+++ b/crates/openhuman-tui/src/controls.rs@@ -268,67 +268,5 @@ fn account_detail(user: &serde_json::Value) -> String {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn rpc_payload_unwraps_runtime_and_api_envelopes() {- let value = json!({"result": {"data": {"mode": "standard"}}, "logs": []});- assert_eq!(rpc_payload(&value), &json!({"mode": "standard"}));- assert_eq!(string_at(rpc_payload(&value), &["mode"]), "standard");- }-- #[test]- fn string_at_never_coerces_non_string_or_missing_values() {- let value = json!({"enabled": true});- assert_eq!(string_at(&value, &["enabled"]), "");- assert_eq!(string_at(&value, &["missing"]), "");- }-- #[test]- fn account_detail_uses_canonical_backend_user_fields() {- let user = json!({- "firstName": "Ada",- "lastName": "Lovelace",- "email": "[email protected]",- "username": "ada"- });- assert_eq!(account_detail(&user), "Ada Lovelace · [email protected]");- }-- #[test]- fn curated_config_fields_map_to_safe_specific_updates() {- let cases = [- (- ConfigKey::ApiUrl,- "openhuman.config_update_model_settings",- json!({"api_url": "value"}),- ),- (- ConfigKey::InferenceUrl,- "openhuman.config_update_model_settings",- json!({"inference_url": "value"}),- ),- (- ConfigKey::DefaultModel,- "openhuman.config_update_model_settings",- json!({"default_model": "value"}),- ),- (- ConfigKey::AutonomyLevel,- "openhuman.config_update_autonomy_settings",- json!({"level": "value"}),- ),- (- ConfigKey::PrivacyMode,- "openhuman.config_set_privacy_mode",- json!({"mode": "value"}),- ),- ];- for (key, expected_method, expected_params) in cases {- let (method, params) = config_update(key, "value".to_string());- assert_eq!(method, expected_method);- assert_eq!(params, expected_params);- }- }-}+#[path = "controls_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/controls_tests.rs b/crates/openhuman-tui/src/controls_tests.rsnew file mode 100644index 0000000000..d0fbd4287f--- /dev/null+++ b/crates/openhuman-tui/src/controls_tests.rs@@ -0,0 +1,62 @@+use super::*;++#[test]+fn rpc_payload_unwraps_runtime_and_api_envelopes() {+ let value = json!({"result": {"data": {"mode": "standard"}}, "logs": []});+ assert_eq!(rpc_payload(&value), &json!({"mode": "standard"}));+ assert_eq!(string_at(rpc_payload(&value), &["mode"]), "standard");+}++#[test]+fn string_at_never_coerces_non_string_or_missing_values() {+ let value = json!({"enabled": true});+ assert_eq!(string_at(&value, &["enabled"]), "");+ assert_eq!(string_at(&value, &["missing"]), "");+}++#[test]+fn account_detail_uses_canonical_backend_user_fields() {+ let user = json!({+ "firstName": "Ada",+ "lastName": "Lovelace",+ "email": "[email protected]",+ "username": "ada"+ });+ assert_eq!(account_detail(&user), "Ada Lovelace · [email protected]");+}++#[test]+fn curated_config_fields_map_to_safe_specific_updates() {+ let cases = [+ (+ ConfigKey::ApiUrl,+ "openhuman.config_update_model_settings",+ json!({"api_url": "value"}),+ ),+ (+ ConfigKey::InferenceUrl,+ "openhuman.config_update_model_settings",+ json!({"inference_url": "value"}),+ ),+ (+ ConfigKey::DefaultModel,+ "openhuman.config_update_model_settings",+ json!({"default_model": "value"}),+ ),+ (+ ConfigKey::AutonomyLevel,+ "openhuman.config_update_autonomy_settings",+ json!({"level": "value"}),+ ),+ (+ ConfigKey::PrivacyMode,+ "openhuman.config_set_privacy_mode",+ json!({"mode": "value"}),+ ),+ ];+ for (key, expected_method, expected_params) in cases {+ let (method, params) = config_update(key, "value".to_string());+ assert_eq!(method, expected_method);+ assert_eq!(params, expected_params);+ }+}diff --git a/crates/openhuman-tui/src/crash_reporting.rs b/crates/openhuman-tui/src/crash_reporting.rsindex 62eaf5d142..96b3ff5dc9 100644--- a/crates/openhuman-tui/src/crash_reporting.rs+++ b/crates/openhuman-tui/src/crash_reporting.rs@@ -85,20 +85,5 @@ fn resolve_environment() -> String {}#[cfg(all(test, feature = "crash-reporting"))]-mod tests {- use super::*;-- #[test]- fn release_tag_uses_the_package_version_without_a_build_sha() {- if option_env!("OPENHUMAN_BUILD_SHA")- .unwrap_or("")- .trim()- .is_empty()- {- assert_eq!(- build_release_tag(),- format!("openhuman@{}", env!("CARGO_PKG_VERSION"))- );- }- }-}+#[path = "crash_reporting_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/crash_reporting_tests.rs b/crates/openhuman-tui/src/crash_reporting_tests.rsnew file mode 100644index 0000000000..9914d6c528--- /dev/null+++ b/crates/openhuman-tui/src/crash_reporting_tests.rs@@ -0,0 +1,15 @@+use super::*;++#[test]+fn release_tag_uses_the_package_version_without_a_build_sha() {+ if option_env!("OPENHUMAN_BUILD_SHA")+ .unwrap_or("")+ .trim()+ .is_empty()+ {+ assert_eq!(+ build_release_tag(),+ format!("openhuman@{}", env!("CARGO_PKG_VERSION"))+ );+ }+}diff --git a/crates/openhuman-tui/src/render.rs b/crates/openhuman-tui/src/render.rsindex 7b8bc640f8..7e789f1833 100644--- a/crates/openhuman-tui/src/render.rs+++ b/crates/openhuman-tui/src/render.rs@@ -506,73 +506,5 @@ fn byte_at_display_column(value: &str, target: usize) -> usize {}#[cfg(test)]-mod tests {- use super::*;- use ratatui::backend::TestBackend;- use ratatui::Terminal;-- fn rendered(ui: &UiState) -> String {- let backend = TestBackend::new(180, 24);- let mut terminal = Terminal::new(backend).expect("test terminal");- let transcript = TranscriptState::new("test-client");- terminal- .draw(|frame| draw(frame, &transcript, ui))- .expect("draw");- terminal- .backend()- .buffer()- .content()- .iter()- .map(|cell| cell.symbol())- .collect::<String>()- }-- #[test]- fn tab_bar_and_navigation_footer_are_always_rendered() {- let ui = UiState::new("thread-1".into(), "client-1".into());- let output = rendered(&ui);- for title in ["1 Logs", "2 Chat", "3 Config", "4 Settings"] {- assert!(output.contains(title), "missing tab {title}");- }- assert!(output.contains("Ctrl+Tab switch"));- assert!(output.contains("Shift+Enter newline"));- }-- #[test]- fn editing_footer_explains_that_tab_switching_is_paused() {- let mut ui = UiState::new("thread-1".into(), "client-1".into());- ui.active_tab = AppTab::Config;- ui.config_edit = Some("value".to_string());- let output = rendered(&ui);- assert!(output.contains("Finish or Esc before switching tabs"));- assert!(!output.contains("Alt+1-4 tabs"));- }-- #[test]- fn tail_to_width_keeps_the_end() {- assert_eq!(tail_to_width("hello world", 5), "world");- assert_eq!(tail_to_width("hi", 10), "hi");- assert_eq!(tail_to_width("anything", 0), "");- }-- #[test]- fn wrapped_line_count_divides_by_width() {- let line = Line::from("a".repeat(25));- assert_eq!(wrapped_line_count(&line, 10), 3);- let empty = Line::from("");- assert_eq!(wrapped_line_count(&empty, 10), 1);- }-- #[test]- fn cursor_byte_lookup_handles_wide_unicode() {- assert_eq!(byte_at_display_column("界a", 2), "界".len());- assert_eq!(byte_at_display_column("界a", 3), "界a".len());- }-- #[test]- fn short_id_truncates_non_ascii_at_a_character_boundary() {- let id = "12345678901界xyz";- assert_eq!(short_id(id), "12345678901界");- assert_eq!(short_id("abcdefghijklmnop"), "abcdefghijkl");- }-}+#[path = "render_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/render_tests.rs b/crates/openhuman-tui/src/render_tests.rsnew file mode 100644index 0000000000..f8737ecabc--- /dev/null+++ b/crates/openhuman-tui/src/render_tests.rs@@ -0,0 +1,68 @@+use super::*;+use ratatui::backend::TestBackend;+use ratatui::Terminal;++fn rendered(ui: &UiState) -> String {+ let backend = TestBackend::new(180, 24);+ let mut terminal = Terminal::new(backend).expect("test terminal");+ let transcript = TranscriptState::new("test-client");+ terminal+ .draw(|frame| draw(frame, &transcript, ui))+ .expect("draw");+ terminal+ .backend()+ .buffer()+ .content()+ .iter()+ .map(|cell| cell.symbol())+ .collect::<String>()+}++#[test]+fn tab_bar_and_navigation_footer_are_always_rendered() {+ let ui = UiState::new("thread-1".into(), "client-1".into());+ let output = rendered(&ui);+ for title in ["1 Logs", "2 Chat", "3 Config", "4 Settings"] {+ assert!(output.contains(title), "missing tab {title}");+ }+ assert!(output.contains("Ctrl+Tab switch"));+ assert!(output.contains("Shift+Enter newline"));+}++#[test]+fn editing_footer_explains_that_tab_switching_is_paused() {+ let mut ui = UiState::new("thread-1".into(), "client-1".into());+ ui.active_tab = AppTab::Config;+ ui.config_edit = Some("value".to_string());+ let output = rendered(&ui);+ assert!(output.contains("Finish or Esc before switching tabs"));+ assert!(!output.contains("Alt+1-4 tabs"));+}++#[test]+fn tail_to_width_keeps_the_end() {+ assert_eq!(tail_to_width("hello world", 5), "world");+ assert_eq!(tail_to_width("hi", 10), "hi");+ assert_eq!(tail_to_width("anything", 0), "");+}++#[test]+fn wrapped_line_count_divides_by_width() {+ let line = Line::from("a".repeat(25));+ assert_eq!(wrapped_line_count(&line, 10), 3);+ let empty = Line::from("");+ assert_eq!(wrapped_line_count(&empty, 10), 1);+}++#[test]+fn cursor_byte_lookup_handles_wide_unicode() {+ assert_eq!(byte_at_display_column("界a", 2), "界".len());+ assert_eq!(byte_at_display_column("界a", 3), "界a".len());+}++#[test]+fn short_id_truncates_non_ascii_at_a_character_boundary() {+ let id = "12345678901界xyz";+ assert_eq!(short_id(id), "12345678901界");+ assert_eq!(short_id("abcdefghijklmnop"), "abcdefghijkl");+}diff --git a/crates/openhuman-tui/src/runner.rs b/crates/openhuman-tui/src/runner.rsindex b69774eb4c..546ec80ad1 100644--- a/crates/openhuman-tui/src/runner.rs+++ b/crates/openhuman-tui/src/runner.rs@@ -285,91 +285,5 @@ fn print_help() {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn extract_thread_id_handles_bare_summary() {- let v = json!({ "id": "thread-1", "title": "x" });- assert_eq!(extract_thread_id(&v).as_deref(), Some("thread-1"));- }-- #[test]- fn extract_thread_id_handles_api_envelope() {- let v = json!({ "data": { "id": "thread-2" }, "meta": {} });- assert_eq!(extract_thread_id(&v).as_deref(), Some("thread-2"));- }-- #[test]- fn extract_thread_id_handles_log_envelope_around_api_envelope() {- let v = json!({- "result": { "data": { "id": "thread-3" }, "meta": {} },- "logs": ["created"]- });- assert_eq!(extract_thread_id(&v).as_deref(), Some("thread-3"));- }-- #[test]- fn extract_thread_id_missing_returns_none() {- let v = json!({ "meta": {} });- assert_eq!(extract_thread_id(&v), None);- }-- #[test]- fn short_hex_is_twelve_chars() {- assert_eq!(short_hex().len(), 12);- }-- /// Regression guard: the RPC method names the TUI invokes must be the- /// canonical `openhuman.<namespace>_<function>` form that the registry- /// resolves — NOT the dotted `namespace.function` short form, which- /// `schema_for_rpc_method` does not recognise and which would make every- /// turn (and the launch-time thread creation) fail with "unknown method".- /// The dispatcher only rewrites a fixed set of legacy aliases; none of- /// these three are in that table, so the short form never resolves.- #[test]- fn tui_invokes_use_canonical_registered_rpc_method_names() {- #[allow(unused_mut)]- let mut methods = vec![- "openhuman.channel_web_chat",- "openhuman.channel_web_cancel",- "openhuman.channel_web_queue_status",- "openhuman.threads_create_new",- "openhuman.threads_list",- "openhuman.threads_transcript_get",- "openhuman.threads_update_title",- "openhuman.threads_delete",- "openhuman.threads_task_board_get",- "openhuman.threads_token_usage",- "openhuman.thread_goals_get",- "openhuman.thread_goals_set",- "openhuman.profiles_list",- "openhuman.profiles_select",- "openhuman.ai_list_artifacts",- "openhuman.approval_list_pending",- "openhuman.approval_decide",- "openhuman.plan_review_decide",- "openhuman.config_get_client_config",- "openhuman.config_get_agent_paths",- "openhuman.config_update_model_settings",- "openhuman.config_get_autonomy_settings",- "openhuman.config_update_autonomy_settings",- "openhuman.config_get_privacy_mode",- "openhuman.config_set_privacy_mode",- "openhuman.auth_get_state",- "openhuman.auth_get_me",- "openhuman.auth_consume_login_token",- "openhuman.auth_store_session",- "openhuman.auth_clear_session",- ];- methods.push("openhuman.skills_list");- methods.push("openhuman.mcp_clients_installed_list");- for method in methods {- assert!(- openhuman_core::core::all::schema_for_rpc_method(method).is_some(),- "TUI invokes `{method}`, but it is not a registered RPC method — \- the tabbed terminal UI would fail with `unknown method: {method}`"- );- }- }-}+#[path = "runner_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/runner_tests.rs b/crates/openhuman-tui/src/runner_tests.rsnew file mode 100644index 0000000000..970aa84136--- /dev/null+++ b/crates/openhuman-tui/src/runner_tests.rs@@ -0,0 +1,86 @@+use super::*;++#[test]+fn extract_thread_id_handles_bare_summary() {+ let v = json!({ "id": "thread-1", "title": "x" });+ assert_eq!(extract_thread_id(&v).as_deref(), Some("thread-1"));+}++#[test]+fn extract_thread_id_handles_api_envelope() {+ let v = json!({ "data": { "id": "thread-2" }, "meta": {} });+ assert_eq!(extract_thread_id(&v).as_deref(), Some("thread-2"));+}++#[test]+fn extract_thread_id_handles_log_envelope_around_api_envelope() {+ let v = json!({+ "result": { "data": { "id": "thread-3" }, "meta": {} },+ "logs": ["created"]+ });+ assert_eq!(extract_thread_id(&v).as_deref(), Some("thread-3"));+}++#[test]+fn extract_thread_id_missing_returns_none() {+ let v = json!({ "meta": {} });+ assert_eq!(extract_thread_id(&v), None);+}++#[test]+fn short_hex_is_twelve_chars() {+ assert_eq!(short_hex().len(), 12);+}++/// Regression guard: the RPC method names the TUI invokes must be the+/// canonical `openhuman.<namespace>_<function>` form that the registry+/// resolves — NOT the dotted `namespace.function` short form, which+/// `schema_for_rpc_method` does not recognise and which would make every+/// turn (and the launch-time thread creation) fail with "unknown method".+/// The dispatcher only rewrites a fixed set of legacy aliases; none of+/// these three are in that table, so the short form never resolves.+#[test]+fn tui_invokes_use_canonical_registered_rpc_method_names() {+ #[allow(unused_mut)]+ let mut methods = vec![+ "openhuman.channel_web_chat",+ "openhuman.channel_web_cancel",+ "openhuman.channel_web_queue_status",+ "openhuman.threads_create_new",+ "openhuman.threads_list",+ "openhuman.threads_transcript_get",+ "openhuman.threads_update_title",+ "openhuman.threads_delete",+ "openhuman.threads_task_board_get",+ "openhuman.threads_token_usage",+ "openhuman.thread_goals_get",+ "openhuman.thread_goals_set",+ "openhuman.profiles_list",+ "openhuman.profiles_select",+ "openhuman.ai_list_artifacts",+ "openhuman.approval_list_pending",+ "openhuman.approval_decide",+ "openhuman.plan_review_decide",+ "openhuman.config_get_client_config",+ "openhuman.config_get_agent_paths",+ "openhuman.config_update_model_settings",+ "openhuman.config_get_autonomy_settings",+ "openhuman.config_update_autonomy_settings",+ "openhuman.config_get_privacy_mode",+ "openhuman.config_set_privacy_mode",+ "openhuman.auth_get_state",+ "openhuman.auth_get_me",+ "openhuman.auth_consume_login_token",+ "openhuman.auth_store_session",+ "openhuman.auth_clear_session",+ ];+ methods.push("openhuman.skills_list");+ methods.push("openhuman.mcp_clients_installed_list");+ for method in methods {+ assert!(+ openhuman_core::core::all::schema_for_rpc_method(method).is_some(),+ "TUI invokes `{method}`, but it is not a registered RPC method — \+ the tabbed terminal UI would fail with `unknown method: {method}`"+ );+ }+}diff --git a/crates/openhuman-tui/src/state.rs b/crates/openhuman-tui/src/state.rsindex 0a044f5053..5688e1e7e8 100644--- a/crates/openhuman-tui/src/state.rs+++ b/crates/openhuman-tui/src/state.rs@@ -402,304 +402,5 @@ fn truncate_line(s: &str) -> String {}#[cfg(test)]-mod tests {- use super::*;-- const CLIENT: &str = "tui-abc123";-- fn ev(event: &str) -> WebChannelEvent {- WebChannelEvent {- event: event.to_string(),- client_id: CLIENT.to_string(),- thread_id: "thread-1".to_string(),- ..Default::default()- }- }-- fn text_delta(delta: &str) -> WebChannelEvent {- WebChannelEvent {- delta: Some(delta.to_string()),- delta_kind: Some("text".to_string()),- ..ev("text_delta")- }- }-- fn thinking_delta(delta: &str) -> WebChannelEvent {- WebChannelEvent {- delta: Some(delta.to_string()),- delta_kind: Some("thinking".to_string()),- ..ev("thinking_delta")- }- }-- #[test]- fn text_deltas_accumulate_into_one_assistant_entry() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("hi");- s.apply_event(&text_delta("Hel"));- s.apply_event(&text_delta("lo "));- s.apply_event(&text_delta("world"));-- let assistant: Vec<_> = s- .entries()- .iter()- .filter(|e| e.kind == EntryKind::Assistant)- .collect();- assert_eq!(assistant.len(), 1, "deltas must fold into a single entry");- assert_eq!(assistant[0].text, "Hello world");- assert!(s.is_streaming(), "still streaming before chat_done");- }-- #[test]- fn thinking_and_text_are_separate_entries() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("q");- s.apply_event(&thinking_delta("let me think"));- s.apply_event(&text_delta("answer"));-- let kinds: Vec<_> = s.entries().iter().map(|e| e.kind).collect();- assert_eq!(- kinds,- vec![EntryKind::User, EntryKind::Thinking, EntryKind::Assistant]- );- let thinking = s- .entries()- .iter()- .find(|e| e.kind == EntryKind::Thinking)- .unwrap();- assert_eq!(thinking.text, "let me think");- }-- #[test]- fn thinking_deltas_accumulate_separately_from_text() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("q");- s.apply_event(&thinking_delta("a"));- s.apply_event(&thinking_delta("b"));- s.apply_event(&text_delta("x"));- s.apply_event(&thinking_delta("c")); // interleaved — same thinking entry- let thinking: Vec<_> = s- .entries()- .iter()- .filter(|e| e.kind == EntryKind::Thinking)- .collect();- assert_eq!(thinking.len(), 1);- assert_eq!(thinking[0].text, "abc");- }-- #[test]- fn chat_done_replaces_streamed_text_with_full_response() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("hi");- s.apply_event(&text_delta("Hel")); // partial / laggy stream- let done = WebChannelEvent {- full_response: Some("Hello, world!".to_string()),- ..ev("chat_done")- };- s.apply_event(&done);-- let assistant: Vec<_> = s- .entries()- .iter()- .filter(|e| e.kind == EntryKind::Assistant)- .collect();- assert_eq!(assistant.len(), 1);- assert_eq!(- assistant[0].text, "Hello, world!",- "full_response is authoritative and replaces the streamed text"- );- assert!(!s.is_streaming(), "chat_done ends the turn");- }-- #[test]- fn chat_done_without_prior_deltas_still_shows_full_response() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("hi");- let done = WebChannelEvent {- full_response: Some("Direct answer".to_string()),- ..ev("chat_done")- };- s.apply_event(&done);- let assistant = s- .entries()- .iter()- .find(|e| e.kind == EntryKind::Assistant)- .expect("chat_done with full_response must produce an assistant entry");- assert_eq!(assistant.text, "Direct answer");- assert!(!s.is_streaming());- }-- #[test]- fn chat_error_pushes_error_entry_and_ends_stream() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("hi");- let err = WebChannelEvent {- message: Some("rate limited".to_string()),- error_type: Some("rate_limit".to_string()),- ..ev("chat_error")- };- s.apply_event(&err);- let error = s- .entries()- .iter()- .find(|e| e.kind == EntryKind::Error)- .expect("chat_error must produce an error entry");- assert_eq!(error.text, "rate limited");- assert!(!s.is_streaming(), "chat_error ends the turn");- }-- #[test]- fn retryable_error_includes_retry_timing() {- let mut state = TranscriptState::new(CLIENT);- state.begin_user_turn("try");- state.apply_event(&WebChannelEvent {- message: Some("rate limited".into()),- error_retryable: Some(true),- error_retry_after_ms: Some(2_100),- ..ev("chat_error")- });- assert_eq!(- state.entries().last().unwrap().text,- "rate limited · retryable after 3s"- );- }-- #[test]- fn last_assistant_excludes_an_in_flight_partial_answer() {- let mut state = TranscriptState::new(CLIENT);- state.begin_user_turn("question");- state.apply_event(&text_delta("partial"));- assert_eq!(state.last_assistant(), None);- state.apply_event(&WebChannelEvent {- full_response: Some("complete".into()),- ..ev("chat_done")- });- assert_eq!(state.last_assistant(), Some("complete"));- }-- #[test]- fn events_for_other_client_id_are_ignored() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("hi");- let before = s.entries().len();- let foreign = WebChannelEvent {- client_id: "tui-someone-else".to_string(),- delta: Some("not mine".to_string()),- ..WebChannelEvent {- event: "text_delta".to_string(),- thread_id: "thread-1".to_string(),- ..Default::default()- }- };- s.apply_event(&foreign);- assert_eq!(- s.entries().len(),- before,- "foreign client_id events must not mutate our transcript"- );- }-- #[test]- fn events_for_an_inactive_thread_are_ignored() {- let mut state = TranscriptState::new(CLIENT);- state.set_thread("thread-1");- let event = WebChannelEvent {- thread_id: "thread-2".into(),- ..text_delta("not this conversation")- };- state.apply_event(&event);- assert!(state.entries().is_empty());- }-- #[test]- fn projected_transcript_is_restored_in_chronological_order() {- let mut state = TranscriptState::new(CLIENT);- state.load_transcript(&serde_json::json!({- "result": {"data": {"items": [- {"kind": "assistantMessage", "content": "answer"},- {"kind": "userMessage", "content": "question"}- ]}}- }));- assert_eq!(state.entries()[0].text, "question");- assert_eq!(state.entries()[1].text, "answer");- }-- #[test]- fn tool_call_and_result_produce_tool_entries() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("do it");- let call = WebChannelEvent {- tool_name: Some("web_search".to_string()),- args: Some(serde_json::json!({"query": "rust ratatui"})),- ..ev("tool_call")- };- s.apply_event(&call);- let result = WebChannelEvent {- tool_name: Some("web_search".to_string()),- success: Some(true),- output: Some("3 results".to_string()),- ..ev("tool_result")- };- s.apply_event(&result);-- let tools: Vec<_> = s- .entries()- .iter()- .filter(|e| e.kind == EntryKind::Tool)- .collect();- assert_eq!(tools.len(), 2);- assert!(tools[0].text.starts_with("→ web_search"));- assert!(tools[0].text.contains("rust ratatui"));- assert!(tools[1].text.starts_with("✓ web_search"));- assert!(tools[1].text.contains("3 results"));- }-- #[test]- fn failed_tool_result_uses_cross_marker() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("do it");- let result = WebChannelEvent {- tool_name: Some("run_shell".to_string()),- success: Some(false),- output: Some("exit code 1".to_string()),- ..ev("tool_result")- };- s.apply_event(&result);- let tool = s- .entries()- .iter()- .find(|e| e.kind == EntryKind::Tool)- .unwrap();- assert!(tool.text.starts_with("✗ run_shell"));- }-- #[test]- fn second_turn_opens_fresh_assistant_entry() {- let mut s = TranscriptState::new(CLIENT);- s.begin_user_turn("first");- s.apply_event(&text_delta("one"));- s.apply_event(&WebChannelEvent {- full_response: Some("one".to_string()),- ..ev("chat_done")- });- s.begin_user_turn("second");- s.apply_event(&text_delta("two"));-- let assistant: Vec<_> = s- .entries()- .iter()- .filter(|e| e.kind == EntryKind::Assistant)- .collect();- assert_eq!(assistant.len(), 2, "each turn gets its own assistant entry");- assert_eq!(assistant[0].text, "one");- assert_eq!(assistant[1].text, "two");- }-- #[test]- fn truncate_line_collapses_newlines_and_caps_length() {- let long = "a\nb\n".repeat(200);- let out = truncate_line(&long);- assert!(!out.contains('\n'));- assert!(out.chars().count() <= 121, "capped to MAX + ellipsis");- }-}+#[path = "state_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/state_tests.rs b/crates/openhuman-tui/src/state_tests.rsnew file mode 100644index 0000000000..4b8724f7c9--- /dev/null+++ b/crates/openhuman-tui/src/state_tests.rs@@ -0,0 +1,299 @@+use super::*;++const CLIENT: &str = "tui-abc123";++fn ev(event: &str) -> WebChannelEvent {+ WebChannelEvent {+ event: event.to_string(),+ client_id: CLIENT.to_string(),+ thread_id: "thread-1".to_string(),+ ..Default::default()+ }+}++fn text_delta(delta: &str) -> WebChannelEvent {+ WebChannelEvent {+ delta: Some(delta.to_string()),+ delta_kind: Some("text".to_string()),+ ..ev("text_delta")+ }+}++fn thinking_delta(delta: &str) -> WebChannelEvent {+ WebChannelEvent {+ delta: Some(delta.to_string()),+ delta_kind: Some("thinking".to_string()),+ ..ev("thinking_delta")+ }+}++#[test]+fn text_deltas_accumulate_into_one_assistant_entry() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("hi");+ s.apply_event(&text_delta("Hel"));+ s.apply_event(&text_delta("lo "));+ s.apply_event(&text_delta("world"));++ let assistant: Vec<_> = s+ .entries()+ .iter()+ .filter(|e| e.kind == EntryKind::Assistant)+ .collect();+ assert_eq!(assistant.len(), 1, "deltas must fold into a single entry");+ assert_eq!(assistant[0].text, "Hello world");+ assert!(s.is_streaming(), "still streaming before chat_done");+}++#[test]+fn thinking_and_text_are_separate_entries() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("q");+ s.apply_event(&thinking_delta("let me think"));+ s.apply_event(&text_delta("answer"));++ let kinds: Vec<_> = s.entries().iter().map(|e| e.kind).collect();+ assert_eq!(+ kinds,+ vec![EntryKind::User, EntryKind::Thinking, EntryKind::Assistant]+ );+ let thinking = s+ .entries()+ .iter()+ .find(|e| e.kind == EntryKind::Thinking)+ .unwrap();+ assert_eq!(thinking.text, "let me think");+}++#[test]+fn thinking_deltas_accumulate_separately_from_text() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("q");+ s.apply_event(&thinking_delta("a"));+ s.apply_event(&thinking_delta("b"));+ s.apply_event(&text_delta("x"));+ s.apply_event(&thinking_delta("c")); // interleaved — same thinking entry+ let thinking: Vec<_> = s+ .entries()+ .iter()+ .filter(|e| e.kind == EntryKind::Thinking)+ .collect();+ assert_eq!(thinking.len(), 1);+ assert_eq!(thinking[0].text, "abc");+}++#[test]+fn chat_done_replaces_streamed_text_with_full_response() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("hi");+ s.apply_event(&text_delta("Hel")); // partial / laggy stream+ let done = WebChannelEvent {+ full_response: Some("Hello, world!".to_string()),+ ..ev("chat_done")+ };+ s.apply_event(&done);++ let assistant: Vec<_> = s+ .entries()+ .iter()+ .filter(|e| e.kind == EntryKind::Assistant)+ .collect();+ assert_eq!(assistant.len(), 1);+ assert_eq!(+ assistant[0].text, "Hello, world!",+ "full_response is authoritative and replaces the streamed text"+ );+ assert!(!s.is_streaming(), "chat_done ends the turn");+}++#[test]+fn chat_done_without_prior_deltas_still_shows_full_response() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("hi");+ let done = WebChannelEvent {+ full_response: Some("Direct answer".to_string()),+ ..ev("chat_done")+ };+ s.apply_event(&done);+ let assistant = s+ .entries()+ .iter()+ .find(|e| e.kind == EntryKind::Assistant)+ .expect("chat_done with full_response must produce an assistant entry");+ assert_eq!(assistant.text, "Direct answer");+ assert!(!s.is_streaming());+}++#[test]+fn chat_error_pushes_error_entry_and_ends_stream() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("hi");+ let err = WebChannelEvent {+ message: Some("rate limited".to_string()),+ error_type: Some("rate_limit".to_string()),+ ..ev("chat_error")+ };+ s.apply_event(&err);+ let error = s+ .entries()+ .iter()+ .find(|e| e.kind == EntryKind::Error)+ .expect("chat_error must produce an error entry");+ assert_eq!(error.text, "rate limited");+ assert!(!s.is_streaming(), "chat_error ends the turn");+}++#[test]+fn retryable_error_includes_retry_timing() {+ let mut state = TranscriptState::new(CLIENT);+ state.begin_user_turn("try");+ state.apply_event(&WebChannelEvent {+ message: Some("rate limited".into()),+ error_retryable: Some(true),+ error_retry_after_ms: Some(2_100),+ ..ev("chat_error")+ });+ assert_eq!(+ state.entries().last().unwrap().text,+ "rate limited · retryable after 3s"+ );+}++#[test]+fn last_assistant_excludes_an_in_flight_partial_answer() {+ let mut state = TranscriptState::new(CLIENT);+ state.begin_user_turn("question");+ state.apply_event(&text_delta("partial"));+ assert_eq!(state.last_assistant(), None);+ state.apply_event(&WebChannelEvent {+ full_response: Some("complete".into()),+ ..ev("chat_done")+ });+ assert_eq!(state.last_assistant(), Some("complete"));+}++#[test]+fn events_for_other_client_id_are_ignored() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("hi");+ let before = s.entries().len();+ let foreign = WebChannelEvent {+ client_id: "tui-someone-else".to_string(),+ delta: Some("not mine".to_string()),+ ..WebChannelEvent {+ event: "text_delta".to_string(),+ thread_id: "thread-1".to_string(),+ ..Default::default()+ }+ };+ s.apply_event(&foreign);+ assert_eq!(+ s.entries().len(),+ before,+ "foreign client_id events must not mutate our transcript"+ );+}++#[test]+fn events_for_an_inactive_thread_are_ignored() {+ let mut state = TranscriptState::new(CLIENT);+ state.set_thread("thread-1");+ let event = WebChannelEvent {+ thread_id: "thread-2".into(),+ ..text_delta("not this conversation")+ };+ state.apply_event(&event);+ assert!(state.entries().is_empty());+}++#[test]+fn projected_transcript_is_restored_in_chronological_order() {+ let mut state = TranscriptState::new(CLIENT);+ state.load_transcript(&serde_json::json!({+ "result": {"data": {"items": [+ {"kind": "assistantMessage", "content": "answer"},+ {"kind": "userMessage", "content": "question"}+ ]}}+ }));+ assert_eq!(state.entries()[0].text, "question");+ assert_eq!(state.entries()[1].text, "answer");+}++#[test]+fn tool_call_and_result_produce_tool_entries() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("do it");+ let call = WebChannelEvent {+ tool_name: Some("web_search".to_string()),+ args: Some(serde_json::json!({"query": "rust ratatui"})),+ ..ev("tool_call")+ };+ s.apply_event(&call);+ let result = WebChannelEvent {+ tool_name: Some("web_search".to_string()),+ success: Some(true),+ output: Some("3 results".to_string()),+ ..ev("tool_result")+ };+ s.apply_event(&result);++ let tools: Vec<_> = s+ .entries()+ .iter()+ .filter(|e| e.kind == EntryKind::Tool)+ .collect();+ assert_eq!(tools.len(), 2);+ assert!(tools[0].text.starts_with("→ web_search"));+ assert!(tools[0].text.contains("rust ratatui"));+ assert!(tools[1].text.starts_with("✓ web_search"));+ assert!(tools[1].text.contains("3 results"));+}++#[test]+fn failed_tool_result_uses_cross_marker() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("do it");+ let result = WebChannelEvent {+ tool_name: Some("run_shell".to_string()),+ success: Some(false),+ output: Some("exit code 1".to_string()),+ ..ev("tool_result")+ };+ s.apply_event(&result);+ let tool = s+ .entries()+ .iter()+ .find(|e| e.kind == EntryKind::Tool)+ .unwrap();+ assert!(tool.text.starts_with("✗ run_shell"));+}++#[test]+fn second_turn_opens_fresh_assistant_entry() {+ let mut s = TranscriptState::new(CLIENT);+ s.begin_user_turn("first");+ s.apply_event(&text_delta("one"));+ s.apply_event(&WebChannelEvent {+ full_response: Some("one".to_string()),+ ..ev("chat_done")+ });+ s.begin_user_turn("second");+ s.apply_event(&text_delta("two"));++ let assistant: Vec<_> = s+ .entries()+ .iter()+ .filter(|e| e.kind == EntryKind::Assistant)+ .collect();+ assert_eq!(assistant.len(), 2, "each turn gets its own assistant entry");+ assert_eq!(assistant[0].text, "one");+ assert_eq!(assistant[1].text, "two");+}++#[test]+fn truncate_line_collapses_newlines_and_caps_length() {+ let long = "a\nb\n".repeat(200);+ let out = truncate_line(&long);+ assert!(!out.contains('\n'));+ assert!(out.chars().count() <= 121, "capped to MAX + ellipsis");+}diff --git a/crates/openhuman-tui/src/ui_state.rs b/crates/openhuman-tui/src/ui_state.rsindex f38aad48b1..143fa523ff 100644--- a/crates/openhuman-tui/src/ui_state.rs+++ b/crates/openhuman-tui/src/ui_state.rs@@ -183,17 +183,5 @@ impl Drop for UiState {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn ui_starts_on_chat_and_tabs_wrap_in_product_order() {- let ui = UiState::new("thread".into(), "client".into());- assert_eq!(ui.active_tab, AppTab::Chat);- assert_eq!(AppTab::Logs.next(), AppTab::Chat);- assert_eq!(AppTab::Chat.next(), AppTab::Config);- assert_eq!(AppTab::Config.next(), AppTab::Settings);- assert_eq!(AppTab::Settings.next(), AppTab::Logs);- assert_eq!(AppTab::Logs.previous(), AppTab::Settings);- }-}+#[path = "ui_state_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/ui_state_tests.rs b/crates/openhuman-tui/src/ui_state_tests.rsnew file mode 100644index 0000000000..9f28cc9e9d--- /dev/null+++ b/crates/openhuman-tui/src/ui_state_tests.rs@@ -0,0 +1,12 @@+use super::*;++#[test]+fn ui_starts_on_chat_and_tabs_wrap_in_product_order() {+ let ui = UiState::new("thread".into(), "client".into());+ assert_eq!(ui.active_tab, AppTab::Chat);+ assert_eq!(AppTab::Logs.next(), AppTab::Chat);+ assert_eq!(AppTab::Chat.next(), AppTab::Config);+ assert_eq!(AppTab::Config.next(), AppTab::Settings);+ assert_eq!(AppTab::Settings.next(), AppTab::Logs);+ assert_eq!(AppTab::Logs.previous(), AppTab::Settings);+}