Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 10 additions & 15 deletions src/apps/cli/src/peer_host/commands/btw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@

use std::future::Future;
use std::sync::{Arc, OnceLock};
use std::time::Duration;

use openbitfun_core::agentic::coordination::{
btw_turn_id, 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 openbitfun_core::agentic::side_question::{
BtwTurnWatch, SideQuestionRuntime, BTW_TURN_POLL_INTERVAL,
};
use serde::Deserialize;
use serde_json::{json, Value};

Expand Down Expand Up @@ -152,23 +153,17 @@ pub(crate) async fn btw_ask_stream(state: &PeerHostState, args: &Value) -> Resul
)
.await;
tokio::spawn(async move {
// The registration only serves cancellation; release it once the turn settles.
let mut watch = BtwTurnWatch::new();
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 {
let processing = matches!(
coordinator.get_session_manager().get_session_state(&child_session_id),
Some(SessionState::Processing { current_turn_id, .. }) if current_turn_id == turn_id
);
if watch.should_release(processing) {
runtime.remove(&request_id).await;
break;
}
tokio::time::sleep(Duration::from_millis(250)).await;
tokio::time::sleep(BTW_TURN_POLL_INTERVAL).await;
}
});
Ok(json!({ "ok": true }))
Expand Down
24 changes: 24 additions & 0 deletions src/apps/cli/src/peer_host/commands/terminal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ fn exited_code(status: Option<&SessionStatus>) -> Option<Option<i32>> {
}
}

fn unpublished_exit(status: Option<&SessionStatus>, exit_published: bool) -> Option<Value> {
if exit_published {
return None;
}
exited_code(status).map(|exit_code| json!({"exit_code":exit_code}))
}

