Skip to content

Commit 7e23bdb

Browse files
authored
Merge pull request #3677 from bobleer/bob/cli-peer-followups
fix(cli-peer): tighten terminal tracking and BTW turn watching
2 parents 724bf2f + 23595a4 commit 7e23bdb

12 files changed

Lines changed: 302 additions & 62 deletions

File tree

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

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,16 @@
77
88
use std::future::Future;
99
use std::sync::{Arc, OnceLock};
10-
use std::time::Duration;
1110

1211
use openbitfun_core::agentic::coordination::{
1312
btw_turn_id, get_global_coordinator, ConversationCoordinator, DialogSubmissionPolicy,
1413
DialogTriggerSource,
1514
};
1615
use openbitfun_core::agentic::core::SessionState;
1716
use openbitfun_core::agentic::image_analysis::ImageContextData;
18-
use openbitfun_core::agentic::side_question::SideQuestionRuntime;
17+
use openbitfun_core::agentic::side_question::{
18+
BtwTurnWatch, SideQuestionRuntime, BTW_TURN_POLL_INTERVAL,
19+
};
1920
use serde::Deserialize;
2021
use serde_json::{json, Value};
2122

@@ -152,23 +153,17 @@ pub(crate) async fn btw_ask_stream(state: &PeerHostState, args: &Value) -> Resul
152153
)
153154
.await;
154155
tokio::spawn(async move {
155-
// The registration only serves cancellation; release it once the turn settles.
156+
let mut watch = BtwTurnWatch::new();
156157
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 {
158+
let processing = matches!(
159+
coordinator.get_session_manager().get_session_state(&child_session_id),
160+
Some(SessionState::Processing { current_turn_id, .. }) if current_turn_id == turn_id
161+
);
162+
if watch.should_release(processing) {
168163
runtime.remove(&request_id).await;
169164
break;
170165
}
171-
tokio::time::sleep(Duration::from_millis(250)).await;
166+
tokio::time::sleep(BTW_TURN_POLL_INTERVAL).await;
172167
}
173168
});
174169
Ok(json!({ "ok": true }))

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ fn exited_code(status: Option<&SessionStatus>) -> Option<Option<i32>> {
4040
}
4141
}
4242

