From b077493ba14feec2eb1803c432f98db78cc58ea9 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 10:24:44 +0800 Subject: [PATCH 1/3] fix(cli-peer): close controller capability gaps on CLI peer hosts Terminal output never reached a Desktop controller on a CLI host: the host publishes cursor hints on terminal- while the controller only listened for terminal_event, so a shell looked hung. The controller now follows those hints with bounded replay pages, selected by host_type so older hosts of both kinds keep working. CLI hosts also publish terminal-exit and terminal-closed. Add CLI handlers for get_skill_configs, get_mode_skill_configs, get_runtime_logging_info, btw_ask_stream and btw_cancel, and advertise the BTW model selection capabilities. ACP and diagnostics bundles stay unsupported with explicit reasons that the settings pages and /btw now surface. --- docs/architecture/peer-device-mode.md | 6 +- src/apps/cli/src/logging.rs | 42 ++++ src/apps/cli/src/peer_host/commands/btw.rs | 201 +++++++++++++++++ src/apps/cli/src/peer_host/commands/dialog.rs | 4 +- src/apps/cli/src/peer_host/commands/mod.rs | 14 ++ src/apps/cli/src/peer_host/commands/skills.rs | 177 +++++++++++++++ src/apps/cli/src/peer_host/commands/system.rs | 4 + .../cli/src/peer_host/commands/terminal.rs | 83 ++++++- .../generated/remote-surface-registry.json | 51 +++-- .../src/remote_surface/capabilities.rs | 6 +- .../src/remote_surface/table.rs | 48 +++-- .../pages/data/DiagnosticsSettingsPage.tsx | 11 +- .../src/flow_chat/components/ChatInput.tsx | 3 + .../api/generated/remoteSurface.ts | 4 +- .../config/components/AcpAgentsConfig.tsx | 11 +- .../peer-device/deviceSurfaceRouting.ts | 3 + .../peer-device/peerHostRefusal.test.ts | 25 +++ .../peer-device/peerHostRefusal.ts | 18 ++ .../services/PeerTerminalReplay.test.ts | 202 ++++++++++++++++++ .../terminal/services/PeerTerminalReplay.ts | 178 +++++++++++++++ .../terminal/services/TerminalService.test.ts | 88 ++++++++ .../terminal/services/TerminalService.ts | 46 ++++ .../src/tools/terminal/types/session.ts | 2 + 23 files changed, 1164 insertions(+), 63 deletions(-) create mode 100644 src/apps/cli/src/peer_host/commands/btw.rs create mode 100644 src/apps/cli/src/peer_host/commands/skills.rs create mode 100644 src/web-ui/src/infrastructure/peer-device/peerHostRefusal.test.ts create mode 100644 src/web-ui/src/infrastructure/peer-device/peerHostRefusal.ts create mode 100644 src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts create mode 100644 src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts diff --git a/docs/architecture/peer-device-mode.md b/docs/architecture/peer-device-mode.md index 922783b873..ae2a1fb565 100644 --- a/docs/architecture/peer-device-mode.md +++ b/docs/architecture/peer-device-mode.md @@ -386,7 +386,11 @@ FS) and must not be mixed with Peer Device Mode. lose its subscription. SSH notification consumers tolerate broadcast lag and read the retained cursor. Controllers fetch bounded replay pages and render them in their terminal surface. Account retirement stops that publisher's - notification observers without terminating the PTY. + notification observers without terminating the PTY. `terminal-exit` and + `terminal-closed` on the same stream report the PTY lifecycle; an older CLI + host omits them and the controller learns of a removed session from the + replay read. The Desktop controller selects this path by `host_type` + (`PeerTerminalReplay`); Desktop hosts keep fanning out `terminal_event`. - During Peer Mode, controller-local SSH maintenance and selected background editor/Git/search refreshes retain their existing noise-reduction policy. These UI refresh policies are separate from durable session synchronization. diff --git a/src/apps/cli/src/logging.rs b/src/apps/cli/src/logging.rs index bcc211ec00..6653bb3079 100644 --- a/src/apps/cli/src/logging.rs +++ b/src/apps/cli/src/logging.rs @@ -32,6 +32,7 @@ pub(crate) struct CliLogPaths { } static ACTIVE_LOG_PATHS: OnceLock = OnceLock::new(); +static ACTIVE_LOG_LEVEL: OnceLock = OnceLock::new(); struct RotatingFile { dir: PathBuf, @@ -254,6 +255,32 @@ pub(crate) fn active_plugin_host_log_path() -> Option { .map(|paths| paths.plugin_host_log_path.clone()) } +/// The `get_runtime_logging_info` wire shape shared with Desktop hosts. Logs a +/// CLI does not write (webview, Flow Chat, native startup) report empty paths. +pub(crate) fn runtime_logging_info() -> serde_json::Value { + let paths = ACTIVE_LOG_PATHS + .get() + .cloned() + .unwrap_or_else(|| build_log_paths(&resolve_logs_root())); + let level = ACTIVE_LOG_LEVEL.get().copied().unwrap_or(DEFAULT_LOG_LEVEL); + logging_info_value(&paths, level) +} + +fn logging_info_value(paths: &CliLogPaths, level: tracing::Level) -> serde_json::Value { + serde_json::json!({ + "effectiveLevel": level.as_str().to_ascii_lowercase(), + "sessionLogDir": paths.session_log_dir.to_string_lossy(), + "earlyStartupLogPath": "", + "nativeStartupTracePath": "", + "appLogPath": paths.app_log_path.to_string_lossy(), + "aiLogPath": paths.ai_log_path.to_string_lossy(), + "flashgrepLogPath": paths.flashgrep_log_path.to_string_lossy(), + "webviewLogPath": "", + "flowChatLogPath": "", + "previousUnexpectedExit": serde_json::Value::Null, + }) +} + fn create_rotating_writer( session_log_dir: &Path, file_name: &str, @@ -379,6 +406,7 @@ pub(crate) fn init_file_logging_at( fs::create_dir_all(session_log_dir).ok(); let paths = build_log_paths(session_log_dir); let _ = ACTIVE_LOG_PATHS.set(paths.clone()); + let _ = ACTIVE_LOG_LEVEL.set(log_level); let app_writer = create_rotating_writer(session_log_dir, "app"); let ai_writer = create_rotating_writer(session_log_dir, "ai"); @@ -419,6 +447,20 @@ mod tests { use super::*; use tracing::Subscriber; + #[test] + fn logging_info_matches_the_controller_wire_shape() { + let info = logging_info_value( + &build_log_paths(Path::new("/logs/session")), + tracing::Level::DEBUG, + ); + assert_eq!(info["effectiveLevel"], "debug"); + assert_eq!(info["sessionLogDir"], "/logs/session"); + assert!(info["appLogPath"].as_str().unwrap().ends_with("app.log")); + assert!(info["aiLogPath"].as_str().unwrap().ends_with("ai.log")); + assert_eq!(info["webviewLogPath"], ""); + assert!(info["previousUnexpectedExit"].is_null()); + } + fn file_subscriber( dir: &Path, level: tracing::Level, diff --git a/src/apps/cli/src/peer_host/commands/btw.rs b/src/apps/cli/src/peer_host/commands/btw.rs new file mode 100644 index 0000000000..a897038e07 --- /dev/null +++ b/src/apps/cli/src/peer_host/commands/btw.rs @@ -0,0 +1,201 @@ +//! `/btw` side-question HostInvoke handlers. +//! +//! The turn runs on the Core coordinator as a child session and flows through +//! the normal agentic event pipeline, so a controller observes it exactly like +//! a side question on a Desktop host. + +use std::sync::{Arc, OnceLock}; +use std::time::Duration; + +use openbitfun_core::agentic::coordination::{ + get_global_coordinator, ConversationCoordinator, DialogSubmissionPolicy, DialogTriggerSource, +}; +use openbitfun_core::agentic::core::SessionState; +use openbitfun_core::agentic::image_analysis::ImageContextData; +use openbitfun_core::agentic::side_question::SideQuestionRuntime; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::peer_host::args::{get_string, request_value}; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct BtwAskStreamRequest { + request_id: String, + session_id: String, + question: String, + child_session_id: String, + child_session_name: Option, + parent_dialog_turn_id: Option, + parent_turn_index: Option, + model_id: Option, + #[serde(default)] + image_contexts: Option>, + #[serde(default)] + initial_model_selection: Option, + #[serde(default)] + initial_model_target: Option, +} + +fn side_questions() -> &'static Arc { + static RUNTIME: OnceLock> = OnceLock::new(); + RUNTIME.get_or_init(|| Arc::new(SideQuestionRuntime::new())) +} + +fn coordinator() -> Result, String> { + get_global_coordinator() + .ok_or_else(|| "Side questions are unavailable: the agent runtime is not running".into()) +} + +fn parse_ask_request(request: &Value) -> Result { + let parsed: BtwAskStreamRequest = serde_json::from_value(request.clone()) + .map_err(|error| format!("Invalid side question request: {error}"))?; + for (value, name) in [ + (&parsed.request_id, "requestId"), + (&parsed.session_id, "sessionId"), + (&parsed.child_session_id, "childSessionId"), + (&parsed.question, "question"), + ] { + if value.trim().is_empty() { + return Err(format!("{name} is required")); + } + } + Ok(parsed) +} + +pub(crate) async fn btw_ask_stream(args: &Value) -> Result { + let raw = request_value(args); + let request = parse_ask_request(raw)?; + // Same reserved-key policy as a Peer dialog turn: routing metadata belongs + // to this host and a controller's copy of it is dropped. + let metadata = match raw.get("userMessageMetadata") { + None | Some(Value::Null) => None, + Some(_) => Some(Value::Object(super::dialog::peer_dialog_metadata(raw)?)), + }; + let coordinator = coordinator()?; + let child_session_id = request.child_session_id.trim().to_string(); + let turn_id = coordinator + .start_btw_turn( + &request.request_id, + &request.session_id, + &child_session_id, + request.child_session_name.as_deref(), + &request.question, + DialogSubmissionPolicy::for_source(DialogTriggerSource::DesktopUi), + request.model_id.as_deref(), + request.image_contexts, + request.parent_dialog_turn_id.as_deref(), + request.parent_turn_index, + metadata, + request.initial_model_selection, + request.initial_model_target, + ) + .await + .map_err(|error| error.to_string())?; + + let runtime = side_questions().clone(); + runtime + .register_btw_turn( + request.request_id.clone(), + child_session_id.clone(), + turn_id.clone(), + ) + .await; + let request_id = request.request_id; + tokio::spawn(async move { + // The registration only serves cancellation; release it once the turn settles. + loop { + let processing = coordinator + .get_session_manager() + .get_session(&child_session_id) + .is_some_and(|session| { + matches!( + session.state, + SessionState::Processing { current_turn_id, .. } + if current_turn_id == turn_id + ) + }); + if !processing { + runtime.remove(&request_id).await; + break; + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + }); + Ok(json!({ "ok": true })) +} + +pub(crate) async fn btw_cancel(args: &Value) -> Result { + let request_id = get_string(request_value(args), "requestId")?; + if request_id.trim().is_empty() { + return Err("requestId is required".to_string()); + } + let runtime = side_questions(); + runtime.cancel(&request_id).await; + if let Some(active) = runtime.get_btw_turn(&request_id).await { + coordinator()? + .cancel_dialog_turn(&active.session_id, &active.turn_id) + .await + .map_err(|error| error.to_string())?; + runtime.remove(&request_id).await; + } + Ok(Value::Null) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ask_request_reads_legacy_payloads_and_ignores_future_fields() { + let request = parse_ask_request(&json!({ + "requestId": "request-1", + "sessionId": "parent-1", + "childSessionId": "child-1", + "question": "Why?", + "futureField": true, + })) + .unwrap(); + assert!(request.initial_model_selection.is_none()); + assert!(request.initial_model_target.is_none()); + assert!(request.image_contexts.is_none()); + } + + #[test] + fn ask_request_accepts_typed_model_targets() { + let request = parse_ask_request(&json!({ + "requestId": "request-1", + "sessionId": "parent-1", + "childSessionId": "child-1", + "question": "Why?", + "initialModelTarget": { "selection": { "kind": "pool", "pool_id": "pool-a" } }, + })) + .unwrap(); + assert!(request.initial_model_target.is_some()); + } + + #[test] + fn ask_request_rejects_blank_identity_fields() { + for field in ["requestId", "sessionId", "childSessionId", "question"] { + let mut payload = json!({ + "requestId": "request-1", + "sessionId": "parent-1", + "childSessionId": "child-1", + "question": "Why?", + }); + payload[field] = json!(" "); + let error = parse_ask_request(&payload).unwrap_err(); + assert_eq!(error, format!("{field} is required")); + } + } + + #[tokio::test] + async fn cancel_of_an_unknown_request_is_a_no_op() { + assert_eq!( + btw_cancel(&json!({ "request": { "requestId": "unknown-request" } })) + .await + .unwrap(), + Value::Null + ); + } +} diff --git a/src/apps/cli/src/peer_host/commands/dialog.rs b/src/apps/cli/src/peer_host/commands/dialog.rs index 0f1ee7de23..81cc338dd4 100644 --- a/src/apps/cli/src/peer_host/commands/dialog.rs +++ b/src/apps/cli/src/peer_host/commands/dialog.rs @@ -72,7 +72,9 @@ fn dialog_submission_slot( .clone()) } -fn peer_dialog_metadata(request: &Value) -> Result, String> { +pub(super) fn peer_dialog_metadata( + request: &Value, +) -> Result, String> { let mut metadata = match request.get("userMessageMetadata") { Some(Value::Object(metadata)) => metadata.clone(), Some(Value::Null) | None => serde_json::Map::new(), diff --git a/src/apps/cli/src/peer_host/commands/mod.rs b/src/apps/cli/src/peer_host/commands/mod.rs index 450857480a..770824b0a2 100644 --- a/src/apps/cli/src/peer_host/commands/mod.rs +++ b/src/apps/cli/src/peer_host/commands/mod.rs @@ -1,5 +1,6 @@ //! Product HostInvoke command handlers for CLI Peer Host. +mod btw; mod config; mod dialog; mod external_sources; @@ -10,6 +11,7 @@ mod models; mod permission; mod product_control; mod session; +mod skills; mod snapshot; mod soft; mod system; @@ -187,6 +189,8 @@ pub(crate) fn dispatch<'a>( // coordinator via the compatibility surface both CLI and Desktop Peer // Hosts share. "cancel_tool" => Box::pin(dialog::cancel_tool(state, args)), + "btw_ask_stream" => Box::pin(btw::btw_ask_stream(args)), + "btw_cancel" => Box::pin(btw::btw_cancel(args)), "get_session_interaction_mailbox" => Box::pin(std::future::ready(permission::get_session_interaction_mailbox(state, args))), "list_pending_permission_requests" => Box::pin(std::future::ready(permission::list_pending_permission_requests(state))), "subscribe_permission_requests" => Box::pin(std::future::ready(permission::subscribe_permission_requests())), @@ -216,8 +220,13 @@ pub(crate) fn dispatch<'a>( "get_acp_clients" => Box::pin(soft::get_acp_clients()), "list_background_command_activities" => Box::pin(soft::list_background_command_activities()), + // Skills + "get_skill_configs" => Box::pin(skills::get_skill_configs(args)), + "get_mode_skill_configs" => Box::pin(skills::get_mode_skill_configs(args)), + // System "get_system_info" => Box::pin(system::get_system_info()), + "get_runtime_logging_info" => Box::pin(system::get_runtime_logging_info()), "get_token_usage_statistics" => Box::pin(system::get_token_usage_statistics(state, args)), // Only reachable if the registry marks a command Handled without a @@ -234,6 +243,11 @@ pub(crate) fn dispatch<'a>( /// cannot be advertised as runnable here without a handler (or vice versa). #[cfg(test)] pub(crate) const HANDLED_COMMANDS: &[&str] = &[ + "btw_ask_stream", + "btw_cancel", + "get_skill_configs", + "get_mode_skill_configs", + "get_runtime_logging_info", "terminal_execute", "terminal_get", "terminal_get_shells", diff --git a/src/apps/cli/src/peer_host/commands/skills.rs b/src/apps/cli/src/peer_host/commands/skills.rs new file mode 100644 index 0000000000..e929c18192 --- /dev/null +++ b/src/apps/cli/src/peer_host/commands/skills.rs @@ -0,0 +1,177 @@ +//! Skill discovery HostInvoke handlers. +//! +//! Discovery is owned by the Core `SkillRegistry`; this adapter only resolves +//! the workspace the controller selected and picks its local or SSH provider. +//! Installed-source markers are SkillHub market metadata, and the CLI host has +//! no market surface, so reports leave `installationSource` unset. + +use std::time::Duration; + +use openbitfun_core::agentic::tools::implementations::skills::mode_overrides::SkillPolicyWorkspace; +use openbitfun_core::agentic::tools::implementations::skills::{SkillRegistry, SkillScanReport}; +use openbitfun_core::agentic::workspace::RemoteWorkspaceFs; +use openbitfun_core::service::workspace::{get_global_workspace_service, WorkspaceInfo}; +use serde::Serialize; +use serde_json::Value; + +use crate::peer_host::args::{get_string, optional_bool, optional_string, request_value}; + +const REMOTE_SKILL_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(60); + +async fn resolve_workspace(request: &Value) -> Result, String> { + let id = optional_string(request, "workspaceId"); + let legacy_path = optional_string(request, "workspacePath"); + if id.is_none() && legacy_path.is_none() { + return Ok(None); + } + let service = get_global_workspace_service().ok_or("Workspace service is unavailable")?; + if let Some(id) = id { + return service + .require_workspace(&id) + .await + .map(Some) + .map_err(|error| error.to_string()); + } + // Pre-ID controllers still send a path; normal callers select a catalog ID. + service + .resolve_legacy_workspace_reference( + None, + legacy_path.as_deref().unwrap_or_default(), + None, + None, + ) + .await + .map_err(|error| error.to_string())? + .map(Some) + .ok_or_else(|| "Legacy Skill workspace cannot be resolved".to_string()) +} + +async fn remote_workspace_fs( + workspace: Option<&WorkspaceInfo>, +) -> Result, String> { + let Some(record) = workspace else { + return Ok(None); + }; + let Some(connection) = record.filesystem_connection_id()? else { + return Ok(None); + }; + let connection = connection.to_owned(); + let services = + openbitfun_core::service::remote_ssh::workspace_state::ensure_saved_connection_services() + .await?; + let file_service = services + .get_file_service() + .await + .ok_or("Remote file service is unavailable")?; + Ok(Some(( + record.root_path.to_string_lossy().into_owned(), + RemoteWorkspaceFs::new(connection, file_service), + ))) +} + +async fn within_remote_deadline( + discovery: impl std::future::Future, +) -> Result { + tokio::time::timeout(REMOTE_SKILL_DISCOVERY_TIMEOUT, discovery) + .await + .map_err(|_| { + format!( + "Remote Skill discovery timed out after {} seconds. Check the SSH/SFTP connection and retry.", + REMOTE_SKILL_DISCOVERY_TIMEOUT.as_secs() + ) + }) +} + +/// Older controllers expect a bare array unless they asked for diagnostics. +fn scan_response( + report: SkillScanReport, + include_diagnostics: bool, +) -> Result { + let value = if include_diagnostics { + serde_json::to_value(report) + } else { + serde_json::to_value(report.skills) + }; + value.map_err(|error| format!("Failed to serialize skill configs: {error}")) +} + +pub(crate) async fn get_skill_configs(args: &Value) -> Result { + let request = request_value(args); + let workspace = resolve_workspace(request).await?; + let registry = SkillRegistry::global(); + if optional_bool(request, "forceRefresh").unwrap_or(false) { + registry.refresh().await; + } + let report = if let Some((root, fs)) = remote_workspace_fs(workspace.as_ref()).await? { + within_remote_deadline(registry.get_skill_scan_report_for_remote_workspace(&fs, &root)) + .await? + } else { + let root = workspace.as_ref().map(|record| record.root_path.as_path()); + registry.get_skill_scan_report_for_workspace(root).await + }; + let mut response = scan_response( + report, + optional_bool(request, "includeDiagnostics").unwrap_or(false), + )?; + if let Some(object) = response.as_object_mut() { + // The import operations are not peer commands on this host; version 0 + // tells the controller not to offer them. + object.insert("importOperationsVersion".into(), Value::from(0)); + } + Ok(response) +} + +pub(crate) async fn get_mode_skill_configs(args: &Value) -> Result { + let request = request_value(args); + let mode_id = get_string(request, "modeId")?; + let workspace = resolve_workspace(request).await?; + let registry = SkillRegistry::global(); + if optional_bool(request, "forceRefresh").unwrap_or(false) { + registry.refresh().await; + } + let report = if let Some((root, fs)) = remote_workspace_fs(workspace.as_ref()).await? { + within_remote_deadline( + registry.get_mode_skill_scan_report_for_remote_workspace(&fs, &root, &mode_id), + ) + .await? + } else { + registry + .get_mode_skill_scan_report_for_workspace( + workspace.as_ref().map(SkillPolicyWorkspace::from_record), + &mode_id, + ) + .await + }; + scan_response( + report, + optional_bool(request, "includeDiagnostics").unwrap_or(false), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[tokio::test] + async fn mode_skill_configs_require_a_mode() { + let error = get_mode_skill_configs(&json!({})).await.unwrap_err(); + assert!(error.contains("modeId"), "{error}"); + } + + #[tokio::test] + async fn no_workspace_reference_needs_no_workspace_service() { + assert!(resolve_workspace(&json!({})).await.unwrap().is_none()); + } + + #[tokio::test] + async fn a_host_invoke_without_a_workspace_lists_host_level_skills() { + let bare = get_skill_configs(&json!({})).await.unwrap(); + assert!(bare.is_array(), "legacy controllers read an array"); + let report = get_skill_configs(&json!({ "includeDiagnostics": true })) + .await + .unwrap(); + assert!(report["skills"].is_array()); + assert_eq!(report["importOperationsVersion"], 0); + } +} diff --git a/src/apps/cli/src/peer_host/commands/system.rs b/src/apps/cli/src/peer_host/commands/system.rs index 3efa00a59d..ab718f833e 100644 --- a/src/apps/cli/src/peer_host/commands/system.rs +++ b/src/apps/cli/src/peer_host/commands/system.rs @@ -16,6 +16,10 @@ pub(crate) async fn get_system_info() -> Result { })) } +pub(crate) async fn get_runtime_logging_info() -> Result { + Ok(crate::logging::runtime_logging_info()) +} + pub(crate) async fn get_token_usage_statistics( state: &PeerHostState, args: &Value, diff --git a/src/apps/cli/src/peer_host/commands/terminal.rs b/src/apps/cli/src/peer_host/commands/terminal.rs index 1ea1d71ee9..33a8423661 100644 --- a/src/apps/cli/src/peer_host/commands/terminal.rs +++ b/src/apps/cli/src/peer_host/commands/terminal.rs @@ -4,14 +4,42 @@ use crate::peer_host::{ state::PeerHostState, }; use openbitfun_core::service::{ + remote_connect::host_stream::HostStreamHub, remote_ssh::{get_remote_workspace_manager, RemoteTerminalManager}, terminal::{ + session::{SessionStatus, TerminalSession}, CloseSessionRequest, CreateSessionRequest, ResizeRequest, TerminalApi, WriteRequest, }, }; use serde::de::DeserializeOwned; use serde_json::{json, Value}; +/// Lifecycle facts on `terminal-`. Output stays in the replay log; these +/// tell a controller when no more of it will come. +const TERMINAL_EXIT_EVENT: &str = "terminal-exit"; +const TERMINAL_CLOSED_EVENT: &str = "terminal-closed"; +const TERMINAL_EXIT_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1); + +async fn publish_lifecycle(hub: &HostStreamHub, id: &str, event: &str, mut payload: Value) { + payload["terminal_id"] = json!(id); + if let Err(error) = hub + .append(format!("terminal-{id}"), event.into(), payload) + .await + { + tracing::debug!( + "Terminal lifecycle event was not published: terminal={id} event={event} error={error}" + ); + } +} + +/// `Some(code)` once the PTY has exited; the code itself may be unknown. +fn exited_code(session: Option<&TerminalSession>) -> Option> { + match session?.status { + SessionStatus::Exited { exit_code } => Some(exit_code), + _ => None, + } +} + fn api() -> Result { TerminalApi::from_singleton().map_err(|e| e.to_string()) } @@ -136,7 +164,10 @@ pub(crate) async fn create(state: &PeerHostState, args: &Value) -> Result output, _ = closed.changed() => break }; match output { Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {} - Err(_) => break, + Err(_) => { + publish_lifecycle(&hub, &id, TERMINAL_CLOSED_EVENT, json!({})).await; + break; + } } tokio::time::sleep(std::time::Duration::from_millis(75)).await; if *closed.borrow() { @@ -144,6 +175,7 @@ pub(crate) async fn create(state: &PeerHostState, args: &Value) -> Result Result changed, _ = closed.changed() => break } - .is_err() - { - break; + tokio::select! { + changed = rx.changed() => { + if changed.is_err() { + publish_lifecycle(&hub, &id, TERMINAL_CLOSED_EVENT, json!({})).await; + break; + } + } + _ = exit_check.tick(), if !exit_published => { + if let Some(exit_code) = exited_code(manager.get_session(&id).await.as_ref()) { + exit_published = true; + publish_lifecycle(&hub, &id, TERMINAL_EXIT_EVENT, json!({"exit_code":exit_code})).await; + } + continue; + } + _ = closed.changed() => break, } tokio::time::sleep(std::time::Duration::from_millis(75)).await; if *closed.borrow() { @@ -420,3 +468,28 @@ pub(crate) async fn execute(args: &Value) -> Result { }; serde_json::to_value(result).map_err(|e| e.to_string()) } + +#[cfg(test)] +mod tests { + use super::*; + use openbitfun_core::service::terminal::{SessionSource, ShellType}; + + #[test] + fn exit_is_reported_only_for_an_exited_session() { + let mut session = TerminalSession::new( + "t1".into(), + "Shell".into(), + ShellType::Bash, + "/repo".into(), + 80, + 24, + SessionSource::Manual, + ); + assert_eq!(exited_code(None), None); + assert_eq!(exited_code(Some(&session)), None); + session.set_exited(Some(7)); + assert_eq!(exited_code(Some(&session)), Some(Some(7))); + session.set_exited(None); + assert_eq!(exited_code(Some(&session)), Some(None)); + } +} diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index fa268d4b0c..f3a3dc166d 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:ee62faff5c97f12a", + "digest": "fnv1a64:6c9684d5e2394817", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -101,6 +101,8 @@ "control_conversation_reset_v1", "idempotent_dialog_submit", "inline_image_attachments_v1", + "btw_initial_model_selection_v1", + "btw_model_pool_selection_v1", "targeted_session_rollback", "token_usage_statistics", "model_channel_routing_v1", @@ -784,8 +786,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -796,8 +797,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -809,7 +809,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -1341,7 +1341,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -2298,7 +2298,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not export diagnostics bundles; collect its log directory on that device instead" } }, { @@ -2430,7 +2430,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -2442,7 +2442,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -3050,8 +3050,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -3247,8 +3246,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -3385,8 +3383,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -4110,7 +4107,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -4181,7 +4178,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -4517,7 +4514,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -5599,7 +5596,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -5623,7 +5620,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -6794,7 +6791,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -7077,7 +7074,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -7089,7 +7086,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -7891,7 +7888,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -8033,7 +8030,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { @@ -8069,7 +8066,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device" } }, { diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index 038a3dd378..d577f2cec0 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -212,6 +212,8 @@ const CLI_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::ControlConversationResetV1, PeerHostCapability::IdempotentDialogSubmit, PeerHostCapability::InlineImageAttachmentsV1, + PeerHostCapability::BtwInitialModelSelectionV1, + PeerHostCapability::BtwModelPoolSelectionV1, PeerHostCapability::TargetedSessionRollback, PeerHostCapability::TokenUsageStatistics, PeerHostCapability::ModelChannelRoutingV1, @@ -287,11 +289,11 @@ mod tests { PeerHostKind::Desktop, PeerHostCapability::BtwInitialModelSelectionV1 )); - assert!(!advertises( + assert!(advertises( PeerHostKind::Cli, PeerHostCapability::BtwInitialModelSelectionV1 )); - assert!(!advertises( + assert!(advertises( PeerHostKind::Cli, PeerHostCapability::BtwModelPoolSelectionV1 )); diff --git a/src/crates/contracts/product-domains/src/remote_surface/table.rs b/src/crates/contracts/product-domains/src/remote_surface/table.rs index 68fdc2ff23..60caeacc6f 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -69,6 +69,12 @@ pub(super) const CLI_NO_BROWSER_OR_OS_AUTOMATION: HostSupport = HostSupport::Uns pub(super) const CLI_NO_REMOTE_WORKSPACE_UI: HostSupport = HostSupport::Unsupported { reason: "the CLI peer host does not expose the remote-workspace UI surface", }; +pub(super) const CLI_NO_ACP_CLIENT_HOST: HostSupport = HostSupport::Unsupported { + reason: "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device", +}; +pub(super) const CLI_NO_DIAGNOSTICS_BUNDLE: HostSupport = HostSupport::Unsupported { + reason: "the CLI peer host does not export diagnostics bundles; collect its log directory on that device instead", +}; pub(super) const SOFT_EMPTY_NO_CRON_HOST: HostSupport = HostSupport::SoftEmpty { reason: "the CLI peer host has no cron host; readiness is acknowledged so hydrate succeeds", }; @@ -139,9 +145,9 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("browser_webview_reload", LocalOnly, ControllerLocal, REFUSED), op("browser_webview_set_agent_target_state", LocalOnly, ControllerLocal, REFUSED), op("browser_webview_set_bounds", LocalOnly, ControllerLocal, REFUSED), - op("btw_ask_stream", Routed, Proxied, CLI_NOT_IMPLEMENTED), - op("btw_cancel", Routed, Proxied, CLI_NOT_IMPLEMENTED), - op("cancel_acp_dialog_turn", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("btw_ask_stream", Routed, Proxied, HANDLED), + op("btw_cancel", Routed, Proxied, HANDLED), + op("cancel_acp_dialog_turn", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("cancel_dialog_turn", Agnostic, Proxied, HANDLED), op("cancel_insights_generation", LocalOnly, ControllerLocal, REFUSED), op("cancel_mcp_remote_oauth", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -186,7 +192,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("control_background_command", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("control_deep_review_queue", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("copy_session", Routed, Proxied, CLI_NOT_IMPLEMENTED), - op("create_acp_flow_session", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("create_acp_flow_session", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("create_assistant_workspace", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("create_control_conversation", Agnostic, Proxied, HANDLED), op("create_cron_job", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -268,7 +274,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("explorer_get_children_paginated", Routed, Proxied, HANDLED), op("explorer_get_file_tree", Routed, Proxied, HANDLED), op("export_config", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("export_diagnostics_bundle", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("export_diagnostics_bundle", Unaudited, Proxied, CLI_NO_DIAGNOSTICS_BUNDLE), op("export_local_file_to_path", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), op("export_session_transcript", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("fetch_mcp_app_resource", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -279,8 +285,8 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("generate_insights", Routed, ControllerLocal, REFUSED), op("generate_session_title", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_acp_clients", Unaudited, Proxied, SOFT_EMPTY_ACP_CLIENTS), - op("get_acp_session_commands", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("get_acp_session_options", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("get_acp_session_commands", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), + op("get_acp_session_options", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("get_agent_profile_config", Unaudited, Proxied, HANDLED), op("get_agent_profile_configs", Unaudited, Proxied, HANDLED), op("get_ai_model_catalog", Agnostic, Proxied, HANDLED), @@ -336,7 +342,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("get_miniapp_draft_storage", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_miniapp_storage", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_miniapp_versions", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("get_mode_skill_configs", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("get_mode_skill_configs", Unaudited, Proxied, HANDLED), op("get_model_configs", Unaudited, Proxied, HANDLED), op("get_model_pool_status", Agnostic, Proxied, HANDLED), op("get_model_pools", Agnostic, Proxied, HANDLED), @@ -353,7 +359,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("get_readonly_tools_info", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_recent_workspaces", Agnostic, Proxied, HANDLED), op("get_runtime_capabilities", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("get_runtime_logging_info", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("get_runtime_logging_info", Unaudited, Proxied, HANDLED), op("get_session_file_diff_stats", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_session_files", Unaudited, Proxied, HANDLED), op("get_session_interaction_mailbox", Agnostic, Proxied, HANDLED), @@ -365,7 +371,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("get_session_thread_goal", Unaudited, Proxied, HANDLED), op("get_session_turns", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_session_usage_report", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("get_skill_configs", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("get_skill_configs", Unaudited, Proxied, HANDLED), op("get_snapshot_sessions", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_snapshot_system_stats", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_startup_native_trace", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), @@ -426,13 +432,13 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("i18n_set_language", Agnostic, ControllerLocal, REFUSED), op("import_agent_companion_pet_package", Unaudited, ControllerLocal, REFUSED), op("import_config", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("initialize_acp_clients", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("initialize_acp_clients", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("initialize_ai", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("initialize_mcp_servers", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("initialize_mcp_servers_non_destructive", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("initialize_tray_after_startup", LocalOnly, ControllerLocal, REFUSED), op("initialize_workspace_startup_state", Routed, Proxied, HANDLED), - op("install_acp_client_cli", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("install_acp_client_cli", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("install_pending_update", Agnostic, ControllerLocal, REFUSED), op("install_update", Agnostic, ControllerLocal, REFUSED), op("interrupt_dialog_turn", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), @@ -461,7 +467,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("list_subscription_account_instances", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), op("list_subscription_accounts", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), op("list_visible_subagents", Routed, Proxied, HANDLED), - op("load_acp_json_config", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("load_acp_json_config", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("load_agent_companion_pet_spritesheet", LocalOnly, ControllerLocal, REFUSED), op("load_canvas_artifact", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("load_canvas_state", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), @@ -552,9 +558,9 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("peer_mode_ping", Agnostic, HostControlPlane, HANDLED), op("plan_external_hook_import_command", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), op("plan_external_mcp_import_command", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), - op("predownload_acp_client_adapter", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("predownload_acp_client_adapter", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("preview_commit_message", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("probe_acp_client_requirements", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("probe_acp_client_requirements", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("product_control_invoke", Agnostic, Proxied, HANDLED), op("project_ai_model_reasoning_catalog", Agnostic, Proxied, HANDLED), op("quick_commit_message", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -653,7 +659,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("rollback_session_to_turn", Unsupported, Proxied, HANDLED), op("run_init_agents_md", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("run_system_command", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), - op("save_acp_json_config", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("save_acp_json_config", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("save_canvas_state", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("save_cloud_speech_config", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("save_git_repo_history", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -677,8 +683,8 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("send_background_command_input", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("send_mcp_app_message", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("send_system_notification", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), - op("set_acp_session_config_option", Routed, Proxied, CLI_NOT_IMPLEMENTED), - op("set_acp_session_model", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("set_acp_session_config_option", Routed, Proxied, CLI_NO_ACP_CLIENT_HOST), + op("set_acp_session_model", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("set_active_workspace", Agnostic, Proxied, HANDLED), op("set_agent_profile_config", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("set_config", Unaudited, Proxied, HANDLED), @@ -746,7 +752,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("ssh_start_port_forward", Agnostic, Proxied, CLI_NO_DESKTOP_IDE_SURFACE), op("ssh_stop_port_forward", Agnostic, Proxied, CLI_NO_DESKTOP_IDE_SURFACE), op("ssh_test_connection", Agnostic, Proxied, CLI_NO_DESKTOP_IDE_SURFACE), - op("start_acp_dialog_turn", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("start_acp_dialog_turn", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("start_dialog_turn", Routed, Proxied, HANDLED), op("start_file_watch", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), op("start_mcp_remote_oauth", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -758,10 +764,10 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("start_user_question_interaction", Agnostic, Proxied, HANDLED), op("startup_window_control", LocalOnly, ControllerLocal, REFUSED), op("steer_dialog_turn", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), - op("stop_acp_client", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("stop_acp_client", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("stop_file_watch", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("stop_mcp_server", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("submit_acp_permission_response", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("submit_acp_permission_response", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("submit_mcp_interaction_response", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("submit_user_answers", Agnostic, Proxied, HANDLED), op("subscribe_permission_requests", Agnostic, Proxied, HANDLED), diff --git a/src/web-ui/src/app/scenes/settings/pages/data/DiagnosticsSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/data/DiagnosticsSettingsPage.tsx index 6da18253a7..fb014aa6c3 100644 --- a/src/web-ui/src/app/scenes/settings/pages/data/DiagnosticsSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/data/DiagnosticsSettingsPage.tsx @@ -8,6 +8,7 @@ import type { BackendLogLevel, RuntimeLoggingInfo } from '@/infrastructure/config/types'; +import { peerHostRefusalReason } from '@/infrastructure/peer-device/peerHostRefusal'; import { createLogger } from '@/shared/utils/logger'; import { Alert, Button, ConfirmDialog, IconButton, Input, Select, Switch, Tooltip } from '@openbitfun/ui'; import { Archive, FolderOpen } from 'lucide-react'; @@ -18,6 +19,12 @@ const loggingRuntime = createSettingsReadCache(); const log = createLogger('DiagnosticsSettingsPage'); +/** A peer host's explicit refusal says more than the generic failure copy. */ +function withHostReason(failure: string, error: unknown): string { + const reason = peerHostRefusalReason(error); + return reason ? `${failure}: ${reason}` : failure; +} + function LoggingSection() { const { t } = useTranslation('settings/application'); const seed = useConfigSeed(['app.logging.level', 'app.logging.include_sensitive_diagnostics']); @@ -141,7 +148,7 @@ function LoggingSection() { await workspaceAPI.revealInExplorer(folder); } catch (error) { log.error('Failed to open log folder', { folder, error }); - showMessage('error', t('logging.messages.openFailed')); + showMessage('error', withHostReason(t('logging.messages.openFailed'), error)); } finally { setOpeningFolder(false); } @@ -156,7 +163,7 @@ function LoggingSection() { await workspaceAPI.revealInExplorer(result.bundlePath); } catch (error) { log.error('Failed to export diagnostics bundle', { error }); - showMessage('error', t('logging.messages.diagnosticsExportFailed')); + showMessage('error', withHostReason(t('logging.messages.diagnosticsExportFailed'), error)); } finally { setExportingDiagnostics(false); } diff --git a/src/web-ui/src/flow_chat/components/ChatInput.tsx b/src/web-ui/src/flow_chat/components/ChatInput.tsx index e17ec33d8f..b4d6a954c2 100644 --- a/src/web-ui/src/flow_chat/components/ChatInput.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInput.tsx @@ -95,6 +95,7 @@ import { successfulRetryCleanupTarget, } from './chatInputDraftRecovery'; import { startBtwThread } from '../services/BtwThreadService'; +import { peerHostRefusalReason } from '@/infrastructure/peer-device/peerHostRefusal'; import { buildImagePayload } from '../utils/imagePayload'; import { canRestoreQueuedMessageToComposer, @@ -3714,6 +3715,8 @@ export const ChatInput: React.FC = ({ selectTargetSession(childSessionId); } catch (e) { log.error('Failed to start /btw thread', { e }); + const refusal = peerHostRefusalReason(e); + if (refusal) notificationService.error(refusal); replacePendingLargePastes(originalPendingLargePastes); dispatchInput({ type: 'SET_VALUE', payload: originalMessage }); } diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index 8d9d4fe2a2..9c8cf1d783 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:ee62faff5c97f12a" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:6c9684d5e2394817" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -269,6 +269,8 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "control_conversation_reset_v1", "idempotent_dialog_submit", "inline_image_attachments_v1", + "btw_initial_model_selection_v1", + "btw_model_pool_selection_v1", "targeted_session_rollback", "token_usage_statistics", "model_channel_routing_v1", diff --git a/src/web-ui/src/infrastructure/config/components/AcpAgentsConfig.tsx b/src/web-ui/src/infrastructure/config/components/AcpAgentsConfig.tsx index 33a82b8eb2..6e1219f9ad 100644 --- a/src/web-ui/src/infrastructure/config/components/AcpAgentsConfig.tsx +++ b/src/web-ui/src/infrastructure/config/components/AcpAgentsConfig.tsx @@ -18,6 +18,7 @@ import { OverflowText, } from '@openbitfun/ui'; import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; import { useI18n } from '@/infrastructure/i18n'; +import { peerHostRefusalReason } from '@/infrastructure/peer-device/peerHostRefusal'; import { CircleAlert, EyeOff, FileJson, Save, Server } from 'lucide-react'; import { ConfigPageContent, @@ -502,6 +503,7 @@ const AcpAgentsConfig = forwardRef( const [savedConnections, setSavedConnections] = useState([]); const [loading, setLoading] = useState(true); const [loadFailed, setLoadFailed] = useState(false); + const [loadRefusal, setLoadRefusal] = useState(null); const [saving, setSaving] = useState(false); const [dirty, setDirty] = useState(false); const [pendingPermissionMigration, setPendingPermissionMigration] = useState(false); @@ -740,6 +742,7 @@ const AcpAgentsConfig = forwardRef( if (showLoading) { setLoading(true); setLoadFailed(false); + setLoadRefusal(null); } const [rawConfig, nextClients] = await Promise.all([ ACPClientAPI.loadJsonConfig(), @@ -772,8 +775,10 @@ const AcpAgentsConfig = forwardRef( } } catch (error) { log.error('Failed to load ACP agent config', error); - if (showLoading) setLoadFailed(true); - else { + if (showLoading) { + setLoadFailed(true); + setLoadRefusal(peerHostRefusalReason(error)); + } else { notifyError(error instanceof Error ? error.message : String(error), { title: t('notifications.loadFailed'), }); @@ -1355,7 +1360,7 @@ const AcpAgentsConfig = forwardRef( ) : ( void loadConfig()} /> diff --git a/src/web-ui/src/infrastructure/peer-device/deviceSurfaceRouting.ts b/src/web-ui/src/infrastructure/peer-device/deviceSurfaceRouting.ts index 558d751eac..fb53133ee3 100644 --- a/src/web-ui/src/infrastructure/peer-device/deviceSurfaceRouting.ts +++ b/src/web-ui/src/infrastructure/peer-device/deviceSurfaceRouting.ts @@ -33,6 +33,9 @@ export const PEER_EVENT_WRAPPED_PAYLOAD_KEY = '__openbitfunSourcePayload'; */ const SURFACE_SCOPED_EVENTS = new Set([ 'terminal_event', + 'terminal-output', + 'terminal-exit', + 'terminal-closed', 'relay://session-gap', 'relay://session-ready', 'session-record', diff --git a/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.test.ts b/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.test.ts new file mode 100644 index 0000000000..bb97a336f3 --- /dev/null +++ b/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest'; +import { peerHostRefusalReason } from './peerHostRefusal'; + +describe('peerHostRefusalReason', () => { + it('extracts the reason a host gave', () => { + expect(peerHostRefusalReason(new Error( + "command 'export_diagnostics_bundle' is not supported on CLI peer host: the CLI peer host does not export diagnostics bundles", + ))).toBe('The CLI peer host does not export diagnostics bundles'); + }); + + it('keeps the whole message when an older host gave no reason', () => { + expect(peerHostRefusalReason("command 'x' is not supported on CLI peer host")) + .toBe("Command 'x' is not supported on CLI peer host"); + }); + + it('recognizes a command the host version does not know', () => { + const message = "command 'x' is unknown to this OpenBitFun CLI peer host version; upgrade the peer host"; + expect(peerHostRefusalReason(new Error(message))).toBe(message); + }); + + it('leaves ordinary failures to the caller', () => { + expect(peerHostRefusalReason(new Error('disk full'))).toBeNull(); + expect(peerHostRefusalReason(undefined)).toBeNull(); + }); +}); diff --git a/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.ts b/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.ts new file mode 100644 index 0000000000..502e2f4018 --- /dev/null +++ b/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.ts @@ -0,0 +1,18 @@ +/** + * The reason a peer host gave for refusing a command, or `null` when the error + * is not a host capability refusal. `PeerRefusal::message` keeps these prefixes + * byte-stable, so settings pages can show the reason instead of a generic + * failure without knowing every command a host lacks. + */ +const REFUSAL = /command '[^']+' is not supported on \w+ peer host(?:: (.+))?$/s; +const UNKNOWN_TO_HOST = /command '[^']+' is unknown to this OpenBitFun \w+ peer host version/; + +export function peerHostRefusalReason(error: unknown): string | null { + const message = error instanceof Error ? error.message : typeof error === 'string' ? error : ''; + const refusal = REFUSAL.exec(message); + if (refusal) { + const reason = refusal[1] ?? message.slice(refusal.index); + return reason.charAt(0).toUpperCase() + reason.slice(1); + } + return UNKNOWN_TO_HOST.test(message) ? message : null; +} diff --git a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts new file mode 100644 index 0000000000..5ef31e135c --- /dev/null +++ b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts @@ -0,0 +1,202 @@ +// @vitest-environment jsdom + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +type Listener = (payload: any) => void; + +const mocks = vi.hoisted(() => ({ + invoke: vi.fn(), + listeners: new Map void>>(), + ready: new Set<(payload: any) => void>(), + syncError: new Set<(payload: any) => void>(), + subscribeSession: vi.fn(), + unsubscribeSession: vi.fn(), + surfaceId: 'peer-cli', + current: true, +})); + +vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ + api: { + invoke: mocks.invoke, + listen: (event: string, callback: Listener) => { + const set = mocks.listeners.get(event) ?? new Set(); + set.add(callback); + mocks.listeners.set(event, set); + return () => set.delete(callback); + }, + }, +})); +vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', () => ({ + remoteConnectAPI: { + subscribeSession: mocks.subscribeSession, + unsubscribeSession: mocks.unsubscribeSession, + onSessionReady: (callback: Listener) => { + mocks.ready.add(callback); + return () => mocks.ready.delete(callback); + }, + onSessionSyncError: (callback: Listener) => { + mocks.syncError.add(callback); + return () => mocks.syncError.delete(callback); + }, + }, +})); +vi.mock('@/infrastructure/peer-device/deviceSurface', () => ({ + getActiveSurfaceScope: () => ({ surfaceId: mocks.surfaceId, isCurrent: () => mocks.current }), +})); +vi.mock('@/shared/utils/logger', () => ({ + createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }), +})); + +import { PeerTerminalReplay, type PeerTerminalRawEvent } from './PeerTerminalReplay'; + +const emit = (event: string, payload: unknown) => + [...(mocks.listeners.get(event) ?? [])].forEach(listener => listener(payload)); +const ready = () => + [...mocks.ready].forEach(listener => listener({ sessionId: 'terminal-t1', hasMore: false, oldestSeq: 0, cursor: 0 })); +const page = (data: string, nextOffset: number, cursor = nextOffset, truncated = false) => ({ + data, nextOffset, cursor, truncated, +}); +const flush = async () => { + for (let i = 0; i < 6; i += 1) await Promise.resolve(); +}; + +describe('PeerTerminalReplay', () => { + let events: PeerTerminalRawEvent[]; + let replay: PeerTerminalReplay; + + beforeEach(() => { + events = []; + mocks.invoke.mockReset(); + mocks.listeners.clear(); + mocks.ready.clear(); + mocks.syncError.clear(); + mocks.subscribeSession.mockReset().mockResolvedValue('subscription-1'); + mocks.unsubscribeSession.mockReset().mockResolvedValue(undefined); + mocks.current = true; + replay = new PeerTerminalReplay('t1', 10, event => events.push(event)); + }); + + afterEach(() => { + replay.close(); + vi.useRealTimers(); + }); + + it('opens the terminal stream on the rendered peer', () => { + replay.start(); + expect(mocks.subscribeSession).toHaveBeenCalledWith('peer-cli', 'terminal-t1'); + }); + + it('continues after the history offset and follows cursor hints', async () => { + mocks.invoke.mockResolvedValueOnce(page('prompt$ ', 18)).mockResolvedValueOnce(page('ls\r\n', 22)); + replay.start(); + emit('terminal-output', { terminal_id: 't1', cursor: 18 }); + await flush(); + expect(mocks.invoke, 'hints replayed before the first page was applied are ignored').not.toHaveBeenCalled(); + + ready(); + await flush(); + expect(mocks.invoke).toHaveBeenLastCalledWith('terminal_get_history', { sessionId: 't1', afterOffset: 10 }); + emit('terminal-output', { terminal_id: 't1', cursor: 22 }); + await flush(); + expect(mocks.invoke).toHaveBeenLastCalledWith('terminal_get_history', { sessionId: 't1', afterOffset: 18 }); + expect(events.map(event => event.payload.data)).toEqual(['prompt$ ', 'ls\r\n']); + }); + + it('ignores hints for another terminal', async () => { + mocks.invoke.mockResolvedValue(page('', 10)); + replay.start(); + ready(); + await flush(); + mocks.invoke.mockClear(); + emit('terminal-output', { terminal_id: 'other', cursor: 99 }); + await flush(); + expect(mocks.invoke).not.toHaveBeenCalled(); + }); + + it('drains every bounded page before stopping', async () => { + mocks.invoke.mockResolvedValueOnce(page('a', 11, 13)).mockResolvedValueOnce(page('b', 12, 13)).mockResolvedValueOnce(page('c', 13, 13)); + replay.start(); + ready(); + await flush(); + expect(events.map(event => event.payload.data)).toEqual(['a', 'b', 'c']); + }); + + it('resets the screen when output left the bounded replay log', async () => { + mocks.invoke.mockResolvedValueOnce(page('tail', 500, 500, true)); + replay.start(); + ready(); + await flush(); + expect(events[0].payload.data).toBe('\x1bctail'); + }); + + it('delivers an exit only after the output already in the log', async () => { + mocks.invoke.mockResolvedValueOnce(page('bye\r\n', 15)); + replay.start(); + emit('terminal-exit', { terminal_id: 't1', exit_code: 3 }); + expect(events).toEqual([]); + ready(); + await flush(); + expect(events.map(event => event.type)).toEqual(['Data', 'Exit']); + expect(events[1].payload.exit_code).toBe(3); + }); + + it('maps a closed session to the destroyed event', async () => { + mocks.invoke.mockResolvedValue(page('', 10)); + replay.start(); + ready(); + await flush(); + emit('terminal-closed', { terminal_id: 't1' }); + await flush(); + expect(events.at(-1)?.type).toBe('SessionDestroyed'); + }); + + it('reports a vanished session from a host without lifecycle events', async () => { + mocks.invoke.mockRejectedValueOnce(new Error('Terminal is unavailable')); + replay.start(); + ready(); + await flush(); + expect(events).toEqual([{ type: 'SessionDestroyed', payload: { session_id: 't1' } }]); + }); + + it('retries a failed read from the same offset without losing output', async () => { + vi.useFakeTimers(); + mocks.invoke.mockRejectedValueOnce(new Error('relay timeout')).mockResolvedValueOnce(page('late', 14)); + replay.start(); + ready(); + await vi.advanceTimersByTimeAsync(0); + expect(events).toEqual([]); + await vi.advanceTimersByTimeAsync(1_000); + expect(mocks.invoke).toHaveBeenLastCalledWith('terminal_get_history', { sessionId: 't1', afterOffset: 10 }); + expect(events[0].payload.data).toBe('late'); + }); + + it('surfaces a stream a host cannot open instead of staying silent', async () => { + mocks.subscribeSession.mockRejectedValueOnce(new Error('older OpenBitFun version')); + replay.start(); + await flush(); + expect(events).toEqual([{ type: 'Error', payload: { session_id: 't1', message: 'older OpenBitFun version' } }]); + }); + + it('stays attached through a sync error after catching up', async () => { + mocks.invoke.mockResolvedValue(page('', 10)); + replay.start(); + ready(); + await flush(); + [...mocks.syncError].forEach(listener => listener({ sessionId: 'terminal-t1', targetDeviceId: 'peer-cli', message: 'relay dropped' })); + expect(events).toEqual([]); + }); + + it('drops late pages after the surface changed and releases the stream on close', async () => { + mocks.invoke.mockResolvedValueOnce(page('stale', 15)); + replay.start(); + await flush(); + ready(); + mocks.current = false; + await flush(); + expect(events).toEqual([]); + + replay.close(); + expect(mocks.unsubscribeSession).toHaveBeenCalledWith('subscription-1'); + expect(mocks.listeners.get('terminal-output')?.size).toBe(0); + }); +}); diff --git a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts new file mode 100644 index 0000000000..c137b855e3 --- /dev/null +++ b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts @@ -0,0 +1,178 @@ +import { api } from '@/infrastructure/api/service-api/ApiClient'; +import { remoteConnectAPI } from '@/infrastructure/api/service-api/RemoteConnectAPI'; +import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { createLogger } from '@/shared/utils/logger'; + +const log = createLogger('PeerTerminalReplay'); + +const MAX_RETRY_DELAY_MS = 15_000; +const TERMINAL_UNAVAILABLE = 'Terminal is unavailable'; +/** ESC c: output before this point left the host's bounded replay log. */ +const TERMINAL_RESET = '\x1bc'; + +/** The backend event shape `TerminalService.handleTerminalEvent` already accepts. */ +export interface PeerTerminalRawEvent { + type: 'Data' | 'Exit' | 'SessionDestroyed' | 'Error'; + payload: Record; +} + +interface TerminalReplayPage { + data: string; + nextOffset: number; + cursor: number; + truncated: boolean; +} + +/** + * Live output of one PTY on a CLI peer host. + * + * A CLI host publishes coalesced cursor hints on the `terminal-` host stream + * instead of fanning out raw output, so a slow controller costs the host nothing + * and cannot lose bytes silently. This reads the bounded replay pages those + * hints announce. Reconnects and missed hints heal themselves, because every + * read continues from the offset this client last applied. + */ +export class PeerTerminalReplay { + private readonly scope = getActiveSurfaceScope(); + private readonly streamId: string; + private readonly listeners: Array<() => void> = []; + private subscriptionId: string | null = null; + private closed = false; + private caughtUp = false; + private draining = false; + private dirty = false; + private pendingLifecycle: PeerTerminalRawEvent | null = null; + private retryDelay = 0; + private retryTimer: ReturnType | null = null; + + constructor( + private readonly sessionId: string, + private offset: number, + private readonly deliver: (event: PeerTerminalRawEvent) => void, + ) { + this.streamId = `terminal-${sessionId}`; + } + + start(): void { + // Listen before subscribing: the first page is emitted while subscribing. + this.listeners.push( + api.listen<{ terminal_id?: string }>('terminal-output', event => { + if (event?.terminal_id === this.sessionId && this.caughtUp) this.requestRead(); + }), + api.listen<{ terminal_id?: string; exit_code?: number | null }>('terminal-exit', event => { + if (event?.terminal_id !== this.sessionId) return; + this.finishAfterDrain({ + type: 'Exit', + payload: { session_id: this.sessionId, exit_code: event.exit_code ?? undefined }, + }); + }), + api.listen<{ terminal_id?: string }>('terminal-closed', event => { + if (event?.terminal_id !== this.sessionId) return; + this.finishAfterDrain({ type: 'SessionDestroyed', payload: { session_id: this.sessionId } }); + }), + remoteConnectAPI.onSessionReady(ready => { + if (ready.sessionId !== this.streamId) return; + this.caughtUp = true; + this.requestRead(); + }), + remoteConnectAPI.onSessionSyncError(error => { + if (error.sessionId !== this.streamId || error.targetDeviceId !== this.scope.surfaceId) return; + if (this.caughtUp) log.warn('Terminal stream sync error', { sessionId: this.sessionId, message: error.message }); + else this.fail(error.message); + }), + ); + void remoteConnectAPI.subscribeSession(this.scope.surfaceId, this.streamId).then( + id => { + if (this.closed) void this.release(id); + else this.subscriptionId = id; + }, + error => this.fail(error instanceof Error ? error.message : String(error)), + ); + } + + close(): void { + if (this.closed) return; + this.closed = true; + this.listeners.splice(0).forEach(unlisten => unlisten()); + if (this.retryTimer !== null) clearTimeout(this.retryTimer); + this.retryTimer = null; + if (this.subscriptionId) void this.release(this.subscriptionId); + this.subscriptionId = null; + } + + private release(subscriptionId: string): Promise { + return remoteConnectAPI.unsubscribeSession(subscriptionId).catch(error => { + log.warn('Failed to release terminal stream', { sessionId: this.sessionId, error }); + }); + } + + private isActive(): boolean { + return !this.closed && this.scope.isCurrent(); + } + + private fail(message: string): void { + if (!this.isActive()) return; + log.error('Terminal stream unavailable', { sessionId: this.sessionId, message }); + this.deliver({ type: 'Error', payload: { session_id: this.sessionId, message } }); + } + + /** The exit must not overtake output that is already in the replay log. */ + private finishAfterDrain(event: PeerTerminalRawEvent): void { + // A close supersedes an exit that is still waiting for its output. + this.pendingLifecycle = event; + if (this.caughtUp) this.requestRead(); + } + + private requestRead(): void { + this.dirty = true; + void this.drain(); + } + + private async drain(): Promise { + if (this.draining || !this.isActive()) return; + this.draining = true; + try { + while (this.dirty && this.isActive()) { + this.dirty = false; + const page = await api.invoke('terminal_get_history', { + sessionId: this.sessionId, + afterOffset: this.offset, + }); + if (!this.isActive()) return; + const data = page.truncated ? `${TERMINAL_RESET}${page.data}` : page.data; + if (data) this.deliver({ type: 'Data', payload: { session_id: this.sessionId, data } }); + const advanced = page.nextOffset > this.offset; + this.offset = page.nextOffset; + if (advanced && page.nextOffset < page.cursor) this.dirty = true; + } + this.retryDelay = 0; + const lifecycle = this.pendingLifecycle; + if (lifecycle && this.isActive()) { + this.pendingLifecycle = null; + this.deliver(lifecycle); + } + } catch (error) { + if (!this.isActive()) return; + const message = error instanceof Error ? error.message : String(error); + if (message.includes(TERMINAL_UNAVAILABLE)) { + // The session is gone, and a host without lifecycle events cannot say so. + this.deliver({ type: 'SessionDestroyed', payload: { session_id: this.sessionId } }); + return; + } + log.warn('Failed to read terminal output', { sessionId: this.sessionId, message }); + this.scheduleRetry(); + } finally { + this.draining = false; + } + } + + private scheduleRetry(): void { + this.dirty = true; + this.retryDelay = Math.min(this.retryDelay ? this.retryDelay * 2 : 1_000, MAX_RETRY_DELAY_MS); + if (this.retryTimer !== null) return; + this.retryTimer = setTimeout(() => { + this.retryTimer = null; + void this.drain(); + }, this.retryDelay); + } +} diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts index 925db6cedf..4ee26afa32 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts @@ -13,6 +13,25 @@ vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ }, })); +const hostKindMock = vi.hoisted(() => ({ current: null as string | null })); +const replayMock = vi.hoisted(() => ({ + created: [] as Array<{ sessionId: string; offset: number; deliver: (event: unknown) => void; start: ReturnType; close: ReturnType }>, +})); +vi.mock('@/infrastructure/peer-device/PeerConnectionManager', () => ({ + peerConnectionManager: { + get: () => ({ getState: () => ({ capabilities: { hostKind: hostKindMock.current } }) }), + }, +})); +vi.mock('./PeerTerminalReplay', () => ({ + PeerTerminalReplay: class { + start = vi.fn(); + close = vi.fn(); + constructor(public sessionId: string, public offset: number, public deliver: (event: unknown) => void) { + replayMock.created.push(this); + } + }, +})); + vi.mock('@/shared/utils/logger', () => ({ createLogger: () => ({ debug: vi.fn(), @@ -40,6 +59,8 @@ describe('TerminalService device surface switching', () => { listenMock.mockReset(); listenMock.mockReturnValue(() => {}); resetDeviceSurfaceForTest(); + hostKindMock.current = null; + replayMock.created.length = 0; }); afterEach(() => { @@ -100,4 +121,71 @@ describe('TerminalService device surface switching', () => { expect(service.isConnected()).toBe(true); expect(invokeMock).not.toHaveBeenCalled(); }); + + describe('CLI peer host output', () => { + async function connectToCliHost(): Promise { + hostKindMock.current = 'cli'; + activateSurface('peer-cli'); + const service = freshTerminalService(); + await service.connect(); + return service; + } + + it('follows replay pages from where the history ended', async () => { + const service = await connectToCliHost(); + invokeMock.mockResolvedValueOnce({ data: 'old', nextOffset: 3 }); + await service.getHistory('t1'); + service.onSessionEvent('t1', vi.fn()); + + expect(replayMock.created).toHaveLength(1); + expect(replayMock.created[0]).toMatchObject({ sessionId: 't1', offset: 3 }); + expect(replayMock.created[0].start).toHaveBeenCalledTimes(1); + }); + + it('routes replayed output through the same terminal event path', async () => { + const service = await connectToCliHost(); + const listener = vi.fn(); + service.onSessionEvent('t1', listener); + + replayMock.created[0].deliver({ type: 'Data', payload: { session_id: 't1', data: 'hello' } }); + + expect(listener).toHaveBeenCalledWith({ type: 'output', sessionId: 't1', data: 'hello' }); + }); + + it('shares one replay per session and stops it with the last listener', async () => { + const service = await connectToCliHost(); + const first = service.onSessionEvent('t1', vi.fn()); + const second = service.onSessionEvent('t1', vi.fn()); + expect(replayMock.created).toHaveLength(1); + + first(); + expect(replayMock.created[0].close).not.toHaveBeenCalled(); + second(); + expect(replayMock.created[0].close).toHaveBeenCalledTimes(1); + }); + + it('stops replaying when the session is destroyed or the surface is left', async () => { + const service = await connectToCliHost(); + service.onSessionEvent('t1', vi.fn()); + service.onSessionEvent('t2', vi.fn()); + + replayMock.created[0].deliver({ type: 'SessionDestroyed', payload: { session_id: 't1' } }); + expect(replayMock.created[0].close).toHaveBeenCalledTimes(1); + + await service.disconnect(); + expect(replayMock.created[1].close).toHaveBeenCalledTimes(1); + }); + + it('keeps Desktop hosts on terminal_event', async () => { + hostKindMock.current = 'desktop'; + activateSurface('peer-desktop'); + const service = freshTerminalService(); + await service.connect(); + invokeMock.mockResolvedValueOnce({ data: 'old', nextOffset: 3 }); + await service.getHistory('t1'); + service.onSessionEvent('t1', vi.fn()); + + expect(replayMock.created).toHaveLength(0); + }); + }); }); diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.ts b/src/web-ui/src/tools/terminal/services/TerminalService.ts index 7fc7dd71f4..1ae0795dc4 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.ts @@ -31,6 +31,8 @@ import type { UnsubscribeFunction, } from '../types'; import { TerminalOriginCache } from './terminalWorkspaceScope'; +import { PeerTerminalReplay } from './PeerTerminalReplay'; +import { peerConnectionManager } from '@/infrastructure/peer-device/PeerConnectionManager'; const log = createLogger('TerminalService'); @@ -54,6 +56,12 @@ export class TerminalService { private connectingPromise: Promise | null = null; + /** Live output of CLI peer hosts, which publish cursor hints instead of `terminal_event`. */ + private readonly peerReplays = new Map(); + + /** Where `getHistory` stopped, so the replay that follows neither repeats nor skips output. */ + private readonly replayOffsets = new Map(); + private constructor() { } @@ -118,6 +126,34 @@ export class TerminalService { } this.streamScope = null; this.connected = false; + this.peerReplays.forEach(replay => replay.close()); + this.peerReplays.clear(); + this.replayOffsets.clear(); + } + + /** + * Host kind is the negotiated fact here: every CLI host publishes cursor hints + * and only Desktop hosts fan out `terminal_event`, so old hosts of both kinds + * keep working without a new capability key. + */ + private usesPeerReplay(): boolean { + const { surfaceId } = getActiveSurfaceScope(); + return peerConnectionManager.get(surfaceId)?.getState().capabilities.hostKind === 'cli'; + } + + private ensurePeerReplay(sessionId: string): void { + if (this.peerReplays.has(sessionId) || !this.isConnected() || !this.usesPeerReplay()) return; + const offset = this.replayOffsets.get(sessionId) ?? 0; + this.replayOffsets.delete(sessionId); + const replay = new PeerTerminalReplay(sessionId, offset, event => this.handleTerminalEvent(event)); + this.peerReplays.set(sessionId, replay); + replay.start(); + } + + private stopPeerReplay(sessionId: string): void { + this.peerReplays.get(sessionId)?.close(); + this.peerReplays.delete(sessionId); + this.replayOffsets.delete(sessionId); } private isStreamCurrent(): boolean { @@ -210,6 +246,7 @@ export class TerminalService { ); } this.eventListeners.delete(sessionId); + this.stopPeerReplay(sessionId); } } @@ -220,11 +257,13 @@ export class TerminalService { this.eventListeners.set(sessionId, listeners); } listeners.add(callback); + this.ensurePeerReplay(sessionId); return () => { listeners?.delete(callback); if (listeners?.size === 0) { this.eventListeners.delete(sessionId); + this.stopPeerReplay(sessionId); } }; } @@ -307,6 +346,7 @@ export class TerminalService { log.debug('Session closed', { sessionId }); this.eventListeners.delete(sessionId); + this.stopPeerReplay(sessionId); } catch (error) { log.error('Failed to close session', error); throw error; @@ -322,6 +362,9 @@ export class TerminalService { await api.invoke('terminal_shutdown_all'); log.debug('All sessions closed'); this.eventListeners.clear(); + this.peerReplays.forEach(replay => replay.close()); + this.peerReplays.clear(); + this.replayOffsets.clear(); } catch (error) { log.error('Failed to shutdown all sessions', error); throw error; @@ -331,6 +374,9 @@ export class TerminalService { async getHistory(sessionId: string): Promise { try { const history = await api.invoke('terminal_get_history', { sessionId }); + if (this.usesPeerReplay() && typeof history.nextOffset === 'number') { + this.replayOffsets.set(sessionId, history.nextOffset); + } return history; } catch (error) { log.error('Failed to get history', error); diff --git a/src/web-ui/src/tools/terminal/types/session.ts b/src/web-ui/src/tools/terminal/types/session.ts index 11efe2825a..c775973337 100644 --- a/src/web-ui/src/tools/terminal/types/session.ts +++ b/src/web-ui/src/tools/terminal/types/session.ts @@ -124,6 +124,8 @@ export interface GetHistoryResponse { cols: number; /** PTY row count when history was captured. */ rows: number; + /** Replay offset following `data`; CLI peer hosts report it for live replay. */ + nextOffset?: number; } export type TerminalEventType = From 42fab447e49a96771b7e6968b56e1495d7815543 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 11:32:05 +0800 Subject: [PATCH 2/3] fix(cli-peer): address review gaps in CLI peer host capabilities - Serve get_global_skill_settings read-only on CLI hosts (directSkillManagementVersion 0) and let the Skills page tolerate a refusal from older hosts. - Register BTW turns with the peer turn tracker before submission using the core btw_turn_id helper, gated on event-stream continuity and released when the start fails. - Lead peer host refusals with localized copy and keep the host reason as secondary detail. - Poll terminal exit through a lightweight session_status accessor instead of cloning the whole session with its history. - Select terminal cursor replay through the typed terminal_cursor_replay_v1 capability, falling back to host kind for older CLI hosts, and re-decide once capabilities resolve. - Report a logging level the host did not apply instead of claiming it was updated. - Track lifecycle for tabs without a mounted view, drop stale replay offsets, publish terminal-exit and terminal-closed on remote SSH terminals, and detect removed sessions from the session list instead of error text. --- docs/architecture/peer-device-mode.md | 5 +- src/apps/cli/src/peer_host/commands/btw.rs | 140 +++++++++++++++--- src/apps/cli/src/peer_host/commands/mod.rs | 4 +- src/apps/cli/src/peer_host/commands/skills.rs | 47 +++++- .../cli/src/peer_host/commands/terminal.rs | 65 +++++--- .../src/agentic/coordination/coordinator.rs | 8 +- .../generated/remote-surface-registry.json | 11 +- .../src/remote_surface/capabilities.rs | 29 +++- .../product-domains/src/remote_surface/mod.rs | 7 + .../src/remote_surface/table.rs | 2 +- .../services/terminal/src/session/manager.rs | 9 ++ .../pages/data/DiagnosticsSettingsPage.tsx | 17 +-- .../pages/data/loggingLevelMessage.test.ts | 12 ++ .../pages/data/loggingLevelMessage.ts | 6 + .../skills/hooks/useInstalledSkills.test.tsx | 35 +++++ .../scenes/skills/hooks/useInstalledSkills.ts | 17 ++- .../src/flow_chat/components/ChatInput.tsx | 4 +- .../api/generated/remoteSurface.test.ts | 3 + .../api/generated/remoteSurface.ts | 4 +- .../config/components/AcpAgentsConfig.tsx | 4 +- .../peer-device/PeerConnectionManager.ts | 4 + .../peerCapabilityResolution.test.ts | 19 +++ .../peer-device/peerCapabilityResolution.ts | 9 ++ .../peer-device/peerHostRefusal.test.ts | 38 +++-- .../peer-device/peerHostRefusal.ts | 41 +++-- src/web-ui/src/locales/en-US/common.json | 5 + .../locales/en-US/settings/application.json | 1 + src/web-ui/src/locales/zh-CN/common.json | 5 + .../locales/zh-CN/settings/application.json | 1 + src/web-ui/src/locales/zh-TW/common.json | 5 + .../locales/zh-TW/settings/application.json | 1 + .../services/PeerTerminalReplay.test.ts | 81 +++++++++- .../terminal/services/PeerTerminalReplay.ts | 122 +++++++++++---- .../terminal/services/TerminalService.test.ts | 129 ++++++++++++---- .../terminal/services/TerminalService.ts | 87 +++++++---- 35 files changed, 787 insertions(+), 190 deletions(-) create mode 100644 src/web-ui/src/app/scenes/settings/pages/data/loggingLevelMessage.test.ts create mode 100644 src/web-ui/src/app/scenes/settings/pages/data/loggingLevelMessage.ts diff --git a/docs/architecture/peer-device-mode.md b/docs/architecture/peer-device-mode.md index ae2a1fb565..a780dc3fec 100644 --- a/docs/architecture/peer-device-mode.md +++ b/docs/architecture/peer-device-mode.md @@ -389,8 +389,9 @@ FS) and must not be mixed with Peer Device Mode. notification observers without terminating the PTY. `terminal-exit` and `terminal-closed` on the same stream report the PTY lifecycle; an older CLI host omits them and the controller learns of a removed session from the - replay read. The Desktop controller selects this path by `host_type` - (`PeerTerminalReplay`); Desktop hosts keep fanning out `terminal_event`. + session list. Hosts advertise this path as `terminal_cursor_replay_v1`; the + Desktop controller (`PeerTerminalReplay`) falls back to `host_type` for older + CLI hosts. Desktop hosts keep fanning out `terminal_event`. - During Peer Mode, controller-local SSH maintenance and selected background editor/Git/search refreshes retain their existing noise-reduction policy. These UI refresh policies are separate from durable session synchronization. diff --git a/src/apps/cli/src/peer_host/commands/btw.rs b/src/apps/cli/src/peer_host/commands/btw.rs index a897038e07..3345ed9ad0 100644 --- a/src/apps/cli/src/peer_host/commands/btw.rs +++ b/src/apps/cli/src/peer_host/commands/btw.rs @@ -2,13 +2,16 @@ //! //! The turn runs on the Core coordinator as a child session and flows through //! the normal agentic event pipeline, so a controller observes it exactly like -//! a side question on a Desktop host. +//! a side question on a Desktop host. Peer ownership follows the dialog turn +//! contract: it is registered before submission and released if that fails. +use std::future::Future; use std::sync::{Arc, OnceLock}; use std::time::Duration; use openbitfun_core::agentic::coordination::{ - get_global_coordinator, ConversationCoordinator, DialogSubmissionPolicy, DialogTriggerSource, + btw_turn_id, get_global_coordinator, ConversationCoordinator, DialogSubmissionPolicy, + DialogTriggerSource, }; use openbitfun_core::agentic::core::SessionState; use openbitfun_core::agentic::image_analysis::ImageContextData; @@ -17,6 +20,7 @@ use serde::Deserialize; use serde_json::{json, Value}; use crate::peer_host::args::{get_string, request_value}; +use crate::peer_host::state::{PeerHostState, PeerTurnKey, PeerTurnTracker}; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] @@ -63,7 +67,31 @@ fn parse_ask_request(request: &Value) -> Result { Ok(parsed) } -pub(crate) async fn btw_ask_stream(args: &Value) -> Result { +/// Own the turn for the duration of `start`, returning the stream generation it +/// was admitted under. A failed start releases the turn: it will never emit the +/// terminal event that would otherwise release it. +async fn start_owned_turn( + turns: &PeerTurnTracker, + turn: &PeerTurnKey, + start: F, +) -> Result +where + F: FnOnce() -> Fut, + Fut: Future>, +{ + let generation = turns.register_root(turn.clone())?; + if !turns.is_event_stream_generation_current(generation) { + turns.finish_turn(turn); + return Err("Peer event stream continuity was lost before side question start".to_string()); + } + if let Err(error) = start().await { + turns.finish_turn(turn); + return Err(error); + } + Ok(generation) +} + +pub(crate) async fn btw_ask_stream(state: &PeerHostState, args: &Value) -> Result { let raw = request_value(args); let request = parse_ask_request(raw)?; // Same reserved-key policy as a Peer dialog turn: routing metadata belongs @@ -74,34 +102,55 @@ pub(crate) async fn btw_ask_stream(args: &Value) -> Result { }; let coordinator = coordinator()?; let child_session_id = request.child_session_id.trim().to_string(); - let turn_id = coordinator - .start_btw_turn( - &request.request_id, - &request.session_id, - &child_session_id, - request.child_session_name.as_deref(), - &request.question, - DialogSubmissionPolicy::for_source(DialogTriggerSource::DesktopUi), - request.model_id.as_deref(), - request.image_contexts, - request.parent_dialog_turn_id.as_deref(), - request.parent_turn_index, - metadata, - request.initial_model_selection, - request.initial_model_target, - ) - .await - .map_err(|error| error.to_string())?; + let turn_id = btw_turn_id(&request.request_id); + let turn = PeerTurnKey::new(child_session_id.clone(), turn_id.clone()); + let submit = coordinator.clone(); + let child = child_session_id.clone(); + let request_id = request.request_id.clone(); + let parent_session_id = request.session_id.clone(); + let generation = start_owned_turn(&state.turns, &turn, || async move { + submit + .start_btw_turn( + &request_id, + &parent_session_id, + &child, + request.child_session_name.as_deref(), + &request.question, + DialogSubmissionPolicy::for_source(DialogTriggerSource::DesktopUi), + request.model_id.as_deref(), + request.image_contexts, + request.parent_dialog_turn_id.as_deref(), + request.parent_turn_index, + metadata, + request.initial_model_selection, + request.initial_model_target, + ) + .await + .map(|_| ()) + .map_err(|error| error.to_string()) + }) + .await?; + if !state.turns.is_event_stream_generation_current(generation) { + coordinator + .cancel_dialog_turn(&child_session_id, &turn_id) + .await + .map_err(|error| { + format!( + "Peer continuity was lost after side question start and cancellation could not be confirmed: session_id={child_session_id}, turn_id={turn_id}, error={error}" + ) + })?; + return Err("Peer event stream lost continuity while starting the side question".into()); + } let runtime = side_questions().clone(); + let request_id = request.request_id; runtime .register_btw_turn( - request.request_id.clone(), + request_id.clone(), child_session_id.clone(), turn_id.clone(), ) .await; - let request_id = request.request_id; tokio::spawn(async move { // The registration only serves cancellation; release it once the turn settles. loop { @@ -146,6 +195,51 @@ pub(crate) async fn btw_cancel(args: &Value) -> Result { mod tests { use super::*; + fn turn() -> PeerTurnKey { + PeerTurnKey::new("child-1", btw_turn_id("request-1")) + } + + #[test] + fn the_registered_turn_id_is_the_one_the_coordinator_assigns() { + assert_eq!(btw_turn_id(" request-1 "), "btw-turn-request-1"); + } + + #[tokio::test] + async fn a_started_turn_stays_owned_until_its_terminal_event() { + let turns = PeerTurnTracker::new(); + turns.mark_event_stream_ready(); + start_owned_turn(&turns, &turn(), || async { Ok(()) }) + .await + .unwrap(); + assert!(turns.owns("child-1", Some(&turn().turn_id))); + } + + #[tokio::test] + async fn the_turn_is_owned_while_it_starts_and_released_when_that_fails() { + let turns = PeerTurnTracker::new(); + turns.mark_event_stream_ready(); + let observer = turns.clone(); + let error = start_owned_turn(&turns, &turn(), || async move { + assert!(observer.owns("child-1", Some(&turn().turn_id))); + Err("model unavailable".to_string()) + }) + .await + .unwrap_err(); + assert_eq!(error, "model unavailable"); + assert!(!turns.owns("child-1", Some(&turn().turn_id))); + } + + #[tokio::test] + async fn a_turn_cannot_start_before_the_event_stream_is_ready() { + let turns = PeerTurnTracker::new(); + let result = start_owned_turn(&turns, &turn(), || async { + panic!("must not start an unobservable turn") + }) + .await; + assert!(result.is_err()); + assert!(!turns.owns("child-1", Some(&turn().turn_id))); + } + #[test] fn ask_request_reads_legacy_payloads_and_ignores_future_fields() { let request = parse_ask_request(&json!({ diff --git a/src/apps/cli/src/peer_host/commands/mod.rs b/src/apps/cli/src/peer_host/commands/mod.rs index 770824b0a2..f9912991e4 100644 --- a/src/apps/cli/src/peer_host/commands/mod.rs +++ b/src/apps/cli/src/peer_host/commands/mod.rs @@ -189,7 +189,7 @@ pub(crate) fn dispatch<'a>( // coordinator via the compatibility surface both CLI and Desktop Peer // Hosts share. "cancel_tool" => Box::pin(dialog::cancel_tool(state, args)), - "btw_ask_stream" => Box::pin(btw::btw_ask_stream(args)), + "btw_ask_stream" => Box::pin(btw::btw_ask_stream(state, args)), "btw_cancel" => Box::pin(btw::btw_cancel(args)), "get_session_interaction_mailbox" => Box::pin(std::future::ready(permission::get_session_interaction_mailbox(state, args))), "list_pending_permission_requests" => Box::pin(std::future::ready(permission::list_pending_permission_requests(state))), @@ -223,6 +223,7 @@ pub(crate) fn dispatch<'a>( // Skills "get_skill_configs" => Box::pin(skills::get_skill_configs(args)), "get_mode_skill_configs" => Box::pin(skills::get_mode_skill_configs(args)), + "get_global_skill_settings" => Box::pin(skills::get_global_skill_settings(args)), // System "get_system_info" => Box::pin(system::get_system_info()), @@ -247,6 +248,7 @@ pub(crate) const HANDLED_COMMANDS: &[&str] = &[ "btw_cancel", "get_skill_configs", "get_mode_skill_configs", + "get_global_skill_settings", "get_runtime_logging_info", "terminal_execute", "terminal_get", diff --git a/src/apps/cli/src/peer_host/commands/skills.rs b/src/apps/cli/src/peer_host/commands/skills.rs index e929c18192..4a8121d618 100644 --- a/src/apps/cli/src/peer_host/commands/skills.rs +++ b/src/apps/cli/src/peer_host/commands/skills.rs @@ -7,12 +7,16 @@ use std::time::Duration; -use openbitfun_core::agentic::tools::implementations::skills::mode_overrides::SkillPolicyWorkspace; +use openbitfun_core::agentic::tools::implementations::skills::mode_overrides::{ + load_globally_disabled_project_skills, load_globally_disabled_user_skills, SkillPolicyWorkspace, +}; use openbitfun_core::agentic::tools::implementations::skills::{SkillRegistry, SkillScanReport}; use openbitfun_core::agentic::workspace::RemoteWorkspaceFs; -use openbitfun_core::service::workspace::{get_global_workspace_service, WorkspaceInfo}; +use openbitfun_core::service::workspace::{ + get_global_workspace_service, WorkspaceInfo, WorkspaceKind, +}; use serde::Serialize; -use serde_json::Value; +use serde_json::{json, Value}; use crate::peer_host::args::{get_string, optional_bool, optional_string, request_value}; @@ -148,6 +152,32 @@ pub(crate) async fn get_mode_skill_configs(args: &Value) -> Result Result { + let workspace = resolve_workspace(request_value(args)).await?; + let user_keys = load_globally_disabled_user_skills() + .await + .map_err(|error| error.to_string())?; + let project_keys = match workspace.as_ref() { + Some(record) if record.workspace_kind != WorkspaceKind::Remote => { + load_globally_disabled_project_skills(SkillPolicyWorkspace::from_record(record)) + .await + .map_err(|error| error.to_string())? + } + _ => Vec::new(), + }; + Ok(global_settings_value(user_keys, project_keys)) +} + +fn global_settings_value(user_keys: Vec, project_keys: Vec) -> Value { + json!({ + "globallyDisabledUserSkillKeys": user_keys, + "globallyDisabledProjectSkillKeys": project_keys, + "directSkillManagementVersion": 0, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -159,6 +189,17 @@ mod tests { assert!(error.contains("modeId"), "{error}"); } + #[test] + fn global_settings_are_read_only_on_this_host() { + let settings = global_settings_value(vec!["user::a".into()], Vec::new()); + assert_eq!(settings["directSkillManagementVersion"], 0); + assert_eq!( + settings["globallyDisabledUserSkillKeys"], + json!(["user::a"]) + ); + assert_eq!(settings["globallyDisabledProjectSkillKeys"], json!([])); + } + #[tokio::test] async fn no_workspace_reference_needs_no_workspace_service() { assert!(resolve_workspace(&json!({})).await.unwrap().is_none()); diff --git a/src/apps/cli/src/peer_host/commands/terminal.rs b/src/apps/cli/src/peer_host/commands/terminal.rs index 33a8423661..0a32eb25a5 100644 --- a/src/apps/cli/src/peer_host/commands/terminal.rs +++ b/src/apps/cli/src/peer_host/commands/terminal.rs @@ -7,8 +7,8 @@ use openbitfun_core::service::{ remote_connect::host_stream::HostStreamHub, remote_ssh::{get_remote_workspace_manager, RemoteTerminalManager}, terminal::{ - session::{SessionStatus, TerminalSession}, - CloseSessionRequest, CreateSessionRequest, ResizeRequest, TerminalApi, WriteRequest, + session::SessionStatus, CloseSessionRequest, CreateSessionRequest, ResizeRequest, + TerminalApi, WriteRequest, }, }; use serde::de::DeserializeOwned; @@ -33,9 +33,9 @@ async fn publish_lifecycle(hub: &HostStreamHub, id: &str, event: &str, mut paylo } /// `Some(code)` once the PTY has exited; the code itself may be unknown. -fn exited_code(session: Option<&TerminalSession>) -> Option> { - match session?.status { - SessionStatus::Exited { exit_code } => Some(exit_code), +fn exited_code(status: Option<&SessionStatus>) -> Option> { + match status? { + SessionStatus::Exited { exit_code } => Some(*exit_code), _ => None, } } @@ -165,7 +165,34 @@ pub(crate) async fn create(state: &PeerHostState, args: &Value) -> Result {} Err(_) => { - publish_lifecycle(&hub, &id, TERMINAL_CLOSED_EVENT, json!({})).await; + // The SSH channel ended, so the shell is gone. The channel + // does not report an exit code. + publish_lifecycle( + &hub, + &id, + TERMINAL_EXIT_EVENT, + json!({"exit_code":Value::Null}), + ) + .await; + // The record, and its replay, outlive the channel until the + // tab is closed. + let mut removal_check = tokio::time::interval(TERMINAL_EXIT_CHECK_INTERVAL); + removal_check + .set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + if *closed.borrow() { + break; + } + tokio::select! { + _ = removal_check.tick() => { + if manager.replay_cursor(&id).await.is_none() { + publish_lifecycle(&hub, &id, TERMINAL_CLOSED_EVENT, json!({})).await; + break; + } + } + _ = closed.changed() => break, + } + } break; } } @@ -247,7 +274,7 @@ pub(crate) async fn create(state: &PeerHostState, args: &Value) -> Result { - if let Some(exit_code) = exited_code(manager.get_session(&id).await.as_ref()) { + if let Some(exit_code) = exited_code(manager.session_status(&id).await.as_ref()) { exit_published = true; publish_lifecycle(&hub, &id, TERMINAL_EXIT_EVENT, json!({"exit_code":exit_code})).await; } @@ -472,24 +499,18 @@ pub(crate) async fn execute(args: &Value) -> Result { #[cfg(test)] mod tests { use super::*; - use openbitfun_core::service::terminal::{SessionSource, ShellType}; #[test] fn exit_is_reported_only_for_an_exited_session() { - let mut session = TerminalSession::new( - "t1".into(), - "Shell".into(), - ShellType::Bash, - "/repo".into(), - 80, - 24, - SessionSource::Manual, - ); assert_eq!(exited_code(None), None); - assert_eq!(exited_code(Some(&session)), None); - session.set_exited(Some(7)); - assert_eq!(exited_code(Some(&session)), Some(Some(7))); - session.set_exited(None); - assert_eq!(exited_code(Some(&session)), Some(None)); + assert_eq!(exited_code(Some(&SessionStatus::Active)), None); + assert_eq!( + exited_code(Some(&SessionStatus::Exited { exit_code: Some(7) })), + Some(Some(7)) + ); + assert_eq!( + exited_code(Some(&SessionStatus::Exited { exit_code: None })), + Some(None) + ); } } diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index 5c7f5a24f1..6049e41c95 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -11948,7 +11948,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet .await?; } - let turn_id = format!("btw-turn-{}", request_id.trim()); + let turn_id = btw_turn_id(request_id); let mut user_message_metadata = user_message_metadata .filter(serde_json::Value::is_object) .unwrap_or_else(|| serde_json::json!({})); @@ -16361,6 +16361,12 @@ async fn new_btw_session_memory_mode_from_global_config() -> SessionMemoryMode { // Global coordinator singleton static GLOBAL_COORDINATOR: OnceLock> = OnceLock::new(); +/// The dialog turn id `start_btw_turn` assigns to a side question. Hosts that +/// track turn ownership register this id before submitting the turn. +pub fn btw_turn_id(request_id: &str) -> String { + format!("btw-turn-{}", request_id.trim()) +} + /// Get global coordinator /// /// Returns `None` if coordinator hasn't been initialized diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index f3a3dc166d..23c8b8f093 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:6c9684d5e2394817", + "digest": "fnv1a64:6af8cd66ba85f89e", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -48,7 +48,8 @@ "whole_session_copy_v1", "session_trajectory_v1", "user_question_response", - "user_question_interaction_v1" + "user_question_interaction_v1", + "terminal_cursor_replay_v1" ], "desktop": [ "model_routing_v1", @@ -116,7 +117,8 @@ "workspace_id_references_v1", "workspace_html_preview_v1", "user_question_response", - "user_question_interaction_v1" + "user_question_interaction_v1", + "terminal_cursor_replay_v1" ] }, "operations": [ @@ -2870,8 +2872,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index d577f2cec0..85a75b370f 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -100,6 +100,10 @@ pub enum PeerHostCapability { UserQuestionResponse, /// First human interaction disables the unattended question timeout. UserQuestionInteractionV1, + /// Terminal output is read as bounded `terminal_get_history` pages announced + /// on the `terminal-` host stream instead of `terminal_event` fan-out. + /// This selects a delivery path, so only a host using that path advertises it. + TerminalCursorReplayV1, } impl PeerHostCapability { @@ -145,6 +149,8 @@ impl PeerHostCapability { Self::SessionTrajectoryV1, Self::UserQuestionResponse, Self::UserQuestionInteractionV1, + // Keep last: Desktop publishes every capability before it. + Self::TerminalCursorReplayV1, ]; /// The key used in the `peer_mode_ping` `capabilities` object. @@ -190,6 +196,7 @@ impl PeerHostCapability { Self::WholeSessionCopyV1 => "whole_session_copy_v1", Self::UserQuestionResponse => "user_question_response", Self::UserQuestionInteractionV1 => "user_question_interaction_v1", + Self::TerminalCursorReplayV1 => "terminal_cursor_replay_v1", } } @@ -199,7 +206,11 @@ impl PeerHostCapability { } } -const DESKTOP_CAPABILITIES: &[PeerHostCapability] = PeerHostCapability::ALL; +/// Desktop fans out `terminal_event`, so it has everything except the cursor +/// replay path, which `ALL` keeps last. +const DESKTOP_CAPABILITIES: &[PeerHostCapability] = PeerHostCapability::ALL + .split_at(PeerHostCapability::ALL.len() - 1) + .0; /// The CLI peer host has no MiniApp runtime, WSL connection setup, host-native /// ProductControl providers, or presentation surface. @@ -228,6 +239,7 @@ const CLI_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::WorkspaceHtmlPreviewV1, PeerHostCapability::UserQuestionResponse, PeerHostCapability::UserQuestionInteractionV1, + PeerHostCapability::TerminalCursorReplayV1, ]; /// The capabilities a peer host of the given kind publishes. @@ -273,8 +285,11 @@ mod tests { } #[test] - fn desktop_advertises_a_superset_of_cli() { + fn desktop_advertises_a_superset_of_cli_except_its_delivery_path() { for capability in advertised_by(PeerHostKind::Cli) { + if *capability == PeerHostCapability::TerminalCursorReplayV1 { + continue; + } assert!( advertises(PeerHostKind::Desktop, *capability), "desktop must advertise every CLI capability: {}", @@ -283,8 +298,16 @@ mod tests { } assert_eq!( advertised_by(PeerHostKind::Desktop).len(), - PeerHostCapability::ALL.len() + PeerHostCapability::ALL.len() - 1 ); + assert!(!advertises( + PeerHostKind::Desktop, + PeerHostCapability::TerminalCursorReplayV1 + )); + assert!(advertises( + PeerHostKind::Cli, + PeerHostCapability::TerminalCursorReplayV1 + )); assert!(advertises( PeerHostKind::Desktop, PeerHostCapability::BtwInitialModelSelectionV1 diff --git a/src/crates/contracts/product-domains/src/remote_surface/mod.rs b/src/crates/contracts/product-domains/src/remote_surface/mod.rs index 5c4f478919..47c1428ea3 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/mod.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/mod.rs @@ -695,6 +695,13 @@ mod tests { } .message("terminal_list"); assert!(cli.starts_with("command 'terminal_list' is not supported on CLI peer host")); + // The Web UI asks for a host update when it sees this reason. + assert_eq!( + table::CLI_NOT_IMPLEMENTED, + HostSupport::Unsupported { + reason: "the CLI peer host has no handler for this command" + } + ); assert!(!PeerRefusal::UnknownToHost { host: PeerHostKind::Cli } diff --git a/src/crates/contracts/product-domains/src/remote_surface/table.rs b/src/crates/contracts/product-domains/src/remote_surface/table.rs index 60caeacc6f..277f492792 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -323,7 +323,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("get_frontend_update_status", LocalOnly, ControllerLocal, REFUSED), op("get_global_config_health", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_global_config_status", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("get_global_skill_settings", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), + op("get_global_skill_settings", Agnostic, Proxied, HANDLED), op("get_health_status", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("get_instruction_source_catalog", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), op("get_latest_insights", LocalOnly, ControllerLocal, REFUSED), diff --git a/src/crates/services/terminal/src/session/manager.rs b/src/crates/services/terminal/src/session/manager.rs index 5c8dbca917..29d83c963c 100644 --- a/src/crates/services/terminal/src/session/manager.rs +++ b/src/crates/services/terminal/src/session/manager.rs @@ -1443,6 +1443,15 @@ impl SessionManager { .map(|session| session.replay_history.cursor()) } + /// Lifecycle polling must not clone the retained PTY history either. + pub async fn session_status(&self, session_id: &str) -> Option { + self.sessions + .read() + .await + .get(session_id) + .map(|session| session.status.clone()) + } + pub async fn replay_page( &self, session_id: &str, diff --git a/src/web-ui/src/app/scenes/settings/pages/data/DiagnosticsSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/data/DiagnosticsSettingsPage.tsx index fb014aa6c3..e5406cc9d9 100644 --- a/src/web-ui/src/app/scenes/settings/pages/data/DiagnosticsSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/data/DiagnosticsSettingsPage.tsx @@ -8,22 +8,18 @@ import type { BackendLogLevel, RuntimeLoggingInfo } from '@/infrastructure/config/types'; -import { peerHostRefusalReason } from '@/infrastructure/peer-device/peerHostRefusal'; +import { peerHostRefusalMessage } from '@/infrastructure/peer-device/peerHostRefusal'; import { createLogger } from '@/shared/utils/logger'; import { Alert, Button, ConfirmDialog, IconButton, Input, Select, Switch, Tooltip } from '@openbitfun/ui'; import { Archive, FolderOpen } from 'lucide-react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { SettingsPage } from '../shared/SettingsPage'; +import { loggingLevelSavedMessageKey } from './loggingLevelMessage'; const loggingRuntime = createSettingsReadCache(); const log = createLogger('DiagnosticsSettingsPage'); -/** A peer host's explicit refusal says more than the generic failure copy. */ -function withHostReason(failure: string, error: unknown): string { - const reason = peerHostRefusalReason(error); - return reason ? `${failure}: ${reason}` : failure; -} function LoggingSection() { const { t } = useTranslation('settings/application'); @@ -103,7 +99,10 @@ function LoggingSection() { const info = await configAPI.getRuntimeLoggingInfo(); setRuntimeInfo(info); - showMessage('success', t('logging.messages.levelUpdated')); + showMessage( + info.effectiveLevel === nextLevel ? 'success' : 'info', + t(loggingLevelSavedMessageKey(info.effectiveLevel, nextLevel), { level: info.effectiveLevel }), + ); } catch (error) { setConfigLevel(previousLevel); log.error('Failed to update logging level', { nextLevel, error }); @@ -148,7 +147,7 @@ function LoggingSection() { await workspaceAPI.revealInExplorer(folder); } catch (error) { log.error('Failed to open log folder', { folder, error }); - showMessage('error', withHostReason(t('logging.messages.openFailed'), error)); + showMessage('error', peerHostRefusalMessage(error, t) ?? t('logging.messages.openFailed')); } finally { setOpeningFolder(false); } @@ -163,7 +162,7 @@ function LoggingSection() { await workspaceAPI.revealInExplorer(result.bundlePath); } catch (error) { log.error('Failed to export diagnostics bundle', { error }); - showMessage('error', withHostReason(t('logging.messages.diagnosticsExportFailed'), error)); + showMessage('error', peerHostRefusalMessage(error, t) ?? t('logging.messages.diagnosticsExportFailed')); } finally { setExportingDiagnostics(false); } diff --git a/src/web-ui/src/app/scenes/settings/pages/data/loggingLevelMessage.test.ts b/src/web-ui/src/app/scenes/settings/pages/data/loggingLevelMessage.test.ts new file mode 100644 index 0000000000..0ec149438c --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/data/loggingLevelMessage.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from 'vitest'; +import { loggingLevelSavedMessageKey } from './loggingLevelMessage'; + +describe('loggingLevelSavedMessageKey', () => { + it('reports an applied level as updated', () => { + expect(loggingLevelSavedMessageKey('info', 'info')).toBe('logging.messages.levelUpdated'); + }); + + it('does not claim a level the host has not applied', () => { + expect(loggingLevelSavedMessageKey('debug', 'info')).toBe('logging.messages.levelSavedNotApplied'); + }); +}); diff --git a/src/web-ui/src/app/scenes/settings/pages/data/loggingLevelMessage.ts b/src/web-ui/src/app/scenes/settings/pages/data/loggingLevelMessage.ts new file mode 100644 index 0000000000..89cbf35888 --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/data/loggingLevelMessage.ts @@ -0,0 +1,6 @@ +/** A host whose level is fixed at launch (a CLI host) saves the setting but keeps reporting its own level. */ +export function loggingLevelSavedMessageKey(effectiveLevel: string, requestedLevel: string): string { + return effectiveLevel === requestedLevel + ? 'logging.messages.levelUpdated' + : 'logging.messages.levelSavedNotApplied'; +} diff --git a/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.test.tsx b/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.test.tsx index 15ec8b03cf..631807eabb 100644 --- a/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.test.tsx +++ b/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.test.tsx @@ -108,6 +108,41 @@ describe('useInstalledSkills', () => { vi.useRealTimers(); }); + describe('on a CLI peer host', () => { + const skills = [{ key: 'user::openbitfun::good', name: 'good', sourceId: 'openbitfun', sourceSlot: 'openbitfun', level: 'user', path: '/skills/good' }]; + + it('lists Skills read-only when the host reports no direct management', async () => { + getSkillConfigsMock.mockResolvedValue(skills); + getGlobalSkillSettingsMock.mockResolvedValue({ + directSkillManagementVersion: 0, + globallyDisabledUserSkillKeys: [], + globallyDisabledProjectSkillKeys: [], + }); + await act(async () => root.render()); + expect(currentInstalled?.skills).toEqual(skills); + expect(currentInstalled?.error).toBeNull(); + expect(currentInstalled?.canToggleSkill(skills[0] as never)).toBe(false); + }); + + it('still lists Skills when an older host refuses the availability settings', async () => { + getSkillConfigsMock.mockResolvedValue(skills); + getGlobalSkillSettingsMock.mockRejectedValue(new Error( + "command 'get_global_skill_settings' is not supported on CLI peer host: the CLI peer host has no handler for this command", + )); + await act(async () => root.render()); + expect(currentInstalled?.skills).toEqual(skills); + expect(currentInstalled?.error).toBeNull(); + expect(currentInstalled?.canToggleSkill(skills[0] as never)).toBe(false); + }); + + it('keeps reporting other availability failures', async () => { + getSkillConfigsMock.mockResolvedValue(skills); + getGlobalSkillSettingsMock.mockRejectedValue(new Error('config is unreadable')); + await act(async () => root.render()); + expect(currentInstalled?.error).not.toBeNull(); + }); + }); + it('preserves available skills alongside discovery failures', async () => { const skills = [{ key: 'user::openbitfun::good', name: 'good', sourceId: 'openbitfun', level: 'user', path: '/skills/good' }]; getSkillConfigsMock.mockResolvedValue(skills); diff --git a/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.ts b/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.ts index 47fb2ea435..8113e1ee86 100644 --- a/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.ts +++ b/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.ts @@ -1,3 +1,5 @@ +import type { GlobalSkillSettings } from '@/infrastructure/config/types'; +import { classifyPeerHostRefusal } from '@/infrastructure/peer-device/peerHostRefusal'; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { open } from '@tauri-apps/plugin-dialog'; import { useTranslation } from 'react-i18next'; @@ -53,6 +55,8 @@ export function useInstalledSkills({ const [loadedDiagnosticsAvailable, setDiagnosticsAvailable] = useState(true); const [globallyDisabledSkillKeys, setGloballyDisabledSkillKeys] = useState>(new Set()); const [directManagementSupported, setDirectManagementSupported] = useState(false); + /** Version 0: the host lists Skills but refuses every availability change. */ + const [skillSettingsReadOnly, setSkillSettingsReadOnly] = useState(false); const [savingGlobalSkillKey, setSavingGlobalSkillKey] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -107,7 +111,12 @@ export function useInstalledSkills({ forceRefresh, workspaceId: workspace?.id, }), - configAPI.getGlobalSkillSettings(isRemoteWorkspace ? undefined : workspace?.id), + configAPI.getGlobalSkillSettings(isRemoteWorkspace ? undefined : workspace?.id).catch((error: unknown): GlobalSkillSettings => { + // Availability settings are optional here: a host that refuses them can + // still list its Skills, only without direct management. + if (!classifyPeerHostRefusal(error)) throw error; + return { directSkillManagementVersion: 0, globallyDisabledUserSkillKeys: [], globallyDisabledProjectSkillKeys: [] }; + }), ]); if (requestId !== loadRequestIdRef.current || !capabilityIsCurrent(capabilityEpoch)) { return; @@ -117,6 +126,7 @@ export function useInstalledSkills({ setDiagnostics(list.diagnostics); setDiagnosticsAvailable(list.diagnosticsAvailable); setDirectManagementSupported(!isRemoteWorkspace && globalSettings.directSkillManagementVersion === 1); + setSkillSettingsReadOnly(globalSettings.directSkillManagementVersion === 0); setGloballyDisabledSkillKeys(new Set([ ...globalSettings.globallyDisabledUserSkillKeys, ...(!isRemoteWorkspace ? globalSettings.globallyDisabledProjectSkillKeys ?? [] : []), @@ -372,8 +382,9 @@ export function useInstalledSkills({ }, [capabilityIsCurrent, currentCapabilityEpoch, loadSkills, notification, t, workspace?.id]); const canToggleSkill = useCallback((skill: SkillInfo) => ( - directManagementSupported || (skill.level === 'user' && isOpenBitFunManagedSkill(skill)) - ), [directManagementSupported]); + !skillSettingsReadOnly + && (directManagementSupported || (skill.level === 'user' && isOpenBitFunManagedSkill(skill))) + ), [directManagementSupported, skillSettingsReadOnly]); const handleGlobalSkillToggle = useCallback(async (skill: SkillInfo, enabled: boolean) => { const capabilityEpoch = currentCapabilityEpoch(); diff --git a/src/web-ui/src/flow_chat/components/ChatInput.tsx b/src/web-ui/src/flow_chat/components/ChatInput.tsx index b4d6a954c2..79816340a8 100644 --- a/src/web-ui/src/flow_chat/components/ChatInput.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInput.tsx @@ -95,7 +95,7 @@ import { successfulRetryCleanupTarget, } from './chatInputDraftRecovery'; import { startBtwThread } from '../services/BtwThreadService'; -import { peerHostRefusalReason } from '@/infrastructure/peer-device/peerHostRefusal'; +import { peerHostRefusalMessage } from '@/infrastructure/peer-device/peerHostRefusal'; import { buildImagePayload } from '../utils/imagePayload'; import { canRestoreQueuedMessageToComposer, @@ -3715,7 +3715,7 @@ export const ChatInput: React.FC = ({ selectTargetSession(childSessionId); } catch (e) { log.error('Failed to start /btw thread', { e }); - const refusal = peerHostRefusalReason(e); + const refusal = peerHostRefusalMessage(e, t); if (refusal) notificationService.error(refusal); replacePendingLargePastes(originalPendingLargePastes); dispatchInput({ type: 'SET_VALUE', payload: originalMessage }); diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.test.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.test.ts index 84844b61e7..5d99b71297 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.test.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.test.ts @@ -100,8 +100,11 @@ describe('remote surface generated bindings', () => { expect([...PEER_HOST_ADVERTISED_CAPABILITIES.desktop]).toEqual(registry.capabilities.desktop); expect([...PEER_HOST_ADVERTISED_CAPABILITIES.cli]).toEqual(registry.capabilities.cli); for (const capability of PEER_HOST_ADVERTISED_CAPABILITIES.cli) { + // A delivery path, not a feature: Desktop fans out `terminal_event` instead. + if (capability === 'terminal_cursor_replay_v1') continue; expect(PEER_HOST_ADVERTISED_CAPABILITIES.desktop, capability).toContain(capability); } + expect(PEER_HOST_ADVERTISED_CAPABILITIES.desktop).not.toContain('terminal_cursor_replay_v1'); expect(PEER_HOST_ADVERTISED_CAPABILITIES.cli).not.toContain('miniapp_agent_context_files_v1'); expect(PEER_HOST_ADVERTISED_CAPABILITIES.desktop).toContain('cancel_tool'); expect(PEER_HOST_ADVERTISED_CAPABILITIES.cli).toContain('cancel_tool'); diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index 9c8cf1d783..12c694fb5f 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:6c9684d5e2394817" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:6af8cd66ba85f89e" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -210,6 +210,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "session_trajectory_v1", "user_question_response", "user_question_interaction_v1", + "terminal_cursor_replay_v1", ] as const; export type PeerHostCapabilityId = (typeof PEER_HOST_CAPABILITY_IDS)[number]; @@ -285,6 +286,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "workspace_html_preview_v1", "user_question_response", "user_question_interaction_v1", + "terminal_cursor_replay_v1", ], }; diff --git a/src/web-ui/src/infrastructure/config/components/AcpAgentsConfig.tsx b/src/web-ui/src/infrastructure/config/components/AcpAgentsConfig.tsx index 6e1219f9ad..d937fb9f5e 100644 --- a/src/web-ui/src/infrastructure/config/components/AcpAgentsConfig.tsx +++ b/src/web-ui/src/infrastructure/config/components/AcpAgentsConfig.tsx @@ -18,7 +18,7 @@ import { OverflowText, } from '@openbitfun/ui'; import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; import { useI18n } from '@/infrastructure/i18n'; -import { peerHostRefusalReason } from '@/infrastructure/peer-device/peerHostRefusal'; +import { peerHostRefusalMessage } from '@/infrastructure/peer-device/peerHostRefusal'; import { CircleAlert, EyeOff, FileJson, Save, Server } from 'lucide-react'; import { ConfigPageContent, @@ -777,7 +777,7 @@ const AcpAgentsConfig = forwardRef( log.error('Failed to load ACP agent config', error); if (showLoading) { setLoadFailed(true); - setLoadRefusal(peerHostRefusalReason(error)); + setLoadRefusal(peerHostRefusalMessage(error, t)); } else { notifyError(error instanceof Error ? error.message : String(error), { title: t('notifications.loadFailed'), diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 7080bd59d7..333078e64b 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -45,6 +45,8 @@ export interface PeerHostCapabilities { readonly inlineImageAttachmentsV1?: boolean; readonly btwInitialModelSelectionV1?: boolean; readonly btwModelPoolSelectionV1?: boolean; + /** Terminal output arrives as replay pages announced on the host stream. */ + readonly terminalCursorReplayV1?: boolean; readonly controlConversationV1?: boolean; readonly controlConversationResetV1?: boolean; readonly targetedSessionRollback: boolean; @@ -190,6 +192,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = { inlineImageAttachmentsV1: false, btwInitialModelSelectionV1: false, btwModelPoolSelectionV1: false, + terminalCursorReplayV1: false, controlConversationV1: false, controlConversationResetV1: false, targetedSessionRollback: false, @@ -551,6 +554,7 @@ export class PeerConnectionManager { inlineImageAttachmentsV1: caps?.inline_image_attachments_v1 === true, btwInitialModelSelectionV1: caps?.btw_initial_model_selection_v1 === true, btwModelPoolSelectionV1: caps?.btw_model_pool_selection_v1 === true, + terminalCursorReplayV1: caps?.terminal_cursor_replay_v1 === true, controlConversationV1: caps?.control_conversation_v1 === true, controlConversationResetV1: caps?.control_conversation_reset_v1 === true, targetedSessionRollback: caps?.targeted_session_rollback === true, diff --git a/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.test.ts b/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.test.ts index a8c4bb1e19..4749c1ad0c 100644 --- a/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.test.ts +++ b/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.test.ts @@ -6,6 +6,7 @@ import { canQueryToolCatalogOnSurface, canSubmitUserQuestionsOnSurface, canQuerySubscriptionQuotaOnSurface, + usesTerminalCursorReplay, } from './peerCapabilityResolution'; import type { PeerHostCapabilities } from './PeerConnectionManager'; @@ -130,3 +131,21 @@ it('requires advertised Grok quota support from a peer', () => { expect(canQueryGrokQuotaOnSurface(true, { subscriptionQuotaV1: true } as PeerHostCapabilities)).toBe(false); expect(canQueryGrokQuotaOnSurface(true, { grokQuotaV1: true } as PeerHostCapabilities)).toBe(true); }); + +describe('usesTerminalCursorReplay', () => { + const capabilities = (fields: Record) => fields as unknown as PeerHostCapabilities; + + it('follows the typed capability', () => { + expect(usesTerminalCursorReplay(capabilities({ terminalCursorReplayV1: true, hostKind: 'cli' }))).toBe(true); + }); + + it('resolves an older host through its kind', () => { + expect(usesTerminalCursorReplay(capabilities({ terminalCursorReplayV1: false, hostKind: 'cli' }))).toBe(true); + expect(usesTerminalCursorReplay(capabilities({ terminalCursorReplayV1: false, hostKind: 'desktop' }))).toBe(false); + }); + + it('stays on terminal_event while the host is unknown or local', () => { + expect(usesTerminalCursorReplay(capabilities({ hostKind: null }))).toBe(false); + expect(usesTerminalCursorReplay(undefined)).toBe(false); + }); +}); diff --git a/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.ts b/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.ts index 221b809568..a47225f922 100644 --- a/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.ts +++ b/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.ts @@ -1,5 +1,14 @@ import type { PeerHostCapabilities } from './PeerConnectionManager'; +/** + * Whether terminal output must be read from replay pages. A missing key means + * an older host, and every CLI host already publishes cursor hints while no + * Desktop host does, so older hosts of both kinds stay on their working path. + */ +export function usesTerminalCursorReplay(capabilities: PeerHostCapabilities | null | undefined): boolean { + return capabilities?.terminalCursorReplayV1 === true || capabilities?.hostKind === 'cli'; +} + /** Unknown peers use the URL; older Desktop hosts already support PR details. */ export function canViewPullRequestsOnSurface( peerActive: boolean, diff --git a/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.test.ts b/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.test.ts index bb97a336f3..7ebe58d36f 100644 --- a/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.test.ts +++ b/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.test.ts @@ -1,25 +1,39 @@ import { describe, expect, it } from 'vitest'; -import { peerHostRefusalReason } from './peerHostRefusal'; -describe('peerHostRefusalReason', () => { - it('extracts the reason a host gave', () => { - expect(peerHostRefusalReason(new Error( +import { classifyPeerHostRefusal, peerHostRefusalMessage } from './peerHostRefusal'; + +const t = (key: string, options?: Record) => + options ? `${options.message} [${options.detail}]` : key; + +describe('peerHostRefusal', () => { + it('keeps the reason a host gave as detail', () => { + expect(classifyPeerHostRefusal(new Error( "command 'export_diagnostics_bundle' is not supported on CLI peer host: the CLI peer host does not export diagnostics bundles", - ))).toBe('The CLI peer host does not export diagnostics bundles'); + ))).toEqual({ kind: 'unavailable', detail: 'the CLI peer host does not export diagnostics bundles' }); + }); + + it('asks for an update when the host version has no handler yet', () => { + expect(classifyPeerHostRefusal( + "command 'btw_ask_stream' is not supported on CLI peer host: the CLI peer host has no handler for this command", + )?.kind).toBe('updateRequired'); + expect(classifyPeerHostRefusal( + "command 'x' is unknown to this OpenBitFun CLI peer host version; upgrade the peer host", + )?.kind).toBe('updateRequired'); }); it('keeps the whole message when an older host gave no reason', () => { - expect(peerHostRefusalReason("command 'x' is not supported on CLI peer host")) - .toBe("Command 'x' is not supported on CLI peer host"); + expect(classifyPeerHostRefusal("command 'x' is not supported on CLI peer host")).toEqual({ + kind: 'unavailable', detail: "command 'x' is not supported on CLI peer host", + }); }); - it('recognizes a command the host version does not know', () => { - const message = "command 'x' is unknown to this OpenBitFun CLI peer host version; upgrade the peer host"; - expect(peerHostRefusalReason(new Error(message))).toBe(message); + it('leads with localized copy and leaves the host text as detail', () => { + expect(peerHostRefusalMessage("command 'x' is not supported on CLI peer host: no ACP host", t)) + .toBe('common:peerHost.unavailable [no ACP host]'); }); it('leaves ordinary failures to the caller', () => { - expect(peerHostRefusalReason(new Error('disk full'))).toBeNull(); - expect(peerHostRefusalReason(undefined)).toBeNull(); + expect(classifyPeerHostRefusal(new Error('disk full'))).toBeNull(); + expect(peerHostRefusalMessage(undefined, t)).toBeNull(); }); }); diff --git a/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.ts b/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.ts index 502e2f4018..b1c63f9867 100644 --- a/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.ts +++ b/src/web-ui/src/infrastructure/peer-device/peerHostRefusal.ts @@ -1,18 +1,35 @@ -/** - * The reason a peer host gave for refusing a command, or `null` when the error - * is not a host capability refusal. `PeerRefusal::message` keeps these prefixes - * byte-stable, so settings pages can show the reason instead of a generic - * failure without knowing every command a host lacks. - */ +export interface PeerHostRefusal { + /** `unavailable`: this host kind does not offer it. `updateRequired`: a newer host may. */ + kind: 'unavailable' | 'updateRequired'; + /** The host's own English explanation, for use as secondary detail only. */ + detail: string; +} + +// `PeerRefusal::message` keeps these prefixes byte-stable for frontend matching. const REFUSAL = /command '[^']+' is not supported on \w+ peer host(?:: (.+))?$/s; const UNKNOWN_TO_HOST = /command '[^']+' is unknown to this OpenBitFun \w+ peer host version/; +/** Registry reason `CLI_NOT_IMPLEMENTED`: this host version has no handler yet. */ +const NOT_YET_IMPLEMENTED = 'has no handler for this command'; -export function peerHostRefusalReason(error: unknown): string | null { +export function classifyPeerHostRefusal(error: unknown): PeerHostRefusal | null { const message = error instanceof Error ? error.message : typeof error === 'string' ? error : ''; + if (UNKNOWN_TO_HOST.test(message)) return { kind: 'updateRequired', detail: message }; const refusal = REFUSAL.exec(message); - if (refusal) { - const reason = refusal[1] ?? message.slice(refusal.index); - return reason.charAt(0).toUpperCase() + reason.slice(1); - } - return UNKNOWN_TO_HOST.test(message) ? message : null; + if (!refusal) return null; + const detail = refusal[1] ?? message.slice(refusal.index); + return { kind: detail.includes(NOT_YET_IMPLEMENTED) ? 'updateRequired' : 'unavailable', detail }; +} + +type Translate = (key: string, options?: Record) => string; + +/** Localized copy for a peer host refusal, or `null` when `error` is something else. */ +export function peerHostRefusalMessage(error: unknown, t: Translate): string | null { + const refusal = classifyPeerHostRefusal(error); + if (!refusal) return null; + return t('common:peerHost.withDetail', { + message: t(refusal.kind === 'updateRequired' + ? 'common:peerHost.updateRequired' + : 'common:peerHost.unavailable'), + detail: refusal.detail, + }); } diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index 788c74fb83..946a447f3f 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -2336,5 +2336,10 @@ "createProject": "Create project", "assistantError": "Unable to create the assistant. Please try again.", "back": "Back to selection" + }, + "peerHost": { + "unavailable": "This feature is not available on that device.", + "updateRequired": "The OpenBitFun version on that device does not support this feature. Try updating OpenBitFun on that device.", + "withDetail": "{{message}} ({{detail}})" } } diff --git a/src/web-ui/src/locales/en-US/settings/application.json b/src/web-ui/src/locales/en-US/settings/application.json index d1b65fb73e..d10d1c9cce 100644 --- a/src/web-ui/src/locales/en-US/settings/application.json +++ b/src/web-ui/src/locales/en-US/settings/application.json @@ -207,6 +207,7 @@ "loadFailed": "Failed to load logging configuration", "saveFailed": "Failed to save logging level", "levelUpdated": "Logging level updated", + "levelSavedNotApplied": "Logging level saved, but that device is still logging at {{level}}.", "sensitiveDiagnosticsUpdated": "Sensitive diagnostic logging preference updated", "refreshed": "Runtime status refreshed", "openedFolder": "Log folder opened", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index 6d98f5594b..db7df14dfb 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -2336,5 +2336,10 @@ "createProject": "创建工程", "assistantError": "无法创建助理,请稍后重试。", "back": "返回选择" + }, + "peerHost": { + "unavailable": "此功能在该设备上不可用。", + "updateRequired": "该设备上的 OpenBitFun 版本不支持此功能。请尝试在该设备上更新 OpenBitFun。", + "withDetail": "{{message}}({{detail}})" } } diff --git a/src/web-ui/src/locales/zh-CN/settings/application.json b/src/web-ui/src/locales/zh-CN/settings/application.json index b6fe8652f3..afc5150642 100644 --- a/src/web-ui/src/locales/zh-CN/settings/application.json +++ b/src/web-ui/src/locales/zh-CN/settings/application.json @@ -207,6 +207,7 @@ "loadFailed": "加载日志配置失败", "saveFailed": "保存日志级别失败", "levelUpdated": "日志级别已更新", + "levelSavedNotApplied": "日志级别已保存,但该设备仍按 {{level}} 级别记录日志。", "sensitiveDiagnosticsUpdated": "敏感调试信息日志偏好已更新", "refreshed": "运行时状态已刷新", "openedFolder": "日志文件夹已打开", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index efdd80cd52..a290fe9365 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -2336,5 +2336,10 @@ "createProject": "建立專案", "assistantError": "無法建立助理,請稍後重試。", "back": "返回選擇" + }, + "peerHost": { + "unavailable": "此功能在該裝置上無法使用。", + "updateRequired": "該裝置上的 OpenBitFun 版本不支援此功能。請嘗試在該裝置上更新 OpenBitFun。", + "withDetail": "{{message}}({{detail}})" } } diff --git a/src/web-ui/src/locales/zh-TW/settings/application.json b/src/web-ui/src/locales/zh-TW/settings/application.json index 8eb5f0b404..58d267e70a 100644 --- a/src/web-ui/src/locales/zh-TW/settings/application.json +++ b/src/web-ui/src/locales/zh-TW/settings/application.json @@ -193,6 +193,7 @@ "loadFailed": "載入日誌設定失敗", "saveFailed": "儲存日誌級別失敗", "levelUpdated": "日誌級別已更新", + "levelSavedNotApplied": "日誌級別已儲存,但該裝置仍按 {{level}} 級別記錄日誌。", "sensitiveDiagnosticsUpdated": "敏感除錯資訊日誌偏好已更新", "refreshed": "運行時狀態已重新整理", "openedFolder": "日誌資料夾已開啟", diff --git a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts index 5ef31e135c..707b464b16 100644 --- a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts +++ b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts @@ -73,7 +73,8 @@ describe('PeerTerminalReplay', () => { mocks.subscribeSession.mockReset().mockResolvedValue('subscription-1'); mocks.unsubscribeSession.mockReset().mockResolvedValue(undefined); mocks.current = true; - replay = new PeerTerminalReplay('t1', 10, event => events.push(event)); + replay = new PeerTerminalReplay('t1', event => events.push(event)); + replay.follow(10); }); afterEach(() => { @@ -150,17 +151,31 @@ describe('PeerTerminalReplay', () => { expect(events.at(-1)?.type).toBe('SessionDestroyed'); }); - it('reports a vanished session from a host without lifecycle events', async () => { - mocks.invoke.mockRejectedValueOnce(new Error('Terminal is unavailable')); + it('reports a vanished session from the session list, not the error text', async () => { + mocks.invoke.mockRejectedValueOnce(new Error('any host wording')).mockResolvedValueOnce([{ id: 'other' }]); replay.start(); ready(); await flush(); + await flush(); + expect(mocks.invoke).toHaveBeenLastCalledWith('terminal_list'); expect(events).toEqual([{ type: 'SessionDestroyed', payload: { session_id: 't1' } }]); }); + it('keeps a listed session after a failed read', async () => { + vi.useFakeTimers(); + mocks.invoke.mockRejectedValueOnce(new Error('relay timeout')).mockResolvedValueOnce([{ id: 't1' }]); + replay.start(); + ready(); + await vi.advanceTimersByTimeAsync(0); + expect(events).toEqual([]); + }); + it('retries a failed read from the same offset without losing output', async () => { vi.useFakeTimers(); - mocks.invoke.mockRejectedValueOnce(new Error('relay timeout')).mockResolvedValueOnce(page('late', 14)); + mocks.invoke + .mockRejectedValueOnce(new Error('relay timeout')) + .mockResolvedValueOnce([{ id: 't1' }]) + .mockResolvedValueOnce(page('late', 14)); replay.start(); ready(); await vi.advanceTimersByTimeAsync(0); @@ -199,4 +214,62 @@ describe('PeerTerminalReplay', () => { expect(mocks.unsubscribeSession).toHaveBeenCalledWith('subscription-1'); expect(mocks.listeners.get('terminal-output')?.size).toBe(0); }); + + describe('without a mounted view', () => { + let tracked: PeerTerminalReplay; + + beforeEach(() => { + tracked = new PeerTerminalReplay('t1', event => events.push(event)); + }); + + afterEach(() => tracked.close()); + + it('reports the lifecycle without reading output', async () => { + tracked.start(); + ready(); + emit('terminal-output', { terminal_id: 't1', cursor: 50 }); + await flush(); + expect(mocks.invoke).not.toHaveBeenCalled(); + + emit('terminal-exit', { terminal_id: 't1', exit_code: 0 }); + expect(events).toEqual([{ type: 'Exit', payload: { session_id: 't1', exit_code: 0 } }]); + }); + + it('starts reading when a view follows and stops when it leaves', async () => { + mocks.invoke.mockResolvedValue(page('x', 21)); + tracked.start(); + ready(); + tracked.follow(20); + await flush(); + expect(mocks.invoke).toHaveBeenLastCalledWith('terminal_get_history', { sessionId: 't1', afterOffset: 20 }); + + mocks.invoke.mockClear(); + tracked.unfollow(); + emit('terminal-output', { terminal_id: 't1', cursor: 30 }); + await flush(); + expect(mocks.invoke).not.toHaveBeenCalled(); + }); + + it('drops a page read for a view that left', async () => { + let finish!: (value: unknown) => void; + mocks.invoke.mockReturnValueOnce(new Promise(resolve => { finish = resolve; })); + tracked.start(); + tracked.follow(20); + ready(); + await flush(); + tracked.unfollow(); + finish(page('stale', 25)); + await flush(); + expect(events).toEqual([]); + }); + + it('shows a stream failure to the view that arrives later', async () => { + mocks.subscribeSession.mockRejectedValueOnce(new Error('older OpenBitFun version')); + tracked.start(); + await flush(); + expect(events).toEqual([]); + tracked.follow(0); + expect(events).toEqual([{ type: 'Error', payload: { session_id: 't1', message: 'older OpenBitFun version' } }]); + }); + }); }); diff --git a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts index c137b855e3..30cb4be82e 100644 --- a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts +++ b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts @@ -6,7 +6,6 @@ import { createLogger } from '@/shared/utils/logger'; const log = createLogger('PeerTerminalReplay'); const MAX_RETRY_DELAY_MS = 15_000; -const TERMINAL_UNAVAILABLE = 'Terminal is unavailable'; /** ESC c: output before this point left the host's bounded replay log. */ const TERMINAL_RESET = '\x1bc'; @@ -24,13 +23,14 @@ interface TerminalReplayPage { } /** - * Live output of one PTY on a CLI peer host. - * - * A CLI host publishes coalesced cursor hints on the `terminal-` host stream + * One PTY on a host that publishes cursor hints on its `terminal-` stream * instead of fanning out raw output, so a slow controller costs the host nothing - * and cannot lose bytes silently. This reads the bounded replay pages those - * hints announce. Reconnects and missed hints heal themselves, because every - * read continues from the offset this client last applied. + * and cannot lose bytes silently. + * + * Attached, it always reports the PTY's lifecycle, which a tab without a mounted + * view needs. While following, it also reads the bounded replay pages the hints + * announce. Reconnects and missed hints heal themselves, because every read + * continues from the offset this client last applied. */ export class PeerTerminalReplay { private readonly scope = getActiveSurfaceScope(); @@ -39,15 +39,19 @@ export class PeerTerminalReplay { private subscriptionId: string | null = null; private closed = false; private caughtUp = false; + /** `null` while no view is rendering output, so nothing is read. */ + private offset: number | null = null; + /** Fences a read in flight across a follow change. */ + private followEpoch = 0; private draining = false; private dirty = false; private pendingLifecycle: PeerTerminalRawEvent | null = null; + private streamFailure: string | null = null; private retryDelay = 0; private retryTimer: ReturnType | null = null; constructor( private readonly sessionId: string, - private offset: number, private readonly deliver: (event: PeerTerminalRawEvent) => void, ) { this.streamId = `terminal-${sessionId}`; @@ -90,12 +94,37 @@ export class PeerTerminalReplay { ); } + isFollowing(): boolean { + return this.offset !== null; + } + + /** Render output from `offset` on; everything before it is already on screen. */ + follow(offset: number): void { + this.offset = offset; + this.followEpoch += 1; + if (this.streamFailure) { + // Nobody could see this while no view was mounted. + this.deliver({ type: 'Error', payload: { session_id: this.sessionId, message: this.streamFailure } }); + return; + } + if (this.caughtUp) this.requestRead(); + } + + /** The last view left: stop reading output and keep reporting the lifecycle. */ + unfollow(): void { + if (this.offset === null) return; + this.offset = null; + this.followEpoch += 1; + this.dirty = false; + this.clearRetry(); + this.deliverPendingLifecycle(); + } + close(): void { if (this.closed) return; this.closed = true; this.listeners.splice(0).forEach(unlisten => unlisten()); - if (this.retryTimer !== null) clearTimeout(this.retryTimer); - this.retryTimer = null; + this.clearRetry(); if (this.subscriptionId) void this.release(this.subscriptionId); this.subscriptionId = null; } @@ -106,6 +135,12 @@ export class PeerTerminalReplay { }); } + private clearRetry(): void { + if (this.retryTimer !== null) clearTimeout(this.retryTimer); + this.retryTimer = null; + this.retryDelay = 0; + } + private isActive(): boolean { return !this.closed && this.scope.isCurrent(); } @@ -113,57 +148,82 @@ export class PeerTerminalReplay { private fail(message: string): void { if (!this.isActive()) return; log.error('Terminal stream unavailable', { sessionId: this.sessionId, message }); - this.deliver({ type: 'Error', payload: { session_id: this.sessionId, message } }); + this.streamFailure = message; + if (this.isFollowing()) { + this.deliver({ type: 'Error', payload: { session_id: this.sessionId, message } }); + } } /** The exit must not overtake output that is already in the replay log. */ private finishAfterDrain(event: PeerTerminalRawEvent): void { // A close supersedes an exit that is still waiting for its output. this.pendingLifecycle = event; - if (this.caughtUp) this.requestRead(); + if (this.isFollowing() && this.caughtUp) this.requestRead(); + else if (!this.isFollowing()) this.deliverPendingLifecycle(); + } + + private deliverPendingLifecycle(): void { + const lifecycle = this.pendingLifecycle; + if (!lifecycle || !this.isActive()) return; + this.pendingLifecycle = null; + this.deliver(lifecycle); } private requestRead(): void { + if (!this.isFollowing()) { + this.deliverPendingLifecycle(); + return; + } this.dirty = true; void this.drain(); } private async drain(): Promise { - if (this.draining || !this.isActive()) return; + if (this.draining || !this.isActive() || this.offset === null) return; this.draining = true; + const epoch = this.followEpoch; try { - while (this.dirty && this.isActive()) { + while (this.dirty && this.isActive() && this.offset !== null) { this.dirty = false; + const after: number = this.offset; const page = await api.invoke('terminal_get_history', { sessionId: this.sessionId, - afterOffset: this.offset, + afterOffset: after, }); if (!this.isActive()) return; + if (epoch !== this.followEpoch) { + // A follow change owns the offset now; its own read will start next. + this.dirty = this.isFollowing(); + break; + } const data = page.truncated ? `${TERMINAL_RESET}${page.data}` : page.data; if (data) this.deliver({ type: 'Data', payload: { session_id: this.sessionId, data } }); - const advanced = page.nextOffset > this.offset; this.offset = page.nextOffset; - if (advanced && page.nextOffset < page.cursor) this.dirty = true; + if (page.nextOffset > after && page.nextOffset < page.cursor) this.dirty = true; } - this.retryDelay = 0; - const lifecycle = this.pendingLifecycle; - if (lifecycle && this.isActive()) { - this.pendingLifecycle = null; - this.deliver(lifecycle); + if (!this.dirty) { + this.retryDelay = 0; + this.deliverPendingLifecycle(); } } catch (error) { - if (!this.isActive()) return; - const message = error instanceof Error ? error.message : String(error); - if (message.includes(TERMINAL_UNAVAILABLE)) { - // The session is gone, and a host without lifecycle events cannot say so. - this.deliver({ type: 'SessionDestroyed', payload: { session_id: this.sessionId } }); - return; - } - log.warn('Failed to read terminal output', { sessionId: this.sessionId, message }); - this.scheduleRetry(); + await this.recoverFromReadFailure(error); } finally { this.draining = false; + if (this.dirty && epoch !== this.followEpoch) void this.drain(); + } + } + + /** The session list is the authority on whether a failed read means it is gone. */ + private async recoverFromReadFailure(error: unknown): Promise { + if (!this.isActive()) return; + log.warn('Failed to read terminal output', { sessionId: this.sessionId, error }); + const sessions = await api.invoke>('terminal_list').catch(() => null); + if (!this.isActive()) return; + if (sessions && !sessions.some(session => session.id === this.sessionId)) { + this.deliver({ type: 'SessionDestroyed', payload: { session_id: this.sessionId } }); + return; } + if (this.isFollowing()) this.scheduleRetry(); } private scheduleRetry(): void { diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts index 4ee26afa32..4f067c1a62 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts @@ -13,20 +13,39 @@ vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ }, })); -const hostKindMock = vi.hoisted(() => ({ current: null as string | null })); +const hostMock = vi.hoisted(() => ({ + capabilities: null as Record | null, + listeners: new Set<() => void>(), +})); const replayMock = vi.hoisted(() => ({ - created: [] as Array<{ sessionId: string; offset: number; deliver: (event: unknown) => void; start: ReturnType; close: ReturnType }>, + created: [] as Array<{ + sessionId: string; + deliver: (event: unknown) => void; + start: ReturnType; + close: ReturnType; + follow: ReturnType; + unfollow: ReturnType; + isFollowing: () => boolean; + }>, })); vi.mock('@/infrastructure/peer-device/PeerConnectionManager', () => ({ peerConnectionManager: { - get: () => ({ getState: () => ({ capabilities: { hostKind: hostKindMock.current } }) }), + get: () => ({ getState: () => ({ capabilities: hostMock.capabilities }) }), + subscribe: (listener: () => void) => { + hostMock.listeners.add(listener); + return () => hostMock.listeners.delete(listener); + }, }, })); vi.mock('./PeerTerminalReplay', () => ({ PeerTerminalReplay: class { + following = false; start = vi.fn(); close = vi.fn(); - constructor(public sessionId: string, public offset: number, public deliver: (event: unknown) => void) { + follow = vi.fn(() => { this.following = true; }); + unfollow = vi.fn(() => { this.following = false; }); + isFollowing = () => this.following; + constructor(public sessionId: string, public deliver: (event: unknown) => void) { replayMock.created.push(this); } }, @@ -59,7 +78,8 @@ describe('TerminalService device surface switching', () => { listenMock.mockReset(); listenMock.mockReturnValue(() => {}); resetDeviceSurfaceForTest(); - hostKindMock.current = null; + hostMock.capabilities = null; + hostMock.listeners.clear(); replayMock.created.length = 0; }); @@ -122,28 +142,56 @@ describe('TerminalService device surface switching', () => { expect(invokeMock).not.toHaveBeenCalled(); }); - describe('CLI peer host output', () => { - async function connectToCliHost(): Promise { - hostKindMock.current = 'cli'; - activateSurface('peer-cli'); + describe('terminal cursor replay', () => { + async function connectToHost(capabilities: Record | null = { terminalCursorReplayV1: true }): Promise { + hostMock.capabilities = capabilities; + activateSurface('peer-host'); const service = freshTerminalService(); await service.connect(); return service; } it('follows replay pages from where the history ended', async () => { - const service = await connectToCliHost(); + const service = await connectToHost(); invokeMock.mockResolvedValueOnce({ data: 'old', nextOffset: 3 }); await service.getHistory('t1'); service.onSessionEvent('t1', vi.fn()); expect(replayMock.created).toHaveLength(1); - expect(replayMock.created[0]).toMatchObject({ sessionId: 't1', offset: 3 }); expect(replayMock.created[0].start).toHaveBeenCalledTimes(1); + expect(replayMock.created[0].follow).toHaveBeenCalledWith(3); + }); + + it('falls back to host kind for a CLI host that predates the capability', async () => { + const service = await connectToHost({ hostKind: 'cli' }); + service.onSessionEvent('t1', vi.fn()); + expect(replayMock.created).toHaveLength(1); + }); + + it('keeps Desktop hosts on terminal_event', async () => { + const service = await connectToHost({ hostKind: 'desktop' }); + invokeMock.mockResolvedValueOnce({ data: 'old', nextOffset: 3 }); + await service.getHistory('t1'); + service.onSessionEvent('t1', vi.fn()); + expect(replayMock.created).toHaveLength(0); + }); + + it('decides again when capabilities resolve after the view subscribed', async () => { + const service = await connectToHost({ hostKind: null }); + invokeMock.mockResolvedValueOnce({ data: 'old', nextOffset: 7 }); + await service.getHistory('t1'); + service.onSessionEvent('t1', vi.fn()); + expect(replayMock.created).toHaveLength(0); + + hostMock.capabilities = { hostKind: 'cli' }; + hostMock.listeners.forEach(listener => listener()); + + expect(replayMock.created).toHaveLength(1); + expect(replayMock.created[0].follow).toHaveBeenCalledWith(7); }); it('routes replayed output through the same terminal event path', async () => { - const service = await connectToCliHost(); + const service = await connectToHost(); const listener = vi.fn(); service.onSessionEvent('t1', listener); @@ -153,7 +201,7 @@ describe('TerminalService device surface switching', () => { }); it('shares one replay per session and stops it with the last listener', async () => { - const service = await connectToCliHost(); + const service = await connectToHost(); const first = service.onSessionEvent('t1', vi.fn()); const second = service.onSessionEvent('t1', vi.fn()); expect(replayMock.created).toHaveLength(1); @@ -164,8 +212,49 @@ describe('TerminalService device surface switching', () => { expect(replayMock.created[0].close).toHaveBeenCalledTimes(1); }); + it('does not leave a second view offset behind for the next replay', async () => { + const service = await connectToHost(); + invokeMock.mockResolvedValueOnce({ data: 'a', nextOffset: 1 }); + await service.getHistory('t1'); + const first = service.onSessionEvent('t1', vi.fn()); + invokeMock.mockResolvedValueOnce({ data: 'ab', nextOffset: 2 }); + await service.getHistory('t1'); + const second = service.onSessionEvent('t1', vi.fn()); + first(); + second(); + + service.onSessionEvent('t1', vi.fn()); + expect(replayMock.created[1].follow).toHaveBeenCalledWith(0); + }); + + it('tracks listed tabs without a view and reports their exit to the tab list', async () => { + const service = await connectToHost(); + const events = vi.fn(); + service.onEvent(events); + invokeMock.mockResolvedValueOnce([{ id: 't1', workspaceId: 'w', name: 'Shell' }]); + await service.listSessions(); + + expect(replayMock.created).toHaveLength(1); + expect(replayMock.created[0].follow).not.toHaveBeenCalled(); + replayMock.created[0].deliver({ type: 'Exit', payload: { session_id: 't1', exit_code: 2 } }); + expect(events).toHaveBeenCalledWith({ type: 'exit', sessionId: 't1', exitCode: 2 }); + }); + + it('returns a tab to lifecycle tracking when its view unmounts', async () => { + const service = await connectToHost(); + service.onEvent(vi.fn()); + invokeMock.mockResolvedValueOnce([{ id: 't1', workspaceId: 'w', name: 'Shell' }]); + await service.listSessions(); + const view = service.onSessionEvent('t1', vi.fn()); + view(); + + expect(replayMock.created).toHaveLength(1); + expect(replayMock.created[0].unfollow).toHaveBeenCalled(); + expect(replayMock.created[0].close).not.toHaveBeenCalled(); + }); + it('stops replaying when the session is destroyed or the surface is left', async () => { - const service = await connectToCliHost(); + const service = await connectToHost(); service.onSessionEvent('t1', vi.fn()); service.onSessionEvent('t2', vi.fn()); @@ -175,17 +264,5 @@ describe('TerminalService device surface switching', () => { await service.disconnect(); expect(replayMock.created[1].close).toHaveBeenCalledTimes(1); }); - - it('keeps Desktop hosts on terminal_event', async () => { - hostKindMock.current = 'desktop'; - activateSurface('peer-desktop'); - const service = freshTerminalService(); - await service.connect(); - invokeMock.mockResolvedValueOnce({ data: 'old', nextOffset: 3 }); - await service.getHistory('t1'); - service.onSessionEvent('t1', vi.fn()); - - expect(replayMock.created).toHaveLength(0); - }); }); }); diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.ts b/src/web-ui/src/tools/terminal/services/TerminalService.ts index 1ae0795dc4..dba03df3a0 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.ts @@ -33,6 +33,7 @@ import type { import { TerminalOriginCache } from './terminalWorkspaceScope'; import { PeerTerminalReplay } from './PeerTerminalReplay'; import { peerConnectionManager } from '@/infrastructure/peer-device/PeerConnectionManager'; +import { usesTerminalCursorReplay } from '@/infrastructure/peer-device/peerCapabilityResolution'; const log = createLogger('TerminalService'); @@ -62,6 +63,11 @@ export class TerminalService { /** Where `getHistory` stopped, so the replay that follows neither repeats nor skips output. */ private readonly replayOffsets = new Map(); + /** Sessions the tab list knows about; their exit must be seen without a mounted view. */ + private trackedSessions = new Set(); + + private unsubscribePeers: (() => void) | null = null; + private constructor() { } @@ -88,6 +94,8 @@ export class TerminalService { }); this.streamScope = scope; this.connected = true; + this.unsubscribePeers = peerConnectionManager.subscribe(() => this.reconcilePeerReplays()); + this.reconcilePeerReplays(); log.debug('Connected to terminal event stream'); })(); @@ -126,34 +134,55 @@ export class TerminalService { } this.streamScope = null; this.connected = false; - this.peerReplays.forEach(replay => replay.close()); - this.peerReplays.clear(); + this.unsubscribePeers?.(); + this.unsubscribePeers = null; + this.trackedSessions.clear(); this.replayOffsets.clear(); + this.reconcilePeerReplays(); } - /** - * Host kind is the negotiated fact here: every CLI host publishes cursor hints - * and only Desktop hosts fan out `terminal_event`, so old hosts of both kinds - * keep working without a new capability key. - */ private usesPeerReplay(): boolean { const { surfaceId } = getActiveSurfaceScope(); - return peerConnectionManager.get(surfaceId)?.getState().capabilities.hostKind === 'cli'; + return usesTerminalCursorReplay(peerConnectionManager.get(surfaceId)?.getState().capabilities); } - private ensurePeerReplay(sessionId: string): void { - if (this.peerReplays.has(sessionId) || !this.isConnected() || !this.usesPeerReplay()) return; - const offset = this.replayOffsets.get(sessionId) ?? 0; - this.replayOffsets.delete(sessionId); - const replay = new PeerTerminalReplay(sessionId, offset, event => this.handleTerminalEvent(event)); - this.peerReplays.set(sessionId, replay); - replay.start(); + /** + * Derive replays from who is listening. Runs again when the host's kind and + * capabilities resolve, because a view can subscribe before they do. + */ + private reconcilePeerReplays(): void { + const active = this.isConnected() && this.usesPeerReplay(); + const wanted = new Set(!active ? [] : [ + ...this.eventListeners.keys(), + ...(this.globalListeners.size > 0 ? this.trackedSessions : []), + ]); + this.peerReplays.forEach((replay, sessionId) => { + if (wanted.has(sessionId)) return; + replay.close(); + this.peerReplays.delete(sessionId); + }); + wanted.forEach(sessionId => { + let replay = this.peerReplays.get(sessionId); + if (!replay) { + replay = new PeerTerminalReplay(sessionId, event => this.handleTerminalEvent(event)); + this.peerReplays.set(sessionId, replay); + replay.start(); + } + if (this.eventListeners.has(sessionId)) { + if (!replay.isFollowing()) replay.follow(this.replayOffsets.get(sessionId) ?? 0); + // Consumed or superseded: a second view must not leave this behind. + this.replayOffsets.delete(sessionId); + } else { + replay.unfollow(); + } + }); } - private stopPeerReplay(sessionId: string): void { - this.peerReplays.get(sessionId)?.close(); - this.peerReplays.delete(sessionId); + private forgetSession(sessionId: string): void { + this.eventListeners.delete(sessionId); + this.trackedSessions.delete(sessionId); this.replayOffsets.delete(sessionId); + this.reconcilePeerReplays(); } private isStreamCurrent(): boolean { @@ -245,8 +274,7 @@ export class TerminalService { new CustomEvent('terminal-session-destroyed', { detail: { sessionId, surfaceId: getActiveSurfaceId() } }) ); } - this.eventListeners.delete(sessionId); - this.stopPeerReplay(sessionId); + this.forgetSession(sessionId); } } @@ -257,21 +285,24 @@ export class TerminalService { this.eventListeners.set(sessionId, listeners); } listeners.add(callback); - this.ensurePeerReplay(sessionId); + this.reconcilePeerReplays(); return () => { listeners?.delete(callback); if (listeners?.size === 0) { this.eventListeners.delete(sessionId); - this.stopPeerReplay(sessionId); + this.reconcilePeerReplays(); } }; } onEvent(callback: TerminalEventCallback): UnsubscribeFunction { this.globalListeners.add(callback); + // A tab list has to see exits before any terminal view has connected. + void this.connect().catch(error => log.warn('Failed to connect terminal events', error)); return () => { this.globalListeners.delete(callback); + this.reconcilePeerReplays(); }; } @@ -332,6 +363,8 @@ export class TerminalService { try { const sessions = await api.invoke('terminal_list'); scope.assertCurrent('terminal_list'); + this.trackedSessions = new Set(sessions.map(session => session.id)); + this.reconcilePeerReplays(); return sessions.map(session => this.projectSession(scope.surfaceId, session)); } catch (error) { log.error('Failed to list sessions', error); @@ -345,8 +378,7 @@ export class TerminalService { await api.invoke('terminal_close', { request }); log.debug('Session closed', { sessionId }); - this.eventListeners.delete(sessionId); - this.stopPeerReplay(sessionId); + this.forgetSession(sessionId); } catch (error) { log.error('Failed to close session', error); throw error; @@ -362,9 +394,9 @@ export class TerminalService { await api.invoke('terminal_shutdown_all'); log.debug('All sessions closed'); this.eventListeners.clear(); - this.peerReplays.forEach(replay => replay.close()); - this.peerReplays.clear(); + this.trackedSessions.clear(); this.replayOffsets.clear(); + this.reconcilePeerReplays(); } catch (error) { log.error('Failed to shutdown all sessions', error); throw error; @@ -374,7 +406,8 @@ export class TerminalService { async getHistory(sessionId: string): Promise { try { const history = await api.invoke('terminal_get_history', { sessionId }); - if (this.usesPeerReplay() && typeof history.nextOffset === 'number') { + // Kept even while the host kind is unknown: the replay decision can come later. + if (typeof history.nextOffset === 'number') { this.replayOffsets.set(sessionId, history.nextOffset); } return history; From 82b6f3be3b6dc333c0ca0099964c8639644fc1bb Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 11:50:26 +0800 Subject: [PATCH 3/3] fix(terminal): reconcile replay for late lifecycle subscribers Co-authored-by: OpenBitFun <318544290+bitfun-ai@users.noreply.github.com> --- src/web-ui/src/infrastructure/peer-device/README.md | 3 +++ .../tools/terminal/services/TerminalService.test.ts | 12 ++++++++++++ .../src/tools/terminal/services/TerminalService.ts | 1 + 3 files changed, 16 insertions(+) diff --git a/src/web-ui/src/infrastructure/peer-device/README.md b/src/web-ui/src/infrastructure/peer-device/README.md index 4f7ec41844..2335d042a6 100644 --- a/src/web-ui/src/infrastructure/peer-device/README.md +++ b/src/web-ui/src/infrastructure/peer-device/README.md @@ -164,6 +164,9 @@ listener alone recovers an interaction emitted before attachment. commands are high priority within each submission burst and use the shared transport admission policy. Both local and SSH-backed PTY cursors on B must notify A without placing raw output into an unbounded event queue. + A host that announces cursors instead of fanning out `terminal_event` + advertises `terminal_cursor_replay_v1`; a CLI host that predates the key is + treated as advertising it, and the choice is re-made once capabilities resolve. Remote `SIGINT` / `SIGTSTP` map to PTY control bytes instead of silently succeeding without affecting the process. diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts index 4f067c1a62..10c726b532 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts @@ -162,6 +162,18 @@ describe('TerminalService device surface switching', () => { expect(replayMock.created[0].follow).toHaveBeenCalledWith(3); }); + it('starts lifecycle tracking when a tab list subscribes after sessions were loaded', async () => { + const service = await connectToHost(); + invokeMock.mockResolvedValueOnce([{ id: 't1', workspaceId: 'w', name: 'Shell' }]); + await service.listSessions(); + expect(replayMock.created).toHaveLength(0); + + service.onEvent(vi.fn()); + await Promise.resolve(); + expect(replayMock.created).toHaveLength(1); + expect(replayMock.created[0].follow).not.toHaveBeenCalled(); + }); + it('falls back to host kind for a CLI host that predates the capability', async () => { const service = await connectToHost({ hostKind: 'cli' }); service.onSessionEvent('t1', vi.fn()); diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.ts b/src/web-ui/src/tools/terminal/services/TerminalService.ts index dba03df3a0..ea4a304e32 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.ts @@ -300,6 +300,7 @@ export class TerminalService { this.globalListeners.add(callback); // A tab list has to see exits before any terminal view has connected. void this.connect().catch(error => log.warn('Failed to connect terminal events', error)); + this.reconcilePeerReplays(); return () => { this.globalListeners.delete(callback); this.reconcilePeerReplays();