Skip to content

Commit bdda67e

Browse files
authored
Merge pull request #3669 from bobleer/bob/cli-peer-capability-gaps
fix(cli-peer): close controller capability gaps on CLI peer hosts
2 parents 32715e4 + 82b6f3b commit bdda67e

41 files changed

Lines changed: 1793 additions & 79 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/architecture/peer-device-mode.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,12 @@ FS) and must not be mixed with Peer Device Mode.
386386
lose its subscription. SSH notification consumers tolerate broadcast lag and
387387
read the retained cursor. Controllers fetch bounded replay pages and render
388388
them in their terminal surface. Account retirement stops that publisher's
389-
notification observers without terminating the PTY.
389+
notification observers without terminating the PTY. `terminal-exit` and
390+
`terminal-closed` on the same stream report the PTY lifecycle; an older CLI
391+
host omits them and the controller learns of a removed session from the
392+
session list. Hosts advertise this path as `terminal_cursor_replay_v1`; the
393+
Desktop controller (`PeerTerminalReplay`) falls back to `host_type` for older
394+
CLI hosts. Desktop hosts keep fanning out `terminal_event`.
390395
- During Peer Mode, controller-local SSH maintenance and selected background
391396
editor/Git/search refreshes retain their existing noise-reduction policy.
392397
These UI refresh policies are separate from durable session synchronization.

‎src/apps/cli/src/logging.rs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ pub(crate) struct CliLogPaths {
3232
}
3333

3434
static ACTIVE_LOG_PATHS: OnceLock<CliLogPaths> = OnceLock::new();
35+
static ACTIVE_LOG_LEVEL: OnceLock<tracing::Level> = OnceLock::new();
3536