43+
fn unpublished_exit(status: Option<&SessionStatus>, exit_published: bool) -> Option<Value> {
44+
if exit_published {
45+
return None;
46+
}
47+
exited_code(status).map(|exit_code| json!({"exit_code":exit_code}))
48+
}
49+
4350
fn api() -> Result<TerminalApi, String> {
4451
TerminalApi::from_singleton().map_err(|e| e.to_string())
4552
}
@@ -269,6 +276,11 @@ pub(crate) async fn create(state: &PeerHostState, args: &Value) -> Result<Value,
269276
tokio::select! {
270277
changed = rx.changed() => {
271278
if changed.is_err() {
279+
// The close can land between exit checks; keep the exit code.
280+
let status = manager.session_status(&id).await;
281+
if let Some(payload) = unpublished_exit(status.as_ref(), exit_published) {
282+
publish_lifecycle(&hub, &id, TERMINAL_EXIT_EVENT, payload).await;
283+
}
272284
publish_lifecycle(&hub, &id, TERMINAL_CLOSED_EVENT, json!({})).await;
273285
break;
274286
}
@@ -500,6 +512,18 @@ pub(crate) async fn execute(args: &Value) -> Result<Value, String> {
500512
mod tests {
501513
use super::*;
502514

515+
#[test]
516+
fn a_close_reports_an_exit_the_periodic_check_has_not_published() {
517+
let exited = SessionStatus::Exited { exit_code: Some(7) };
518+
assert_eq!(
519+
unpublished_exit(Some(&exited), false),
520+
Some(json!({"exit_code":7}))
521+
);
522+
assert_eq!(unpublished_exit(Some(&exited), true), None);
523+
assert_eq!(unpublished_exit(Some(&SessionStatus::Active), false), None);
524+
assert_eq!(unpublished_exit(None, false), None);
525+
}
526+
503527
#[test]
504528
fn exit_is_reported_only_for_an_exited_session() {
505529
assert_eq!(exited_code(None), None);

‎src/apps/desktop/src/api/btw_api.rs‎

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use openbitfun_core::agentic::coordination::{
1616
ConversationCoordinator, DialogSubmissionPolicy, DialogTriggerSource,
1717
};
1818
use openbitfun_core::agentic::image_analysis::ImageContextData;
19+
use openbitfun_core::agentic::side_question::{BtwTurnWatch, BTW_TURN_POLL_INTERVAL};
1920

2021
fn desktop_btw_submission_policy() -> DialogSubmissionPolicy {
2122
DialogSubmissionPolicy::for_source(DialogTriggerSource::DesktopUi)
@@ -143,27 +144,20 @@ pub async fn btw_ask_stream(
143144
let request_id = request.request_id.clone();
144145
let coordinator = coordinator.inner().clone();
145146
tokio::spawn(async move {
147+
let mut watch = BtwTurnWatch::new();
146148
loop {
147-
let Some(session) = coordinator
148-
.get_session_manager()
149-
.get_session(&child_session_id)
150-
else {
151-
runtime.remove(&request_id).await;
152-
break;
153-
};
154-
155-
match session.state {
156-
openbitfun_core::agentic::core::SessionState::Processing {
149+
let processing = matches!(
150+
coordinator.get_session_manager().get_session_state(&child_session_id),
151+
Some(openbitfun_core::agentic::core::SessionState::Processing {
157152
current_turn_id,
158153
..
159-
} if current_turn_id == turn_id => {
160-
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
161-
}
162-
_ => {
163-
runtime.remove(&request_id).await;
164-
break;
165-
}
154+
}) if current_turn_id == turn_id
155+
);
156+
if watch.should_release(processing) {
157+
runtime.remove(&request_id).await;
158+
break;
166159
}
160+
tokio::time::sleep(BTW_TURN_POLL_INTERVAL).await;
167161
}
168162
});
169163

‎src/crates/assembly/core/src/agentic/side_question.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
//! Shared `/btw` prompt helpers and compatibility exports for runtime tracking.
22
33
use crate::agentic::core::{InternalReminderKind, Message};
4-
pub use openbitfun_agent_runtime::side_question::{ActiveBtwTurn, SideQuestionRuntime};
4+
pub use openbitfun_agent_runtime::side_question::{
5+
ActiveBtwTurn, BtwTurnWatch, SideQuestionRuntime, BTW_TURN_POLL_INTERVAL,
6+
};
57

68
pub fn btw_system_reminder() -> &'static str {
79
r#"This is a side question from the user. You must answer this question directly.

‎src/crates/contracts/product-domains/src/remote_surface/capabilities.rs‎

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,6 @@ impl PeerHostCapability {
153153
Self::SessionTrajectoryV1,
154154
Self::UserQuestionResponse,
155155
Self::UserQuestionInteractionV1,
156-
// Keep last: Desktop publishes every capability before it.
157156
Self::TerminalCursorReplayV1,
158157
];
159158

@@ -211,11 +210,50 @@ impl PeerHostCapability {
211210
}
212211
}
213212

214-
/// Desktop fans out `terminal_event`, so it has everything except the cursor
215-
/// replay path, which `ALL` keeps last.
216-
const DESKTOP_CAPABILITIES: &[PeerHostCapability] = PeerHostCapability::ALL
217-
.split_at(PeerHostCapability::ALL.len() - 1)
218-
.0;
213+
/// Desktop publishes everything except `TerminalCursorReplayV1`: it fans out
214+
/// `terminal_event`, and that key selects the other delivery path.
215+
const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[
216+
PeerHostCapability::ModelRoutingV1,
217+
PeerHostCapability::ModelPoolSelectionV1,
218+
PeerHostCapability::BackgroundResultDeliveryV1,
219+
PeerHostCapability::DialogQueueV1,
220+
PeerHostCapability::IdempotentDialogSubmit,
221+
PeerHostCapability::InlineImageAttachmentsV1,
222+
PeerHostCapability::BtwInitialModelSelectionV1,
223+
PeerHostCapability::BtwModelPoolSelectionV1,
224+
PeerHostCapability::ControlConversationV1,
225+
PeerHostCapability::ControlConversationResetV1,
226+
PeerHostCapability::TargetedSessionRollback,
227+
PeerHostCapability::TokenUsageStatistics,
228+
PeerHostCapability::SubscriptionAccountsV1,
229+
PeerHostCapability::SubscriptionProviderAccountsV1,
230+
PeerHostCapability::SubscriptionQuotaV1,
231+
PeerHostCapability::GrokQuotaV1,
232+
PeerHostCapability::SubscriptionModelQuotaV1,
233+
PeerHostCapability::SubscriptionAccountPoolsV1,
234+
PeerHostCapability::SubscriptionAccountFailoverV1,
235+
PeerHostCapability::ModelChannelRoutingV1,
236+
PeerHostCapability::SubscriptionAccountManagementV1,
237+
PeerHostCapability::MiniappAgentContextFilesV1,
238+
PeerHostCapability::MiniappAgentImagesV1,
239+
PeerHostCapability::WslWorkspacesV1,
240+
PeerHostCapability::ComputerUseSharingV1,
241+
PeerHostCapability::ProductControlV1,
242+
PeerHostCapability::RemoteConnectControlV1,
243+
PeerHostCapability::ProductControlNativeV1,
244+
PeerHostCapability::ProductControlPresentationV1,
245+
PeerHostCapability::CancelTool,
246+
PeerHostCapability::ToolCatalog,
247+
PeerHostCapability::ReviewPlatformV1,
248+
PeerHostCapability::ChatMcpCatalogV1,
249+
PeerHostCapability::WorkspaceIconV1,
250+
PeerHostCapability::WorkspaceIdReferencesV1,
251+
PeerHostCapability::WorkspaceHtmlPreviewV1,
252+
PeerHostCapability::WholeSessionCopyV1,
253+
PeerHostCapability::SessionTrajectoryV1,
254+
PeerHostCapability::UserQuestionResponse,
255+
PeerHostCapability::UserQuestionInteractionV1,
256+
];
219257

220258
/// The CLI peer host has no MiniApp runtime, WSL or SSH connection setup, host-native
221259
/// ProductControl providers, or presentation surface.
@@ -301,6 +339,14 @@ mod tests {
301339
capability.key()
302340
);
303341
}
342+
for capability in PeerHostCapability::ALL {
343+
assert_eq!(
344+
advertises(PeerHostKind::Desktop, *capability),
345+
*capability != PeerHostCapability::TerminalCursorReplayV1,
346+
"Desktop advertises everything but the cursor replay path: {}",
347+
capability.key()
348+
);
349+
}
304350
assert_eq!(
305351
advertised_by(PeerHostKind::Desktop).len(),
306352
PeerHostCapability::ALL.len() - 1

‎src/crates/execution/agent-runtime/src/side_question.rs‎

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use std::collections::HashMap;
44
use std::sync::Arc;
5+
use std::time::{Duration, Instant};
56
use tokio::sync::Mutex;
67
use tokio_util::sync::CancellationToken;
78

@@ -17,6 +18,48 @@ pub struct ActiveBtwTurn {
1718
pub turn_id: String,
1819
}
1920

21+
/// How often a host re-reads whether a registered `/btw` turn still runs.
22+
pub const BTW_TURN_POLL_INTERVAL: Duration = Duration::from_millis(250);
23+
/// How long a turn that has not been seen running yet may keep its registration.
24+
const BTW_TURN_START_GRACE: Duration = Duration::from_secs(5);
25+
26+
/// Decides when a host may drop a `/btw` registration, which only serves
27+
/// `btw_cancel`. A turn accepted a moment ago may not be running yet, and
28+
/// dropping it then would make it uncancellable for its whole run.
29+
#[derive(Debug)]
30+
pub struct BtwTurnWatch {
31+
started_at: Instant,
32+
seen_processing: bool,
33+
}
34+
35+
impl Default for BtwTurnWatch {
36+
fn default() -> Self {
37+
Self::new()
38+
}
39+
}
40+
41+
impl BtwTurnWatch {
42+
pub fn new() -> Self {
43+
Self {
44+
started_at: Instant::now(),
45+
seen_processing: false,
46+
}
47+
}
48+
49+
/// Record one observation; `true` means the turn has settled.
50+
pub fn should_release(&mut self, processing: bool) -> bool {
51+
self.should_release_at(processing, Instant::now())
52+
}
53+
54+
fn should_release_at(&mut self, processing: bool, now: Instant) -> bool {
55+
if processing {
56+
self.seen_processing = true;
57+
return false;
58+
}
59+
self.seen_processing || now.duration_since(self.started_at) >= BTW_TURN_START_GRACE
60+
}
61+
}
62+
2063
impl Default for SideQuestionRuntime {
2164
fn default() -> Self {
2265
Self::new()
@@ -83,7 +126,33 @@ impl SideQuestionRuntime {
83126

84127
#[cfg(test)]
85128
mod tests {
86-
use super::{ActiveBtwTurn, SideQuestionRuntime};
129+
use super::{ActiveBtwTurn, BtwTurnWatch, SideQuestionRuntime, BTW_TURN_START_GRACE};
130+
use std::time::Duration;
131+
132+
#[test]
133+
fn a_turn_not_running_yet_keeps_its_registration_during_the_grace_period() {
134+
let mut watch = BtwTurnWatch::new();
135+
let start = watch.started_at;
136+
assert!(!watch.should_release_at(false, start));
137+
assert!(!watch.should_release_at(false, start + Duration::from_secs(1)));
138+
}
139+
140+
#[test]
141+
fn a_turn_that_never_runs_is_released_after_the_grace_period() {
142+
let mut watch = BtwTurnWatch::new();
143+
let start = watch.started_at;
144+
assert!(watch.should_release_at(false, start + BTW_TURN_START_GRACE));
145+
}
146+
147+
#[test]
148+
fn a_running_turn_is_released_as_soon_as_it_settles() {
149+
let mut watch = BtwTurnWatch::new();
150+
let start = watch.started_at;
151+
assert!(!watch.should_release_at(false, start));
152+
let long_after = start + BTW_TURN_START_GRACE * 10;
153+
assert!(!watch.should_release_at(true, long_after));
154+
assert!(watch.should_release_at(false, start + Duration::from_millis(1)));
155+
}
87156

88157
#[tokio::test]
89158
async fn registering_same_request_cancels_previous_token() {
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// @vitest-environment jsdom
2+
3+
import React, { act } from 'react';
4+
import { createRoot, type Root } from 'react-dom/client';
5+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
6+
7+
const service = vi.hoisted(() => ({
8+
connect: vi.fn(async () => {}),
9+
listSessions: vi.fn(),
10+
onEvent: vi.fn(() => () => {}),
11+
setTrackedSessions: vi.fn(),
12+
clearTrackedSessions: vi.fn(),
13+
}));
14+
15+
vi.mock('@/tools/terminal/services/TerminalService', () => ({ getTerminalService: () => service }));
16+
vi.mock('@/shared/services/createManualTerminalSession', () => ({ createManualTerminalSession: vi.fn() }));
17+
18+
import { useTerminalSessions } from './useTerminalSessions';
19+
20+
const scope = {
21+
surfaceId: 'peer-host',
22+
isCurrent: () => true,
23+
assertCurrent: () => {},
24+
key: (...parts: unknown[]) => parts.join(':'),
25+
} as never;
26+
const savedSessionIds = new Set<string>();
27+
28+
function Harness() {
29+
useTerminalSessions({
30+
workspaceId: 'workspace-a', workspacePath: '/a', isRemote: false, currentConnectionId: null,
31+
scope, savedSessionIds,
32+
});
33+
return null;
34+
}
35+
36+
describe('useTerminalSessions', () => {
37+
let root: Root;
38+
39+
beforeEach(() => {
40+
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
41+
root = createRoot(document.createElement('div'));
42+
});
43+
44+
afterEach(() => {
45+
vi.clearAllMocks();
46+
});
47+
48+
it('tracks only the sessions this workspace shows and stops when it unmounts', async () => {
49+
service.listSessions.mockResolvedValue([
50+
{ id: 'mine', workspaceId: 'workspace-a', name: 'A', cwd: '/a' },
51+
{ id: 'other', workspaceId: 'workspace-b', name: 'B', cwd: '/b' },
52+
]);
53+
await act(async () => root.render(<Harness />));
54+
55+
expect(service.setTrackedSessions).toHaveBeenLastCalledWith(expect.anything(), ['mine']);
56+
const owner = service.setTrackedSessions.mock.calls.at(-1)?.[0];
57+
await act(async () => root.unmount());
58+
expect(service.clearTrackedSessions).toHaveBeenCalledWith(owner);
59+
});
60+
});

0 commit comments

Comments
 (0)