fn api() -> Result<TerminalApi, String> {
TerminalApi::from_singleton().map_err(|e| e.to_string())
}
Expand Down Expand Up @@ -269,6 +276,11 @@ pub(crate) async fn create(state: &PeerHostState, args: &Value) -> Result<Value,
tokio::select! {
changed = rx.changed() => {
if changed.is_err() {
// The close can land between exit checks; keep the exit code.
let status = manager.session_status(&id).await;
if let Some(payload) = unpublished_exit(status.as_ref(), exit_published) {
publish_lifecycle(&hub, &id, TERMINAL_EXIT_EVENT, payload).await;
}
publish_lifecycle(&hub, &id, TERMINAL_CLOSED_EVENT, json!({})).await;
break;
}
Expand Down Expand Up @@ -500,6 +512,18 @@ pub(crate) async fn execute(args: &Value) -> Result<Value, String> {
mod tests {
use super::*;

#[test]
fn a_close_reports_an_exit_the_periodic_check_has_not_published() {
let exited = SessionStatus::Exited { exit_code: Some(7) };
assert_eq!(
unpublished_exit(Some(&exited), false),
Some(json!({"exit_code":7}))
);
assert_eq!(unpublished_exit(Some(&exited), true), None);
assert_eq!(unpublished_exit(Some(&SessionStatus::Active), false), None);
assert_eq!(unpublished_exit(None, false), None);
}

#[test]
fn exit_is_reported_only_for_an_exited_session() {
assert_eq!(exited_code(None), None);
Expand Down
28 changes: 11 additions & 17 deletions src/apps/desktop/src/api/btw_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use openbitfun_core::agentic::coordination::{
ConversationCoordinator, DialogSubmissionPolicy, DialogTriggerSource,
};
use openbitfun_core::agentic::image_analysis::ImageContextData;
use openbitfun_core::agentic::side_question::{BtwTurnWatch, BTW_TURN_POLL_INTERVAL};

fn desktop_btw_submission_policy() -> DialogSubmissionPolicy {
DialogSubmissionPolicy::for_source(DialogTriggerSource::DesktopUi)
Expand Down Expand Up @@ -143,27 +144,20 @@ pub async fn btw_ask_stream(
let request_id = request.request_id.clone();
let coordinator = coordinator.inner().clone();
tokio::spawn(async move {
let mut watch = BtwTurnWatch::new();
loop {
let Some(session) = coordinator
.get_session_manager()
.get_session(&child_session_id)
else {
runtime.remove(&request_id).await;
break;
};

match session.state {
openbitfun_core::agentic::core::SessionState::Processing {
let processing = matches!(
coordinator.get_session_manager().get_session_state(&child_session_id),
Some(openbitfun_core::agentic::core::SessionState::Processing {
current_turn_id,
..
} if current_turn_id == turn_id => {
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
_ => {
runtime.remove(&request_id).await;
break;
}
}) if current_turn_id == turn_id
);
if watch.should_release(processing) {
runtime.remove(&request_id).await;
break;
}
tokio::time::sleep(BTW_TURN_POLL_INTERVAL).await;
}
});

Expand Down
4 changes: 3 additions & 1 deletion src/crates/assembly/core/src/agentic/side_question.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Shared `/btw` prompt helpers and compatibility exports for runtime tracking.

use crate::agentic::core::{InternalReminderKind, Message};
pub use openbitfun_agent_runtime::side_question::{ActiveBtwTurn, SideQuestionRuntime};
pub use openbitfun_agent_runtime::side_question::{
ActiveBtwTurn, BtwTurnWatch, SideQuestionRuntime, BTW_TURN_POLL_INTERVAL,
};

pub fn btw_system_reminder() -> &'static str {
r#"This is a side question from the user. You must answer this question directly.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,6 @@ impl PeerHostCapability {
Self::SessionTrajectoryV1,
Self::UserQuestionResponse,
Self::UserQuestionInteractionV1,
// Keep last: Desktop publishes every capability before it.
Self::TerminalCursorReplayV1,
];

Expand Down Expand Up @@ -206,11 +205,50 @@ impl PeerHostCapability {
}
}

/// 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;
/// Desktop publishes everything except `TerminalCursorReplayV1`: it fans out
/// `terminal_event`, and that key selects the other delivery path.
const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[
PeerHostCapability::ModelRoutingV1,
PeerHostCapability::ModelPoolSelectionV1,
PeerHostCapability::BackgroundResultDeliveryV1,
PeerHostCapability::DialogQueueV1,
PeerHostCapability::IdempotentDialogSubmit,
PeerHostCapability::InlineImageAttachmentsV1,
PeerHostCapability::BtwInitialModelSelectionV1,
PeerHostCapability::BtwModelPoolSelectionV1,
PeerHostCapability::ControlConversationV1,
PeerHostCapability::ControlConversationResetV1,
PeerHostCapability::TargetedSessionRollback,
PeerHostCapability::TokenUsageStatistics,
PeerHostCapability::SubscriptionAccountsV1,
PeerHostCapability::SubscriptionProviderAccountsV1,
PeerHostCapability::SubscriptionQuotaV1,
PeerHostCapability::GrokQuotaV1,
PeerHostCapability::SubscriptionModelQuotaV1,
PeerHostCapability::SubscriptionAccountPoolsV1,
PeerHostCapability::SubscriptionAccountFailoverV1,
PeerHostCapability::ModelChannelRoutingV1,
PeerHostCapability::SubscriptionAccountManagementV1,
PeerHostCapability::MiniappAgentContextFilesV1,
PeerHostCapability::MiniappAgentImagesV1,
PeerHostCapability::WslWorkspacesV1,
PeerHostCapability::ComputerUseSharingV1,
PeerHostCapability::ProductControlV1,
PeerHostCapability::RemoteConnectControlV1,
PeerHostCapability::ProductControlNativeV1,
PeerHostCapability::ProductControlPresentationV1,
PeerHostCapability::CancelTool,
PeerHostCapability::ToolCatalog,
PeerHostCapability::ReviewPlatformV1,
PeerHostCapability::ChatMcpCatalogV1,
PeerHostCapability::WorkspaceIconV1,
PeerHostCapability::WorkspaceIdReferencesV1,
PeerHostCapability::WorkspaceHtmlPreviewV1,
PeerHostCapability::WholeSessionCopyV1,
PeerHostCapability::SessionTrajectoryV1,
PeerHostCapability::UserQuestionResponse,
PeerHostCapability::UserQuestionInteractionV1,
];

/// The CLI peer host has no MiniApp runtime, WSL connection setup, host-native
/// ProductControl providers, or presentation surface.
Expand Down Expand Up @@ -296,6 +334,14 @@ mod tests {
capability.key()
);
}
for capability in PeerHostCapability::ALL {
assert_eq!(
advertises(PeerHostKind::Desktop, *capability),
*capability != PeerHostCapability::TerminalCursorReplayV1,
"Desktop advertises everything but the cursor replay path: {}",
capability.key()
);
}
assert_eq!(
advertised_by(PeerHostKind::Desktop).len(),
PeerHostCapability::ALL.len() - 1
Expand Down
71 changes: 70 additions & 1 deletion src/crates/execution/agent-runtime/src/side_question.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;

Expand All @@ -17,6 +18,48 @@ pub struct ActiveBtwTurn {
pub turn_id: String,
}

/// How often a host re-reads whether a registered `/btw` turn still runs.
pub const BTW_TURN_POLL_INTERVAL: Duration = Duration::from_millis(250);
/// How long a turn that has not been seen running yet may keep its registration.
const BTW_TURN_START_GRACE: Duration = Duration::from_secs(5);

/// Decides when a host may drop a `/btw` registration, which only serves
/// `btw_cancel`. A turn accepted a moment ago may not be running yet, and
/// dropping it then would make it uncancellable for its whole run.
#[derive(Debug)]
pub struct BtwTurnWatch {
started_at: Instant,
seen_processing: bool,
}

impl Default for BtwTurnWatch {
fn default() -> Self {
Self::new()
}
}

impl BtwTurnWatch {
pub fn new() -> Self {
Self {
started_at: Instant::now(),
seen_processing: false,
}
}

/// Record one observation; `true` means the turn has settled.
pub fn should_release(&mut self, processing: bool) -> bool {
self.should_release_at(processing, Instant::now())
}

fn should_release_at(&mut self, processing: bool, now: Instant) -> bool {
if processing {
self.seen_processing = true;
return false;
}
self.seen_processing || now.duration_since(self.started_at) >= BTW_TURN_START_GRACE
}
}

impl Default for SideQuestionRuntime {
fn default() -> Self {
Self::new()
Expand Down Expand Up @@ -83,7 +126,33 @@ impl SideQuestionRuntime {

#[cfg(test)]
mod tests {
use super::{ActiveBtwTurn, SideQuestionRuntime};
use super::{ActiveBtwTurn, BtwTurnWatch, SideQuestionRuntime, BTW_TURN_START_GRACE};
use std::time::Duration;

#[test]
fn a_turn_not_running_yet_keeps_its_registration_during_the_grace_period() {
let mut watch = BtwTurnWatch::new();
let start = watch.started_at;
assert!(!watch.should_release_at(false, start));
assert!(!watch.should_release_at(false, start + Duration::from_secs(1)));
}

#[test]
fn a_turn_that_never_runs_is_released_after_the_grace_period() {
let mut watch = BtwTurnWatch::new();
let start = watch.started_at;
assert!(watch.should_release_at(false, start + BTW_TURN_START_GRACE));
}

#[test]
fn a_running_turn_is_released_as_soon_as_it_settles() {
let mut watch = BtwTurnWatch::new();
let start = watch.started_at;
assert!(!watch.should_release_at(false, start));
let long_after = start + BTW_TURN_START_GRACE * 10;
assert!(!watch.should_release_at(true, long_after));
assert!(watch.should_release_at(false, start + Duration::from_millis(1)));
}

#[tokio::test]
async fn registering_same_request_cancels_previous_token() {
Expand Down
60 changes: 60 additions & 0 deletions src/web-ui/src/app/scenes/shell/hooks/useTerminalSessions.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// @vitest-environment jsdom

import React, { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

const service = vi.hoisted(() => ({
connect: vi.fn(async () => {}),
listSessions: vi.fn(),
onEvent: vi.fn(() => () => {}),
setTrackedSessions: vi.fn(),
clearTrackedSessions: vi.fn(),
}));

vi.mock('@/tools/terminal/services/TerminalService', () => ({ getTerminalService: () => service }));
vi.mock('@/shared/services/createManualTerminalSession', () => ({ createManualTerminalSession: vi.fn() }));

import { useTerminalSessions } from './useTerminalSessions';

const scope = {
surfaceId: 'peer-host',
isCurrent: () => true,
assertCurrent: () => {},
key: (...parts: unknown[]) => parts.join(':'),
} as never;
const savedSessionIds = new Set<string>();

function Harness() {
useTerminalSessions({
workspaceId: 'workspace-a', workspacePath: '/a', isRemote: false, currentConnectionId: null,
scope, savedSessionIds,
});
return null;
}

describe('useTerminalSessions', () => {
let root: Root;

beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
root = createRoot(document.createElement('div'));
});

afterEach(() => {
vi.clearAllMocks();
});

it('tracks only the sessions this workspace shows and stops when it unmounts', async () => {
service.listSessions.mockResolvedValue([
{ id: 'mine', workspaceId: 'workspace-a', name: 'A', cwd: '/a' },
{ id: 'other', workspaceId: 'workspace-b', name: 'B', cwd: '/b' },
]);
await act(async () => root.render(<Harness />));

expect(service.setTrackedSessions).toHaveBeenLastCalledWith(expect.anything(), ['mine']);
const owner = service.setTrackedSessions.mock.calls.at(-1)?.[0];
await act(async () => root.unmount());
expect(service.clearTrackedSessions).toHaveBeenCalledWith(owner);
});
});
Loading
Loading