3637
struct RotatingFile {
3738
dir: PathBuf,
@@ -254,6 +255,32 @@ pub(crate) fn active_plugin_host_log_path() -> Option<PathBuf> {
254255
.map(|paths| paths.plugin_host_log_path.clone())
255256
}
256257

258+
/// The `get_runtime_logging_info` wire shape shared with Desktop hosts. Logs a
259+
/// CLI does not write (webview, Flow Chat, native startup) report empty paths.
260+
pub(crate) fn runtime_logging_info() -> serde_json::Value {
261+
let paths = ACTIVE_LOG_PATHS
262+
.get()
263+
.cloned()
264+
.unwrap_or_else(|| build_log_paths(&resolve_logs_root()));
265+
let level = ACTIVE_LOG_LEVEL.get().copied().unwrap_or(DEFAULT_LOG_LEVEL);
266+
logging_info_value(&paths, level)
267+
}
268+
269+
fn logging_info_value(paths: &CliLogPaths, level: tracing::Level) -> serde_json::Value {
270+
serde_json::json!({
271+
"effectiveLevel": level.as_str().to_ascii_lowercase(),
272+
"sessionLogDir": paths.session_log_dir.to_string_lossy(),
273+
"earlyStartupLogPath": "",
274+
"nativeStartupTracePath": "",
275+
"appLogPath": paths.app_log_path.to_string_lossy(),
276+
"aiLogPath": paths.ai_log_path.to_string_lossy(),
277+
"flashgrepLogPath": paths.flashgrep_log_path.to_string_lossy(),
278+
"webviewLogPath": "",
279+
"flowChatLogPath": "",
280+
"previousUnexpectedExit": serde_json::Value::Null,
281+
})
282+
}
283+
257284
fn create_rotating_writer(
258285
session_log_dir: &Path,
259286
file_name: &str,
@@ -379,6 +406,7 @@ pub(crate) fn init_file_logging_at(
379406
fs::create_dir_all(session_log_dir).ok();
380407
let paths = build_log_paths(session_log_dir);
381408
let _ = ACTIVE_LOG_PATHS.set(paths.clone());
409+
let _ = ACTIVE_LOG_LEVEL.set(log_level);
382410

383411
let app_writer = create_rotating_writer(session_log_dir, "app");
384412
let ai_writer = create_rotating_writer(session_log_dir, "ai");
@@ -419,6 +447,20 @@ mod tests {
419447
use super::*;
420448
use tracing::Subscriber;
421449

450+
#[test]
451+
fn logging_info_matches_the_controller_wire_shape() {
452+
let info = logging_info_value(
453+
&build_log_paths(Path::new("/logs/session")),
454+
tracing::Level::DEBUG,
455+
);
456+
assert_eq!(info["effectiveLevel"], "debug");
457+
assert_eq!(info["sessionLogDir"], "/logs/session");
458+
assert!(info["appLogPath"].as_str().unwrap().ends_with("app.log"));
459+
assert!(info["aiLogPath"].as_str().unwrap().ends_with("ai.log"));
460+
assert_eq!(info["webviewLogPath"], "");
461+
assert!(info["previousUnexpectedExit"].is_null());
462+
}
463+
422464
fn file_subscriber(
423465
dir: &Path,
424466
level: tracing::Level,
Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
//! `/btw` side-question HostInvoke handlers.
2+
//!
3+
//! The turn runs on the Core coordinator as a child session and flows through
4+
//! the normal agentic event pipeline, so a controller observes it exactly like
5+
//! a side question on a Desktop host. Peer ownership follows the dialog turn
6+
//! contract: it is registered before submission and released if that fails.
7+
8+
use std::future::Future;
9+
use std::sync::{Arc, OnceLock};
10+
use std::time::Duration;
11+
12+
use openbitfun_core::agentic::coordination::{
13+
btw_turn_id, get_global_coordinator, ConversationCoordinator, DialogSubmissionPolicy,
14+
DialogTriggerSource,
15+
};
16+
use openbitfun_core::agentic::core::SessionState;
17+
use openbitfun_core::agentic::image_analysis::ImageContextData;
18+
use openbitfun_core::agentic::side_question::SideQuestionRuntime;
19+
use serde::Deserialize;
20+
use serde_json::{json, Value};
21+
22+
use crate::peer_host::args::{get_string, request_value};
23+
use crate::peer_host::state::{PeerHostState, PeerTurnKey, PeerTurnTracker};
24+
25+
#[derive(Debug, Deserialize)]
26+
#[serde(rename_all = "camelCase")]
27+
struct BtwAskStreamRequest {
28+
request_id: String,
29+
session_id: String,
30+
question: String,
31+
child_session_id: String,
32+
child_session_name: Option<String>,
33+
parent_dialog_turn_id: Option<String>,
34+
parent_turn_index: Option<usize>,
35+
model_id: Option<String>,
36+
#[serde(default)]
37+
image_contexts: Option<Vec<ImageContextData>>,
38+
#[serde(default)]
39+
initial_model_selection: Option<openbitfun_runtime_ports::AgentSessionModelSelection>,
40+
#[serde(default)]
41+
initial_model_target: Option<openbitfun_runtime_ports::AgentSessionModelTargetSelection>,
42+
}
43+
44+
fn side_questions() -> &'static Arc<SideQuestionRuntime> {
45+
static RUNTIME: OnceLock<Arc<SideQuestionRuntime>> = OnceLock::new();
46+
RUNTIME.get_or_init(|| Arc::new(SideQuestionRuntime::new()))
47+
}
48+
49+
fn coordinator() -> Result<Arc<ConversationCoordinator>, String> {
50+
get_global_coordinator()
51+
.ok_or_else(|| "Side questions are unavailable: the agent runtime is not running".into())
52+
}
53+
54+
fn parse_ask_request(request: &Value) -> Result<BtwAskStreamRequest, String> {
55+
let parsed: BtwAskStreamRequest = serde_json::from_value(request.clone())
56+
.map_err(|error| format!("Invalid side question request: {error}"))?;
57+
for (value, name) in [
58+
(&parsed.request_id, "requestId"),
59+
(&parsed.session_id, "sessionId"),
60+
(&parsed.child_session_id, "childSessionId"),
61+
(&parsed.question, "question"),
62+
] {
63+
if value.trim().is_empty() {
64+
return Err(format!("{name} is required"));
65+
}
66+
}
67+
Ok(parsed)
68+
}
69+
70+
/// Own the turn for the duration of `start`, returning the stream generation it
71+
/// was admitted under. A failed start releases the turn: it will never emit the
72+
/// terminal event that would otherwise release it.
73+
async fn start_owned_turn<F, Fut>(
74+
turns: &PeerTurnTracker,
75+
turn: &PeerTurnKey,
76+
start: F,
77+
) -> Result<u64, String>
78+
where
79+
F: FnOnce() -> Fut,
80+
Fut: Future<Output = Result<(), String>>,
81+
{
82+
let generation = turns.register_root(turn.clone())?;
83+
if !turns.is_event_stream_generation_current(generation) {
84+
turns.finish_turn(turn);
85+
return Err("Peer event stream continuity was lost before side question start".to_string());
86+
}
87+
if let Err(error) = start().await {
88+
turns.finish_turn(turn);
89+
return Err(error);
90+
}
91+
Ok(generation)
92+
}
93+
94+
pub(crate) async fn btw_ask_stream(state: &PeerHostState, args: &Value) -> Result<Value, String> {
95+
let raw = request_value(args);
96+
let request = parse_ask_request(raw)?;
97+
// Same reserved-key policy as a Peer dialog turn: routing metadata belongs
98+
// to this host and a controller's copy of it is dropped.
99+
let metadata = match raw.get("userMessageMetadata") {
100+
None | Some(Value::Null) => None,
101+
Some(_) => Some(Value::Object(super::dialog::peer_dialog_metadata(raw)?)),
102+
};
103+
let coordinator = coordinator()?;
104+
let child_session_id = request.child_session_id.trim().to_string();
105+
let turn_id = btw_turn_id(&request.request_id);
106+
let turn = PeerTurnKey::new(child_session_id.clone(), turn_id.clone());
107+
let submit = coordinator.clone();
108+
let child = child_session_id.clone();
109+
let request_id = request.request_id.clone();
110+
let parent_session_id = request.session_id.clone();
111+
let generation = start_owned_turn(&state.turns, &turn, || async move {
112+
submit
113+
.start_btw_turn(
114+
&request_id,
115+
&parent_session_id,
116+
&child,
117+
request.child_session_name.as_deref(),
118+
&request.question,
119+
DialogSubmissionPolicy::for_source(DialogTriggerSource::DesktopUi),
120+
request.model_id.as_deref(),
121+
request.image_contexts,
122+
request.parent_dialog_turn_id.as_deref(),
123+
request.parent_turn_index,
124+
metadata,
125+
request.initial_model_selection,
126+
request.initial_model_target,
127+
)
128+
.await
129+
.map(|_| ())
130+
.map_err(|error| error.to_string())
131+
})
132+
.await?;
133+
if !state.turns.is_event_stream_generation_current(generation) {
134+
coordinator
135+
.cancel_dialog_turn(&child_session_id, &turn_id)
136+
.await
137+
.map_err(|error| {
138+
format!(
139+
"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}"
140+
)
141+
})?;
142+
return Err("Peer event stream lost continuity while starting the side question".into());
143+
}
144+
145+
let runtime = side_questions().clone();
146+
let request_id = request.request_id;
147+
runtime
148+
.register_btw_turn(
149+
request_id.clone(),
150+
child_session_id.clone(),
151+
turn_id.clone(),
152+
)
153+
.await;
154+
tokio::spawn(async move {
155+
// The registration only serves cancellation; release it once the turn settles.
156+
loop {
157+
let processing = coordinator
158+
.get_session_manager()
159+
.get_session(&child_session_id)
160+
.is_some_and(|session| {
161+
matches!(
162+
session.state,
163+
SessionState::Processing { current_turn_id, .. }
164+
if current_turn_id == turn_id
165+
)
166+
});
167+
if !processing {
168+
runtime.remove(&request_id).await;
169+
break;
170+
}
171+
tokio::time::sleep(Duration::from_millis(250)).await;
172+
}
173+
});
174+
Ok(json!({ "ok": true }))
175+
}
176+
177+
pub(crate) async fn btw_cancel(args: &Value) -> Result<Value, String> {
178+
let request_id = get_string(request_value(args), "requestId")?;
179+
if request_id.trim().is_empty() {
180+
return Err("requestId is required".to_string());
181+
}
182+
let runtime = side_questions();
183+
runtime.cancel(&request_id).await;
184+
if let Some(active) = runtime.get_btw_turn(&request_id).await {
185+
coordinator()?
186+
.cancel_dialog_turn(&active.session_id, &active.turn_id)
187+
.await
188+
.map_err(|error| error.to_string())?;
189+
runtime.remove(&request_id).await;
190+
}
191+
Ok(Value::Null)
192+
}
193+
194+
#[cfg(test)]
195+
mod tests {
196+
use super::*;
197+
198+
fn turn() -> PeerTurnKey {
199+
PeerTurnKey::new("child-1", btw_turn_id("request-1"))
200+
}
201+
202+
#[test]
203+
fn the_registered_turn_id_is_the_one_the_coordinator_assigns() {
204+
assert_eq!(btw_turn_id(" request-1 "), "btw-turn-request-1");
205+
}
206+
207+
#[tokio::test]
208+
async fn a_started_turn_stays_owned_until_its_terminal_event() {
209+
let turns = PeerTurnTracker::new();
210+
turns.mark_event_stream_ready();
211+
start_owned_turn(&turns, &turn(), || async { Ok(()) })
212+
.await
213+
.unwrap();
214+
assert!(turns.owns("child-1", Some(&turn().turn_id)));
215+
}
216+
217+
#[tokio::test]
218+
async fn the_turn_is_owned_while_it_starts_and_released_when_that_fails() {
219+
let turns = PeerTurnTracker::new();
220+
turns.mark_event_stream_ready();
221+
let observer = turns.clone();
222+
let error = start_owned_turn(&turns, &turn(), || async move {
223+
assert!(observer.owns("child-1", Some(&turn().turn_id)));
224+
Err("model unavailable".to_string())
225+
})
226+
.await
227+
.unwrap_err();
228+
assert_eq!(error, "model unavailable");
229+
assert!(!turns.owns("child-1", Some(&turn().turn_id)));
230+
}
231+
232+
#[tokio::test]
233+
async fn a_turn_cannot_start_before_the_event_stream_is_ready() {
234+
let turns = PeerTurnTracker::new();
235+
let result = start_owned_turn(&turns, &turn(), || async {
236+
panic!("must not start an unobservable turn")
237+
})
238+
.await;
239+
assert!(result.is_err());
240+
assert!(!turns.owns("child-1", Some(&turn().turn_id)));
241+
}
242+
243+
#[test]
244+
fn ask_request_reads_legacy_payloads_and_ignores_future_fields() {
245+
let request = parse_ask_request(&json!({
246+
"requestId": "request-1",
247+
"sessionId": "parent-1",
248+
"childSessionId": "child-1",
249+
"question": "Why?",
250+
"futureField": true,
251+
}))
252+
.unwrap();
253+
assert!(request.initial_model_selection.is_none());
254+
assert!(request.initial_model_target.is_none());
255+
assert!(request.image_contexts.is_none());
256+
}
257+
258+
#[test]
259+
fn ask_request_accepts_typed_model_targets() {
260+
let request = parse_ask_request(&json!({
261+
"requestId": "request-1",
262+
"sessionId": "parent-1",
263+
"childSessionId": "child-1",
264+
"question": "Why?",
265+
"initialModelTarget": { "selection": { "kind": "pool", "pool_id": "pool-a" } },
266+
}))
267+
.unwrap();
268+
assert!(request.initial_model_target.is_some());
269+
}
270+
271+
#[test]
272+
fn ask_request_rejects_blank_identity_fields() {
273+
for field in ["requestId", "sessionId", "childSessionId", "question"] {
274+
let mut payload = json!({
275+
"requestId": "request-1",
276+
"sessionId": "parent-1",
277+
"childSessionId": "child-1",
278+
"question": "Why?",
279+
});
280+
payload[field] = json!(" ");
281+
let error = parse_ask_request(&payload).unwrap_err();
282+
assert_eq!(error, format!("{field} is required"));
283+
}
284+
}
285+
286+
#[tokio::test]
287+
async fn cancel_of_an_unknown_request_is_a_no_op() {
288+
assert_eq!(
289+
btw_cancel(&json!({ "request": { "requestId": "unknown-request" } }))
290+
.await
291+
.unwrap(),
292+
Value::Null
293+
);
294+
}
295+
}

‎src/apps/cli/src/peer_host/commands/dialog.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,9 @@ fn dialog_submission_slot(
7272
.clone())
7373
}
7474

75-
fn peer_dialog_metadata(request: &Value) -> Result<serde_json::Map<String, Value>, String> {
75+
pub(super) fn peer_dialog_metadata(
76+
request: &Value,
77+
) -> Result<serde_json::Map<String, Value>, String> {
7678
let mut metadata = match request.get("userMessageMetadata") {
7779
Some(Value::Object(metadata)) => metadata.clone(),
7880
Some(Value::Null) | None => serde_json::Map::new(),

0 commit comments

Comments
 (0)